Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

api validation in laravel

How to validate API in Laravel?

Today, I will give you an example of “How to Validate API in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

laravel rest api validation example

laravel api validation response

In this example, we will create a POST Rest API request and test API in Postman, and using this post API we will store user data into our database using Request Validation.

So let’s Create a Post API in Laravel

Generating Migration

php artisan make:migration create_apivalidation_examples_table

Migration Structures

<?php

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

class CreateApivalidationExamplesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('apivalidation_examples', function (Blueprint $table) {
            $table->id();
            $table->string('name',25);
            $table->string('email',25);
            $table->string('address');
            $table->timestamps();
        });
    }

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

Run Migration

php artisan migrate
How to validate API in Laravel?
How to validate API in Laravel?

Create a Model

php artisan make:model ApivalidationExample

app\Models\ApivalidationExample.php

<?php

namespace App\Models;

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


class ApivalidationExample extends Model
{
    use HasFactory;
    protected $table="apivalidation_examples";
}

Create a Controller

php artisan make:controller ApiValidationExampleController

Define Routes

routes\api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ApiValidationExampleController;


/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});


Route::post('/user/store',[ApiValidationExampleController::class, 'store'])->name('user.store');

app\Http\Controllers\ApiValidationExampleController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ApivalidationExample;
use Validator;

class ApiValidationExampleController extends Controller
{
    
    function store(Request $request){

        $rules=array(
            'name'  =>"required|min:2|max:30",
            'email' =>"required|min:5|max:30",
            'address' =>"required",
        );
        $validator=Validator::make($request->all(),$rules);
        if($validator->fails())
        {
            return $validator->errors();
        }
        else{
        $data = new ApivalidationExample();
        $data->name = $request->name;
        $data->email = $request->email;
        $data->address = $request->address;
        $result = $data->save();

        if($result){
            return ["Result"=>"Data has been saved"];
        }

        else{
            return ["Result"=>"Operation failed"];
        }
      }
    }
}

Recommended article: The Smart Way To Handle Request Validation In Laravel.

Just import the validator class in the controller, and we return a validation error in API.

Test the API using Postman

http://127.0.0.1:8000/api/user/store

Output:-

return validation error in laravel api

laravel api validation response

laravel 8 request validation api

In this article, we learned “how to validate API requests in Laravel”, I hope this article will help you with your Laravel application Project.

Read also: Search API in Laravel.