Avenue Code Snippets

The Best Way to Use Request Validation in Laravel REST API

Written by Luiz Henrique Santos | 5/11/22 5:00 PM

When you're working with a REST API, it's very important to guarantee that the data you're receiving match some defined rules and will not break the system. How do we do this? Meet Laravel's request validation tool. 

Introduction

Laravel is an open-source PHP framework that has a very good tool for request validations. You can use it to validate a lot of structures and rules, such as files, arrays, alpha, numeric, and others. Let's take a look at how these validations are carried out in most cases.

Simple Validations

To illustrate simple validations, let’s start by creating a route in routes/api.php to represent a POST request to create a post:

<?php

use App\Http\Controllers\PostController;



Route::post('/post', [PostController::class, 'store']);

Next, let's create a controller to handle the request and perform all necessary validations. In the code below, we created a store method that uses the request as a parameter. Inside this function, the method validate is used to check if the requested data match some criteria defined in the parameter array. In this example, the title is required, it has to be unique considering the table post in the database, and it can not exceed 255 characters.

<?php



namespace App\Http\Controllers;



use App\Http\Controllers\Controller;

use Illuminate\Http\Request;



class PostController extends Controller

{

    public function store(Request $request)

    {

       $validated = $request->validate([

          'title' => 'required|unique:posts|max:255',

          'body' => 'required',

       ]);

    }

}

Depending on the size of the request, PostController may increase its size and be too complex. As a developer, I like to keep the controller as simple as possible. It should be responsible for receiving the request, validating it, and getting its parameters to pass them to a proper service. So, how can we keep it simple and validate all data?

The Best Way to Use Request Validation

A good development principle is to keep code simple, splitting responsibilities into classes and files. So a better way to validate requests is to create a custom request validation class and insert it as a dependency injection into the controller. The code below does the same validations as the code above:

Controller:

<?php



namespace App\Http\Controllers;



use App\Http\Controllers\Controller;

use App\Http\Requests\PostStoreRequest;



class PostController extends Controller

{

    public function store(PostStoreRequest $request)

    {

//At this point all data is validated,just need to call proper service with $request data

    }

}

PostStoreRequest:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

use Illuminate\Http\Exceptions\HttpResponseException;

use Illuminate\Contracts\Validation\Validator;



class PostStoreRequest extends FormRequest

{

    public function rules()

    {

        return [

            'title' => 'required|unique:posts|max:255',

            'body' => 'required',

        ];

    }



    public function failedValidation(Validator $validator)

    {

        throw new HttpResponseException(response()->json([

            'success'   => false,

            'message'   => 'Validation errors',

            'data'      => $validator->errors()

        ]));

    }



    public function messages()

    {

        return [

            ‘title.required' => ‘Title is required',

            'body.required' => ‘Body is required'

        ];

    }

}

In the code above, all field validations are done in a separate file. The "function rules" is responsible for all field validations, so all possible rules can be checked on. The function failedValidation handles the API return when the validation fails. In function messages, it is possible to customize errors messages for each field rule.

Conclusion

Request validations in Laravel are a very helpful development tool. Writing the validation in a dedicated class makes your controller cleaner and splits the responsibilities of your components. 

 

References

Laravel Validation Documentation. Laravel.

"Available Validation Rules." Laravel.

"How to validate an API request in laravel." Shail Gandhi. Medium.

"The Smart Way To Handle Request Validation In Laravel." KashYap Merai. Medium.