mardi 17 juillet 2018

Laravel request update unique field only if changed

I wan't to be able to validate a user email address based on certain circumstances.

For example

If a user is being created, the email address must be unique

If a user is being updated but the email address hasn't changed, ignore the unique email rule

If a user is being updated and their email address has changed, it has to be unique

I've had a little look around and I know that I can specify different rules based on the method like so

public function rules()
{
    $user = User::find($this->users);

    switch($this->method())
    {
        case 'POST':
        {
            return [
                'user.email'      => 'required|email|unique:users,email',
            ];
        }
        case 'PUT':
        case 'PATCH':
        {
            return [
                'user.email'      => 'required|email,
            ];
        }
        default:break;
    }
}

Is there any way to make it so that in the put/patch case, the rule checks if the email address has been changed, and if it has then it has to be unique?

If not is there a cleaner way of achieving this goal? Maybe without the switch case? Perhaps more in depth validation rules I haven't stumbled across yet?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire