Laravel 9 Rest Api Image Upload with Validation Example

In this tutorial we will see how to upload image file via rest api in laravel 9. we also see laravel image validation.


Laravel 9 Rest Api image upload

Step 1: Create Laravel Project

Step 2: Setup Databases

Step 3: Create Image Model and Migration

Step 4: Create Image Api Controller and Route

Step 5: Migrate database & Storage links

Step 6: Setup and Test Api


Step 1: Create Laravel Project

Run below command in your terminal to create laravel project.

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


Step 2: Setup Databases

Now, fill the details in env file.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password


Step 3: Create Image Model and Migration

Run shorthand command to create image modal, migration and controller.

php artisan make:model Image -mc 


images_table.php

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


app/Models/Image.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;
    protected $fillable = [
        'image'
    ];
}


Step 4: Create Image Api Controller and Route

There are two way you can store and validate image file.

1) First Way to Image file upload with validation

Create Image Api Controller by running below command.

php artisan make:controller Api/ImageController  


First you need to import Image class and import use Symfony\Component\HttpFoundation\Response;

app/Http/Controllers/Api/ImageController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Image;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;


class ImageController extends Controller
{
    public function imageStore(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
        ]);
        $image_path = $request->file('image')->store('image', 'public');

        $data = Image::create([
            'image' => $image_path,
        ]);

        return response($data, Response::HTTP_CREATED);
    }
}


2) Second Way to Image file upload with validation

Create image store request for validation.

php artisan make:request ImageStoreRequest 


app/Http/Controllers/Requests/ImageStoreRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ImageStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
        ];
    }
}


Now you need remove Request and import ImageStoreRequest for image validation.

app/Http/Controllers/Api/ImageController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\ImageStoreRequest;
use App\Models\Image;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;


class ImageController extends Controller
{
    public function imageStore(ImageStoreRequest $request)
    {

        $validatedData = $request->validated();
        $validatedData['image'] = $request->file('image')->store('image');
        $data = Image::create($validatedData);

        return response($data, Response::HTTP_CREATED);
    }
}


Now you need to set api.php route.

routes/api.php

<?php

use App\Http\Controllers\Api\ImageController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;


Route::post('image',[ImageController::class, 'imageStore']);


Step 5: Migrate database & Storage links

run migrate database

php artisan migrate

Storage links to public directory.

php artisan storage:link


Step 6: Setup and Test Api

First you need go body section then select form filed for api image upload. then hit http://localhost:8000/api/image with post method.and set header to Accept to application/json

http://localhost:8000/api/image

set header

laravel 9 api image upload validation set

laravel 9 api image upload validation set


Laravel 9 rest api Image upload validation test.

laravel 9 rest api image validation

laravel 9 rest api image validation

Laravel 9 rest api Image upload successful.

laravel 9 api image upload

laravel 9 api image upload