Laravel 8 Image Upload API Using Postman

Laravel

199

w3alert.com

28-12-2020


Laravel 8 image uploading via apis with postman tutorial. In this example, you will learn how to upload image using apis with postman into the database table and folder in laravel 8 app with validatin.

Laravel 8 Image Uploading Via Api Tutorial

  • Install Laravel 8 App
  • Configure Database Detail
  • Create Model and Migration
  • Run Migration
  • Create Routes
  • Generate Controller By Artisan
  • Start Development Server

Install Laravel 8 App

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

composer create-project laravel/laravel blog –-prefer-dist

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=root

Create Model and Migration

Next, I need to create a model and migration in your laravel web application using the php artisan make:model model_name -m. So run the following command in your project root directory.

Go to the command prompt

cd/project_root_directory

php artisan make:model Image -m

after that, go to database/migrations/ and find created migration file and add fields, as you want to in your database table.

Your migration file looks like:

<?php

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

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

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

Run Migration

Next, go to command prompt and run the following command:

php artisan migrate
OR
php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Create Routes

Next step, go to routes/api.php file and update the following routes into your file:

use App\Http\Controllers\API\ImageController;

Route::post('image-upload-api', [ImageController::class, 'store']);

Generate Controller By Artisan

Now, you need to generate or create a controller file using artisan command, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller API\ImageController

In this controller file, I will create method for uploading image into database and folder in laravel 8 app.

After that, go to App/Http/Controllers/API directory and find the created ImageController file and update the following code into your file:

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Validator,Redirect,Response,File;
use App\Models\Image;
use Validator;

class ImageController extends Controller
{

    public function store(Request $request)
    {

       $validator = Validator::make($request->all(), 
              [ 
               'user_id' => 'required',
               'file' => 'required|mimes:jpeg,png,jpg,gif,svg,doc,docx,pdf|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/images');

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

 
    }
}

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

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

http://localhost:8000/image-upload-api