Laravel's post

post
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, that 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 new class with 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 AppService Provider

Add your rule to AppServiceProvider.php into boot() method. here I have to give the named 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 Rule ?

You can use your custom rule as follows. here we have using required and uuid_exists rule, where we are passing attribute 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.


January 21, 20211 minuteauthorVishal Ribdiya