Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate UUID with Laravel Validation

Is there a built-in way to validate UUID with a validation rule? I did not found anything about this in the "Available Validation Rules" documentation.

like image 413
rap-2-h Avatar asked Oct 11 '17 07:10

rap-2-h


2 Answers

Actually, Laravel 5.7 supports UUID validation.

$validation = $this->validate($request, [
    'uuid_field' => 'uuid'
]);

Based on documentation.

like image 127
Legionar Avatar answered Oct 04 '22 01:10

Legionar


Laravel 5.6 provides the ramesey/uuid package out of the box now. You can use its "isValid" method now to check for a UUID. I noticed that the regex in the solution above would fail sometimes. I haven't had any issue yet with the package used by Laravel internally.

Validator::extend('uuid', function ($attribute, $value, $parameters, $validator) {
    return \Ramsey\Uuid\Uuid::isValid($value);
});

Unrelated to the question but you can now also generate a UUID using the "Str" class from Laravel. It is the reason why ramsey/uuid is now included by default, removing the necessity to include your own regex.

\Illuminate\Support\Str::uuid();
like image 37
Bryse Meijer Avatar answered Oct 04 '22 00:10

Bryse Meijer