Laravel 9 File Upload via API Example Tutorial

Laravel 9 file uploading via api using postman; Through this tutorial, i am going to show you how to upload file via api using postman in laravel 9 with validation.

Laravel 9 Uploading Files Via API Using Postman Example validate files type like pdf, txt, excel, xlsx, csv before upload into database and public storage directory.

When you call this api of file uploading via api using postman in laravel will look like:

Laravel 9 File Upload API using Postman

Use the below given simple steps to file uploading in laravel 9 app:

  • Step 1 – Install Laravel 9 Application
  • Step 2 – Configuring Database Details
  • Step 3 – Create File Model & Migration
  • Step 4 – Create API File Upload Routes
  • Step 5 – Creating API File Upload Controller
  • Step 6 – Start Development Server
  • Step 7 – Run this App On PostMan

Step 1 – Install Laravel 9 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

composer create-project --prefer-dist laravel/laravel LaravelApiFile

Step 2 – Configuring Database Details

In step 2, open your downloaded laravel app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Create File Model & Migration

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaravelApiFile

Then create model and migration file by using the following command:

php artisan make:model File -m

The above command will create two files into your laravel file upload tutorial app, which is located inside the following locations:

  • /app/Models/File.php
  • /database/migrations/create_files_table.php

So, find create_files_table.php file inside /database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('path');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create API File Upload Routes

In step 4, open your api.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Controllers\API\FileUploadController;

Route::post('uploading-file-api', [FileUploadController::class, 'upload']);

Step 5 – Creating API File Upload Controller

In step 5, create API file upload controller by using the following command:

php artisan make:controller API\FileUploadController

The above command will create FileUploadController.php file, which is located inside /app/Http/Controllers/API directory.

The following laravel validation rules will validate file before upload/save into database:

       $validator = Validator::make($request->all(),[ 
              'file' => 'required|mimes:doc,docx,pdf,txt,csv|max:2048',
        ]);   
 
        if($validator->fails()) {          
            
            return response()->json(['error'=>$validator->errors()], 401);                        
         }  

Note that, if you want to upload image file via api using postman. So, you can do it with adding the following validation rules with $validator:

'file'  => 'required|mimes:png,jpg,jpeg,gif|max:2048',

Then add the below given code into API\FileController.php file:

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;

use App\Models\File;

use Validator;

use Illuminate\Http\Request;

class FileUploadController extends Controller
{
    public function upload(Request $request)
    {
 
       $validator = Validator::make($request->all(),[ 
              'file' => 'required|mimes:doc,docx,pdf,txt,csv|max:2048',
        ]);   
 
        if($validator->fails()) {          
            
            return response()->json(['error'=>$validator->errors()], 401);                        
         }  
 
  
        if ($file = $request->file('file')) {


            $path = $file->store('public/files');
            $name = $file->getClientOriginalName();
 
            //store your file into directory and db
            $save = new File();
            $save->name = $file;
            $save->store_path= $path;
            $save->save();
              
            return response()->json([
                "success" => true,
                "message" => "File successfully uploaded",
                "file" => $file
            ]);
  
        }
 
  
    }
}

The following single line of code will upload files inside storage/app/public/files directory:

        $path = $request->file('file')->store('public/files');

Step 6 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel file upload via api application:

php artisan serve

Step 7 – Run this App On PostMan

In step 7, open postman app and call api with file parameter:

http://127.0.0.1:8000/uploading-file-api

The uploading file via api using postman will look like:

Note that, in this example, the file will be upload on the following path – storage/app/public/files.

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.