How to create custom validation rules in Laravel ?

Laravel
January 21, 20211 minuteuserVishal Ribdiya
How to create custom validation rules in Laravel ?

While developing complex applications, sometimes we have to validate fields and data in a totally customized way, at that time you can use laravel's custom validations rules functionality.

In this tutorial, we are going to create our own custom validation rule to compare UUID. In our case, I have to check the UUID which is actually a binary string, whether it exists on DB or not.

Laravel doesn't provide any rule to compare that binary UUID string, so we will create our own validation rule.

So let's create our custom validation rule::

Generate Custom Validation Class

So here we have created a new class named UuidExists into App\Rules

namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Ramsey\Uuid\Uuid;
class UuidExists implements Rule
{

    protected $table;
    protected $column;

    public function __construct($table, $column)
    {
        $this->table = $table;
        $this->column = $column;
    }
    public function passes($attribute, $value)
    {
        $value = Uuid::fromString(strtolower($value))->getBytes();
        return \DB::table($this->table)->where($this->column, $value)->exists();
    }
    public function message()
    {
        return 'The validation error message.';
    }
}

Add Rule to AppServiceProvider

Add your rule to AppServiceProvider.php into boot() method. here I have to give the name uuid_exists to my custom rule. you can give your own name whatever you want.

\Validator::extend('uuid_exists', function ($attribute, $value, $parameters, $validator) {
    list($table, $column) = $parameters;
    return (new UuidExists($table, $column))->passes($attribute, $value);
});

How to use custom rules?

You can use your custom rule as follows. Here we have using the required and uuid_exists rule, where we are passing attributes and values to our custom rule, which will be used to passes($attribute, $value) function.

'tenant_id' => ['required', 'uuid_exists:tenant_id,uuid']

Keep connected to us for more interesting posts about Laravel.