L
L
lolrofl012020-01-12 21:28:38
Laravel
lolrofl01, 2020-01-12 21:28:38

How to check if such a value exists in a table using laravel validate()?

Good afternoon.
There is an entry in which, among other things, you can change the url. The url must be unique, i.e. There shouldn't be any other posts with this url. When creating a record, everything is easy, I check it like this:

$request->validate([
   'slug'  => [ 'required', 'unique:posts' ],
]);

Works! However, there is a problem when editing a record. If you do not change the URL in the entry, but leave it as it is, then it will be impossible to save. The validator will find this very entry and an error will appear that such a url is already in the database - write another one. Is there a way to bypass this with a validator? I can make a selection from the database next to it, check if there is an entry with the same url but not the same ID as the edited entry. If there is - only then issue an error. But this is a bicycle, what if you can do without it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2020-01-12
@lolrofl01

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

V
Vladimir Kokhan, 2020-01-12
@SkazochNick

When editing a record, validation is not so important, since the data in the fields is already present.
Or, in extreme cases, you can not do it for input from url

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question