Error updating a unique field

1

I have a problem updating the information in a role. In my database I have the attribute nombre_rol as unique . Registering a new role works perfectly, but when updating the same record, it gives me the error that the Role element is already in use.

Role Model

class Rol extends Model
{
    protected $table = 'rol';
    protected $primaryKey = 'idrol';
    public $timestamps =false;

    protected $fillable =['nombre_rol, descripcion, estado, fecha'];
    protected $guarded =[];
}

RolRequest

 public function rules()
    {
        return [
            'nombre_rol'=>'required|unique:Rol,nombre_rol',            
            'descripcion'=>'required'
        ];
    }

I am using laravel 5.2 and according to the documentation it says that to ignore I must place the following 'email' => 'nombre_rol'=>'required|unique:Rol,nombre_rol,'.$user->id.',user_id',

But in my case I get an undefined variable error, I do not even understand where I get the variable $ user- > id.

    
asked by jeancarlos733 23.06.2017 в 06:48
source

2 answers

1

You are using the incorrect values in the validation syntax:

  • The third parameter is the ID or primary key of the specific record that you do not want to include in the "unique" comparison.
  • The fourth parameter is the field name of the primary key

In your case it should be something like that, assuming you're not using Model Binding:

If your route is something like Route::put('actualizar-rol/{id}', '[email protected]');

Then the validation would be

'nombre_rol'=>'required|unique:rol,nombre_rol,'. $this->id .',idrol',

If you use Route Model Binding, it would be something like this:

Path: Route::put('actualizar-rol/{rol}', '[email protected]');

and the valication:

'nombre_rol'=>'required|unique:rol,nombre_rol,'. $this->rol->idrol .',idrol',
    
answered by 23.06.2017 / 07:57
source
1

I run 100% using the validation in my update method, since in my store method I do not send the id.

 public function update(Request $request, $id)
{
    $request->validate([
        'type_id' => 'required',
        'owner_code' => 'required|max:6|unique:owners,owner_code,'. $id.',owner_id',
        'name' => 'required|max:50',
        'country_id' => 'required',
        'company_id' => 'required'
    ]);

    $owner = Owner::findOrFail($id);
    $owner->type_id = $request->get('type_id');
    $owner->status = $request->get('status');
    $owner->owner_code = $request->get('owner_code');
    $owner->status = '1';
    $owner->name = ucwords($request->get('name'));
    $owner->country_id = $request->get('country_id');
    $owner->company_id = $request->get('company_id');
    $owner->update();
    return Redirect::to('/owner/'.$id);
}

I leave the code in case someone serves you. Greetings.

    
answered by 15.06.2018 в 23:27