Reputation: 68
So far I have stayed on this option:
return [
'url' => [
'required',
'string',
'url',
'max:255',
function ($attribute, $value, $fail) {
$url = parse_url($value, PHP_URL_HOST);
if (Store::where('url', $url)->count() > 0) {
$fail('The ' . $attribute . ' has already been taken.');
}
},
],
]
Upvotes: 0
Views: 317
Reputation: 2398
Try this:
return [
'url' => [
'required',
'string',
'url',
'max:255',
'unique:NAME_OF_THE_TABLE,NAME_OF_THE_COLUMN',
],
]
Or you can create a custom Rule:
php artisan make:rule UniqueUrl
//UniqueUrl class
public function passes($attribute, $value)
{
$url = str_replace(parse_url($value, PHP_URL_SCHEME) . '://', '', $value);
return Store::where('url', $url)->count === 0; //true if there is no such url, false if there is at least one
}
and use it:
return [
'url' => [
'required',
'string',
'url',
'max:255',
new UniqueUrl,
],
]
Upvotes: 1