Katanji
Katanji

Reputation: 68

Laravel 5.8. How to trim http during validation and check for uniqueness in the table?

  1. there is a table of shops, in it, we store URLs with HTTP and https already cut off. example: rozetka.ua, comfy.ua
  2. from the front to the request for validation, the URL that has not yet been processed arrives, with HTTP or https. For example http://rozetka.ua
  3. How to check the site for uniqueness? validation have a check for URL, the option with preliminary HTTP is not suitable.
  4. Since the site has already been configured to work with errors and interception of front-line and back-validation, it is necessary to achieve the condition that when validating the request it is an error as if unique. That is the status 422 and the corresponding error object.

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

Answers (1)

Tarasovych
Tarasovych

Reputation: 2398

Try this:

return [
    'url' => [
        'required',
        'string',
        'url',
        'max:255',
        'unique:NAME_OF_THE_TABLE,NAME_OF_THE_COLUMN',
    ],
]

Reference

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

Related Questions