How to validate data in Laravel, A Form Request Validation example for Laravel 7/8/9/10

In this simple tutorial I will show you an example of how to perform form request validation using Laravel’s Validator Facade.

What is FormRequest?

FormRequest is Laravel’s default form request validation mechanism. FormRequest can be extedned to define your custom validation class. In this extender class you can define your validation rules under rules() array. You can also use this extender class to perform advanced actions such as pre-validation checks or write your custom complex rules.

In this example I will show you three different methods to perform form request validation in a Laravel application.

Examples with Code

Let’s start with creating the FormRequest class. Run:

php artisan make:request GiftcodeRequest

It creates a FormRequest class in App\Http\Requests\GiftcodeRequest.php.

I update rules() method of this class to define my validation rules. (Here is list of validation rules available in Laravel)

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class GiftcodeRequest 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 [
            'date_field' => 'required|date',
        ];
    }
}

Validation via Dependency Injection (default)

Using Laravel’s FormRequest class we can validate incoming data by injecting our form request class into the method of our controller. Look at the code below. GiftcodeRequest $request is passed as an argument to create method of the controller. In Laravel this mechanism is called dependency injection.

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\GiftcodeRequest;

class GiftcodeController extends Controller
{
    public function create(GiftcodeRequest $request)
    {
        (...)
        $validated = $this->validated();
        (...)
    }
}

Validating Manually (custom)

There is no reason to not use the FormRequest class as a dependency injection into controller method as shown above. However in some cases you may wish to validate data within a controller function or inside any other class.

The following code sample demonstrates the use of  data validation mechanism to perform validate request data manually, but still using the FormRequest class.

<?php
namespace App\Services;

use Illuminate\Support\Facades\Validator;
use Exception;

use App\Http\Requests\GiftcodeRequest;

class GiftcodesService
{
    public function someMethod()
    {
        $data = ['some' => 'data'];
        $formRequest = new GiftcodeRequest();
        $validator = Validator::make($data, $formRequest->rules());
        if ($validator->fails()) {
            throw new Exception($validator->errors()->toJson());
        }
        return (object)$validator->validated();
    }
}

(You may also like to check the use of FormRequest validation to validate CSV content here)

Custom and Manual Validation

Again there is no reason to not use FormRequest to define your rules in and use it. But, in case you are in an extreme hurry and can afford to write code within the file, you can even define your rule and validate it at the spot (as shown below).

<?php
namespace App\Somewhere;

use Illuminate\Support\Facades\Validator;

class SomeClass {
    public function someMethod() { 
        $data = ['date' => '2023-08-25'];
        $rules = ['date' => 'date_format:Y-m-d|required'];
        $validator = Validator::make($data, $rules); 
        if ($validator->fails()) { 
            throw new Exception($validator->errors()->toJson()); 
        }
        return (object)$validator->validated(); 
    } 
}

Conclusion

Laravel comes with FormRequest mechanism to perform form request validation. It can be used by simply defining rules() in a class which extends FormRequest class. You can inject your FormRequest extender class into your controller function to perform form request validation on incoming request data.

However you can also use Validator class manually to validate form request in Laravel. In third example, I have shown you method to define both rule and data in anywhere inside your application file.

Leave a Reply