Boone Boone - 2 months ago 42x
PHP Question

Laravel 5.2 Validator: limiting unique field check to specific user

I am trying to limit the required:unique validator in my Laravel 5.2 app to checking uniqueness of my 'slug' column against only the table results of a specific user_id. In other words, the slug does need to be unique, but only on a per-user basis. I've got it working for the store() function, with the following code:

'slug' => 'required|unique:contents,slug,NULL,id,user_id,' . Auth::id()

That works just fine. However, I can't get the update() function to work the same, because I can't get the validator to stop checking unique against the result of the entry that's currently being updated. The code I'm currently using is:

'slug' => 'required|unique:contents,slug,' . $content->slug . ',id,user_id,' . Auth::id()

That code doesn't look right to me, but I've tried several variants and none of them work how I would like. To my mind, I would think that this would work:

'slug' => 'required|unique:contents,id,' . $content->id . ',user_id,' . Auth::id()

But it doesn't. Does anybody know what my problem is here? Any guidance would be much appreciated.


It's hard to give the right answer without knowing the actual attribute names in your model. The validator supports the following parameters



{0} = table name being validated

{1} = column name being validated

{2} = Id value of row in {0} to skip validation

{3} = name of primary key column in {0}

{4} = name of additional filter column in {0}

{5} = value for additional filter column

So, it seems we clearly have the values for {0}, {1}, {2} and {5}. I am not sure from your question information what the correct values for {3} and {4} are. If I was to take a guess, I would write the validator rule like this:

'slug' => 'required|unique:contents,slug,' . $content->id . ',id,user_id,' . Auth::id()