Laravel Unique Validation for each user

Viewed 322

I am running into an issue which I assume is simple, but it has me stumpted and I would appreciate any help.

The issue is I want each user to be able to create ads, User 1 can have one ad called "Test Ad" and user two can have one ad called "Test Ad" What is happening right now is the user can only have one ad called "Test Ad" but if user one has created "Test Ad" then user 2 is not able to because validation is returning that it already exists, but it doesn't exist for that user.

Here is my validation code:

 'ad_title' => 'unique:ads,ad_title,user_id|required|min:3|max:128,' . Auth::user()->id,

Thanks for your time!

2 Answers

You can use closure function to apply your custom validation requirement.

Try

[
    'ad_title' => [
        'required',
        'min:3',
        'max:128',
        function ($attribute, $value, $fail) {
            return !! (\DB::table('ads')
                ->where('user_id', auth()->id())
                ->get()
                ->contains('ad_title', $value);
            );
        },
]

However the logic for this validation is likely to be required at multiple places then it's better to define a custom rule class https://laravel.com/docs/8.x/validation#using-rule-objects

Laravel 5.3 and above

use Illuminate\Validation\Rule;

'email' => Rule::unique('ads')->where(function ($query) {
     $query->where('user_id', Auth::id());
 })

Laravel 9

use Illuminate\Validation\Rule;

Rule::unique('ads')->where(fn ($query) => $query->where('user_id', Auth::id()))
Related