OrgGila
OrgGila

Reputation: 333

Laravel 5 update without id

I have a problem in Laravel 5. When I update a record in database, I get error Unknown column 'id' in 'where clause'. In the controller, I use WHERE clause to get the record I want to update. My primary key is not id and the type is bigInteger. I've tried adding protected $primaryKey in the model but it doesn't work for bigInteger. Is there any way to use my own primary key instead of using id?

Controller

$item = Item::where('item_id','=',$item_id)->first();
$item.name = $name;
$item.type = $type;
$item.save();

Upvotes: 6

Views: 7785

Answers (3)

qiyon
qiyon

Reputation: 31

Laravel's orm $primaryKey default is 'id'.

When orm update, it use the sql like:

... where {$this->primaryKey} = {$this->{$this->primaryKey}}

So when you class extends orm.

You should redefine protected $primaryKey = '<your_table_primary_key>';.

Upvotes: 3

CanKer
CanKer

Reputation: 450

Try this $item = Item::where('item_id', $item_id)->first(); If still don't working add also protected $primaryKey = "item_id"; to your model

Upvotes: 0

terry low
terry low

Reputation: 10618

pls add this line to your Item.php model

class Item extends Model {


// add this line only
protected $primaryKey = 'item_id';

//..... the rest of your model

since your using custom id name, laravel will not know what is your primary key without you specify it

Upvotes: 3

Related Questions