Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validate unique if id is the same

I have a table/model that contains multiple albums per user. Is there a way to say that the column title should be unique, but only for the rows that have the same user_id?

Example: http://pastebin.com/8dvM4a1T

As you can see in the example, the user with the id of 2 has created 2 albums, with the same title. I don't want that to be allowed, that's why I'm wondering if there's a way to deny that with the validator from Laravel?

I tried this, but that did not work.

// Validator
    $validator = Validator::make($input, [
        'title' => 'required|min:1|max:255|unique:galleries,title,'. Auth::user() -> id .',user_id',
        'description' => 'min:1|max:255'
    ]);

Any help appreciated, thanks.

like image 467
Kaizokupuffball Avatar asked Apr 12 '16 13:04

Kaizokupuffball


2 Answers

Your code should be something like:

'title' => 'unique:galleries,title,NULL,id,user_id,'.Auth::user() -> id.'',

Or, you can write a custom rule Reference here

like image 52
VipindasKS Avatar answered Oct 20 '22 15:10

VipindasKS


The approach with the default unique rule does not work because the rule expects the column value to be passed as the third parameter, so in your case it would check if the title column is equal to the Auth::user()->id value which is not what you want.

You can create you own custom validation rule by adding the following code to the boot method of the App\Providers\AppServiceProvider class:

Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
    // Get the parameters passed to the rule
    list($table, $field, $field2, $field2Value) = $parameters;

    // Check the table and return true only if there are no entries matching
    // both the first field name and the user input value as well as
    // the second field name and the second field value
    return DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});

Now you can use the unique_custom (or you can name it whatever you like) rule like so:

$validator = Validator::make($input, [
    'title' => 'required|min:1|max:255|unique_custom:galleries,title,user_id,' . Auth::id(),
    'description' => 'min:1|max:255'
]);

The rule expects the parameters to be the following:

  • the 1st parameter to be the table name, which in this case is galleries
  • the 2nd parameter to be the field name that is supposed to be unique and for which the value comes from the user input, which in this case is title
  • the 3rd parameter to be the second field name that will be added to the query conditions, which in this case is user_id
  • the 4th parameter to be the value of the field name passed as the third parameter

Also you can use Auth::id() since that is the short form of Auth::user()->id.


You can read more about Custom Validation rules in the Laravel Documentation.

like image 32
Bogdan Avatar answered Oct 20 '22 15:10

Bogdan