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.