PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from `item` where `barcode` = A002 and `id` <> 12)

 February 20, 2022     laravel, unique, validation     No comments   

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 where barcode = A002 and id <> 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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing