Custom Validation Rules with form request validation method in Laravel

We are familiar with using validator in controller which is the common way but this is not a good practice. Laravel has form request which is a special request class containing the validation logic. You can create form request using artisan command.

Php artisan make:request UserStoreRequest

This command will create a new Request class in app\Http\Request\UserRequest .

Those who are not familiar with this method will get confused easily when you first use it.

So we will see how to add custom validation rules in form request method.

Example:

You want to add a custom validation numeric_array with field items

protected $rules = [

'shipping_country' => ['max:60'],

'items' => ['array|numericarray']

];

The custom function is :

Validator::extend('numericarray', function($attribute, $value, $parameters) {

foreach ($value as $v) {

if (!is_int($v)) {

return false;

}

}

return true;

});

Put the validator::extend() function in the ServiceProvider as given below.

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ValidatorServiceProvider extends ServiceProvider {

public function boot()

{

$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)

{

foreach ($value as $v) {

if (!is_int($v)) {

return false;

}

}

return true;

});

}

public function register()

{

//

}

}

Register the provider by adding it to the list in config/app.php then you can use numericarray validation

rule wherever you want.

'providers' => [

// Other Service Providers

'App\Providers\ValidatorServiceProvider',

],