robman70's avatar

Validator Unique only if another column has specified value

Maybe I have a bit of a weird problem: I should check that the value in a certain field is unique but only among the records that have a certain value in another field.

Example: I would like to check that the user's e-mail field is unique but considering only the records where the 'enabled' field is = 1. Basically I need to change the rule: 'email' => 'required | email | unique: users | max: 100' of my Validator.

I would also like to know if it is possible to edit \app\Actions\Fortify\ CreateNewUser.php where there is a similar rule: 'email' => ['required', 'string', 'email', 'max: 255', 'unique: users'].

Thanks in advance.

0 likes
3 replies
robman70's avatar

@OussamaMater

Thanks a lot, it works perfectly!

I would have preferred to use a Validator but I have not much practice with the syntax yet and I don't know how to rewrite this (working thanks to your suggestion):

$ request-> validate ([
			'email' => [
				'required',
				'max:100',
				'email',
				Rule::unique('users')->where(function ($query) {
					$query->where('deleted', 0);
				})
			],
]);

to take advantage of a Validator:

$ validator = Validator :: make ($ request-> all (), [
			'email' => 'required | email | max: 100 | unique: users', // check for 'enabled' is missing ...
]);
if ($validator->fails()) ...
if ($validator->validated()) ...

This is the method I used but in my version (using a Validator) I don't know how to insert the control that considers only the records with enabled = 1 (it would also be good to exclude enabled = 0, of course ...).

Anyway, what you proposed works well, thanks!

OussamaMater's avatar

@robman70 Happy to help, if it's solved please close the thread by setting a "best answer", for future comers :)

1 like

Please or to participate in this conversation.