Skip to content
Advertisement

Laravel Validation Request, how to handle validation on update?

First of all I love the way that validation is going through, can now easily use

 public function authorize(Authenticator $auth)
 {
    return $auth->user()->hasRole('administrator');
 }

hat’s not the problem, I bump always into another problem… that is when you update an record, how to do things with the rules? If I need to update an email, I need the following string: 'email' => 'unique:users,email_address,10'. In this case it should look like:

public function rules()
 {
    return [
   'email' => 'required|unique:users,id,?????',
   'tags' => 'required'
    ];
 }

Advertisement

Answer

It’s more simple.

The Laravel documentation says “If your table uses a primary key column name other than id, you may specify it as the fourth parameter”:

'email' => 'unique:users,email_address,'.$user->id.',user_id'

If for example, you want to verify if a username exists, but excluding current user ID:

// UpdateUserRequest.php
public function rules() {
   // 
    return [
        'username' => 'required|unique:users,username,'  .  $this->id . ',id',
    ];
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement