Search code examples
phplaravellaravel-4laravel-validation

using unique rule of laravel 4 on updating database records


i have this table weapons that have the columns weaponID, weaponName, wStock, wDesc

in my update function inside the controller, i have this set of rules

public function c_updateSystemUser($id)
{
    $rules = array(
            'weaponName'  => 'required|min:2|max:50|regex:/^[a-zA-Z0-9\-\s]+$/|unique:weaponTbl,weaponName,' . $id,
            'wStock'      => 'required|numeric',
            'wDesc'       => 'required|min:1|max:100|regex:/^[a-zA-Z0-9\-\s]+$/' 

        );
    //other stuff
}

when i updated and only changed the wStock it is having problems because it is saying that the weaponName already existed. so i used the unique rule

unique:weaponTbl,weaponName,' . $id,

because i wanted to except the record whose im currently working on but when i tested it i'am having these errors

Column not found: 1054 Unknown column 'id' in 'where clause'
(SQL: select count(*) as aggregate from `weaponTbl` where `weaponName` = unicorn and `id` <> 1)

why is that it using id only whereas i don't have any 'id' in my table but only weaponID? is there a way to work around with this?


Solution

  • Inside your weapon class you need to change the primary key:

    class Weapon extends Eloquent {
    
        protected $primaryKey = 'weaponID';
    
    }
    

    And then change the unique rule to:

    unique:weaponTbl,weaponName,' . $id . ',weaponID'