Laravel request update unique field only if changed

laravel unique validation on update
laravel validation rules unique update
laravel form request validation unique update
laravel update only changed fields
laravel ignore unique on update
laravel unique validation with condition
laravel validation unique combination
laravel validation unique except

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?

If i understand you correctly, you want to add unique validation if email changed, if that is the case then you just need to add a condition in validation. If you check unique validation structure it look like this unique:table,column,except,idColumn, check documentation

So the validation will be look like this, when you will create new record $userId will be null but at time of patch it will have value. So this validation will work for both create and patch.

$userId = isset($user) ? $user->id : null;

$rules = [
        'email' => 'required|email|unique:users,email,'. $userId.',id',
    ];

 $this->validate($request, $rules);

php - Laravel request update unique field only if changed, 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. Laravel’s Eloquent ORM has a method called fill which accepts an array and will update the database with new values for only the fields passed in. The nice thing about the fill method is that it automatically preserves values that are already stored in the database if you don’t want to update every field when doing a PUT request. Implementing it is much simpler than the ternary method:

There is a built-in feature for this. You can add the actual user id to the unique constraint, if present. This will ensure that the unique constraint will still work, but it will not fail when the value did not change:

$exists = $user->exists;
$rules = return [
    'user.email' => 'required|email|unique:users,email' . ($exists ? ','.$user->id : ''),
];

Internally, this will execute a query like:

SELECT count(id) FROM users WHERE email = 'some-mail@example.com' AND id != 42

The latter part AND id != 42 will only be part of the query when you add the third parameter to the unique validation rule.

Problem with unique field validation on update, http://laravel.com/docs/5.1/validation#rule-unique However, if the user only changes the name field and not the e-mail field, you do not want a  If I remove the unique validation, I can update the row. But, the row will no longer be unique. I mean I can change the name to anything I want and the update will work.

You are missing the break; statement after every case. And for Update (PATCH request) you have to pass id also in update request.

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

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

Input Validation: Unique field, but what if there is no edit?, However, if the user only changes the name field and not the e-mail field, /​laravel-5-validation-request-how-to-handle-validation-on-update. A Note On Optional Fields; Form Request Validation. the base Laravel request e-mail address is unique. However, if the user only changes the name field and

$request->validate([
        'naam' => 'required|max:190|unique:database_name.table,column_where_you_check_unique,'.$id.',$id_column_reference'
    ]);

'naam' - form input field name

database_name(optional) - if you have multiple database

table(required) - table name

column_where_you_check_unique(required) - where data is unique

$id(required) - check with id autoincrement

$id_column_reference - column name of $id.

Using the unique validation rule in a Laravel Form Request, Using the unique validation rule in Laravel to ensure that a field is unique If you have a form that the user has to fill in to create the post then you store and update, or you can move the validation into a form request class. Forum Requests Problem with unique field validation on update. Problem with unique field validation on update Each product may have a unique ID and a unique code.

My way:

'slug' => $site->slug !== $request->slug ? 'required|min:4|max:80|unique:sites' : 'required|min:4|max:80'

Laravel request update unique field only if changed, Laravel request update unique field only if changed. laravel unique validation on update laravel form request validation unique update laravel validation rules  If you would like to obtain an instance of a PSR-7 request instead of a Laravel request, you will first need to install a few libraries. Laravel uses the Symfony HTTP Message Bridge component to convert typical Laravel requests and responses into PSR-7 compatible implementations:

Laravel request update unique field only if changed – GiveMeAns , 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  The update method expects an array of column and value pairs representing the columns that should be updated. {note} When issuing a mass update via Eloquent, the saving, saved, updating, and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.

Laravel validation service with unique fields, For example, if a user has the username of John then when I try to update the model this will merge update rules to default rules $rule = 'update'; // user has changed his at http://laravel.com/docs/validation unique:table,column,except,​idColumn The field under this->route("user")->id, This is inside of my form request. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve. The Laravel Schema facade provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems.

HTTP Requests - Laravel, If your controller method is also expecting input from a route parameter you string $id * @return Response */ public function update(Request $request, $id) { // } } from entire request payload (including the query string), the query method will only If it is not present, Laravel will search for the field in the route parameters. The problem is when I modify the email field and put inside this one an email address affected to another user and so already existing in the database. Laravel display me this message, because the email column has a unique value in my users table. Illuminate \ Database \ QueryException (23000)

Comments
  • i have added an answer, check it once
  • @rkj I have taken the advice of another user and temporarily removed the switch statement to try and clean the code. If i resort back to the switch method I will try your answer, thank you.
  • no need to add switch condition for my answer, that one line will work for all create, patch
  • My apologies, I didn't notice you had updated it to ignore the switch statement. Your answer works great, thanks!
  • glad it works for you
  • This sounds logical, but it doesn't seem to work for me? It still errors out saying the email has to be unique if i don't change it. Does this have to be applied in the above switch statement or can it just be a general rule?
  • If there is not another good reason to have the switch other than the unique thingy, get rid of it - for the unique constraint you definitely don't need it. You only need a good and consistent way to determine if a user exists already. By the way, I had to fix the call to $user->exists because it shouldn't be a function call. It is a magic property.
  • It still doesn't seem to be detecting correctly, its still returning 'email has already been taken'
  • @S_R did you try my answer ?
  • I'm sorry, Im struggling to see how this answers my question? This is the same as my switch method in my request, I need it to be able to detect if the email has changed in the POST and run a different unique rule if it has been changed
  • Do you have more code, controller, model and/or repository?