Support the ongoing development of Laravel.io →
posted 11 years ago
Validation

Hi all,

I am trying to figure out how to create a unique validation based on 2 fields.

My app creates an 'assessment' with a unique identifier field. However the assessment is linked to a user and I only want the unique validation to happen on that user. Can anyone tell me how to do this?

'required|unique:assessments,identifier'

will validate for the whole assessments table but I only want to check if it is unique for the current user. Something like:

'required|unique:assessments,identifier,user_id,'.Auth::user()-id;

I guess something like the following but instead of 'exits', I want 'not_exists':

'email' => 'exists:staff,email,account_id,1'

Can anyone help?

Last updated 3 years ago.
0

I think I've figured it out but do not really understand the syntax:

'required|unique:assessments,identifier,NULL,id,user_id,'.Auth::user()->id);'

I am not sure why I need NULL and id in there? It produces:

"select count(*) as aggregate from `assessments` where `identifier` = ? and `user_id` = ?"
Last updated 3 years ago.
0

From the Laravel docs on validation rules:

unique:table,column,except,idColumn

So, in your example, the third argument, NULL, is the except bit. It's null because you're not trying to ignore a given ID. The fourth argument, if I read the docs right, is the column containing the id field... probably just id. The fifth and sixth arguments are what populate your where clause, in your example, WHERE user_id = Auth::user()->id

Again, from the docs for the third argument,

"Forcing A Unique Rule To Ignore A Given ID"

'email' => 'unique:users,email_address,10'
Last updated 3 years ago.
0

This is NOT working:

'short' => 'required|unique:kunden,id,6'

also tried: 'short' => 'required|unique:kunden,6'

since i cant find the information if i need to specify the field the 6 is related to or not.

I edit data with ID 6 and it still tells me i cant since short is existing already.

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

chriship chriship Joined 7 Mar 2014

Moderators

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

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.