Laravel 9 File Upload via API

Laravel 9 File Upload via API Example

Laravel 9 File Upload via API Example

In this post we will give you Laravel 9 File Upload via API Example, hear for Laravel 9 File Upload via API we will give you details about it.

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

In this example post, you will learn how to upload files via API using postman in laravel 9. And also how to validate file type in laravel API controller.

This is very easy to upload files via laravel API using postman example will show you each thing steps by step.

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 webserver directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 9 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 9 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 the command prompt and navigate to your project by using the following command:

cd / LaravelApiFile

Then create a 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 9 file upload tutorial app, which is located inside the following locations:

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

So, find create_files_table.php file inside LaravelApiFile/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 an 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 LaravelApiFile/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:2305',

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 the development server for your laravel file upload via API application:

php artisan serve

Step 7 – Run this App On PostMan
In step 7, open the postman app and call API with file parameter:

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

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

Hope this code and post will helped you for implement Laravel 9 File Upload via API Tutorial. if you need any help or any feedback give it in the comment section or you have a good idea about this post you can give it a comment section. Your comment will help us to help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs https://onlinecode.org