Laravel 7 File Upload Via API Example From Scratch

Laravel 7 File Upload Via API Example From Scratch

Laravel 7 file upload via API using postman example tutorial. Here, you will learn how to upload files via API using postman in laravel app.

As well as you can upload images, files via API using postman in laravel apps and also you can upload images/files via api using ajax in laravel apps.

If you work with laravel apis and want to upload files or images using postman or ajax. And also want to validate files or images before uploading to server via API or ajax in laravel.

So this tutorial will guide you step by step on how to upload file via API using postman and ajax in laravel with validation.

Laravel Uploading Files Via API Using Postman Example

Follow the below given following steps and upload file via API using postman with validation in laravel app:

  • Step 1: Install Laravel New App
  • Step 2: Add Database Credentials
  • Step 3: Generate Migration & Model
  • Step 4: Create Routes For File
  • Step 5: Generate Controller by Artisan
  • Step 6: Run Development Server
  • Step 7: Laravel Upload File Via Api Using PostMan

Step 1: Install Laravel New App

First of all, open your terminal and run the following command to install or download laravel fresh application setup for uploading files via laravel api:

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

Step 2: Add Database Credentials

Next, Navigate to your downloaded laravel app root directory and open .env file. Then add your database details in .env file, as follow:

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=here your database name here
 DB_USERNAME=here database username here
 DB_PASSWORD=here database password here

Step 3: Generate Migration & Model

In this step, open a command prompt and run the following command:

php artisan make:model Documents -m

This command will create one model name file and as well as one migration file for the Documents table.

Then Navigate to database/migrations folder and open create_documents_table.php. Then update the following code into create_documents_table.php:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatedocumentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('documents', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->integer('user_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('documents');
    }
}

After that, run the following command to migrate the table into your select database:

php artisan migrate

Step 4: Create Route For File

In this step, Navigate to the app/routes folder and open api.php file. Then update the following routes into your api.php file:

 Route::prefix('v1')->group(function(){
  Route::post('store-file', '[email protected]');
 });

Step 5: Generate Controller by Artisan

In this step, open your terminal and run the following command:

php artisan make:controller Api\DocumentController

Note that, This command will create a controller named DocumentController.php file.

Now app/controllers/Api folder and open DocumentController.php. Then update the following file uploading methods into your DocumentController.php file:

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Validator,Redirect,Response,File;
use App\Document;
use Validator;
class DocumentController extends Controller
{

    public function store(Request $request)
    {

       $validator = Validator::make($request->all(), 
              [ 
              'user_id' => 'required',
              'file' => 'required|mimes:doc,docx,pdf,txt|max:2048',
             ]);   

	if ($validator->fails()) {          
            return response()->json(['error'=>$validator->errors()], 401);                        
         }  

 
        if ($files = $request->file('file')) {
            
            //store file into document folder
            $file = $request->file->store('public/documents');

            //store your file into database
            $document = new Document();
            $document->title = $file;
            $document->user_id = $request->user_id;
            $document->save();
             
            return response()->json([
                "success" => true,
                "message" => "File successfully uploaded",
                "file" => $file
            ]);
 
        }

 
    }
}

If you want to upload images via api instead of files in laravel. So you can change in validation rules on the controller file, as follow:

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

Step 6: Run Development Server

In this step, run the following command to start the development server:

 php artisan serve

Step 7: Laravel Upload File Via Api Using PostMan

Finally, uploading files via laravel APIs using postman app. So start postman app and use the following URL to upload files via api in laravel app:

http://localhost:8000/store-file

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

In this upload file using rest API laravel example tutorial, you have learned how to upload a file using rest api laravel apps using postman.

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Livewire, Codeigniter, Vue JS, Angular JS, React Js, WordPress, and Bootstrap from a starting stage. As well as demo example.

One reply to Laravel 7 File Upload Via API Example From Scratch

  1. hi, could make some tutorial about LARAVEL7 use ‘SUMMER NOTE’ with drag&drop multiple image upload ?, thanks

Leave a Reply

Your email address will not be published. Required fields are marked *