Issue
I try to update my table Item
but I use unique validation in my controller, I have set the primary key = 'item_id' in my model but I keep get this error said unknown column id even though I have set the primary key as item_id in my model, when I try to use validation :
// 'barcode' => 'unique:item' //
This error doesn't appear and the program works but in the unique of barcode it is checking itself for the unique column and it fails but seeing its own field. that's why i change my validation become this :
// 'barcode' => 'unique:item,barcode,'.$item_id, //
when I try to update I get this error :
Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from
item
wherebarcode
= A002 andid
<> 12)
ItemController :
public function update(Request $request,$item_id)
{
$messages = [
'unique' => 'Sorry this barcode already exist....',
];
$this->validate($request,[
'barcode' => 'unique:item,barcode,'.$item_id,
],$messages);
$data = $request->except(['_token']);
Item::where('item_id',$item_id)->update($data);
return redirect('/item')->with('sukses','item successfully updated');
}
this is my model Item.php :
class Item extends Model
{
protected $table = 'item';
protected $primaryKey = 'item_id';
protected $fillable = ['barcode','item_name','category_id','satuan_id','price'];
public function category_r(){
return $this->belongsTo('App\Category','category_id','category_id');
}
public function satuan_r(){
return $this->belongsTo('App\Satuan','satuan_id','satuan_id');
}
}
Solution
When you are using custom primary key you should also add its name to the validation:
$this->validate($request,[
'barcode' => 'unique:item,barcode,'.$item_id.',item_id'
],$messages);
https://laravel.com/docs/5.2/validation#rule-unique
Answered By - katsarov
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.