Mark
Mark

Reputation: 31

Laravel 5.4 validation unique issue

I'm trying to update an user and when the email is already taken it will give an error, except when it's your own email. Right now my code is:

$user = User::find($id);

$input['email'] = request('email');

$rules = array('email' => 'unique:users,email,'.$user->id);

$validator = Validator::make($input, $rules);

if ($validator->fails()) {
    return back()->withInput()->withErrors(['email']);
}

This works perfectly fine, but now I want that it only gives an error if the email already exists AND from the found record the column 'function' = 'client', but I have no idea how to code this.

Upvotes: 1

Views: 3240

Answers (3)

Adam Kozlowski
Adam Kozlowski

Reputation: 5906

At this point you should use powerful Laravel's Validation. According to documentation:

The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.

And simply rule:

unique:table,column,except,idColumn

Code:

$request->validate([
    'email' => 'unique:users,email_address,'.$request->get('id').',id'
]);

Read more: https://laravel.com/docs/5.3/validation#rule-unique

Upvotes: 0

omitobi
omitobi

Reputation: 7334

Checking the Exist rule and Unique rule from Laravel 5.4 doc

enter image description here

Then you can simply have:

//Import Rule
use Illuminate\Validation\Rule;

......

$rules = array( 'email' => array( 'required', 
    Rule::unique('users')->where(function ($query) {
        $query->where('function','!=', 'client');
    })->ignore($user->id)
));

$validator = Validator::make($input, $rules);

I think the above should be sufficient even though I can't be 100% assure its going to fit your expectation but I think it should show you what is missing.

Upvotes: 1

Vaibhavraj Roham
Vaibhavraj Roham

Reputation: 1165

$count = User::where('email','=',request('email'))
        ->where('function','!=','client')
        ->count();

if($count){
    return back()->withInput()->withErrors(['email' => 'Email Already Exist']);
}

What will above code do :

Count users whose email is request_email and function is not client.

if $count is greater than 1 that means duplicate email.

Return with error that Email Already Exist

Upvotes: 0

Related Questions