Back

Laravel unique validation on multiple columns for unique relations


How do I perform a Laravel unique validation on multiple columns for unique relations.

One user can add new games but I want it so that one user cannot add new identical games

For example, I don't want to allow this: - table games - id name user_id - 1 Descent 1 - 1 Descent 1

But I want to force the users this:

  • table games
  • id name user_id
  • 1 Descent 1
  • 1 Descent 2

How do I do this in laravel? I apologise for the messy formatting, I can't seem to get it to work

RDelorier replied 1 year ago Solution

Try the unique rule with with additional where clause

'name' => 'unique:games,name,NULL,id,user_id,'.$user->id

http://laravel.com/docs/5.1/validation#rule-unique

jschouwstra replied 1 year ago

Thank you so much, it works perfectly!

sineld replied 1 week ago

If using auth:

public function rules() {
	return [
		'email' => 'required|email|unique:users,email,NULL,id,deleted_at,NULL,department_id,' . auth()->user()->department_id,
	];
}

Sign in to participate in this thread!


We'd like to thank these amazing companies for supporting us