Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default primary key in Eloquent

Can I change Eloquent model primary key.

I want to set primary key for example admin_id instead of 'id'?

I know I can change table name for model like

protected $table = "admin"; 

Is there something similar for primary key?

like image 997
Vuk Stanković Avatar asked Nov 17 '13 12:11

Vuk Stanković


People also ask

How do I change my primary key in eloquent?

By default, Eloquent models expect for the primary key to be named 'id' . If that is not your case, you can change the name of your primary key by specifying the $primaryKey property. Now, any Eloquent methods that use your primary key (e.g. find or findOrFail ) will use this new name.

What is eloquent ORM in PHP?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

Why we use eloquent in Laravel?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.


2 Answers

Yes

class User extends Eloquent {      protected $primaryKey = 'admin_id';  } 
like image 111
phirschybar Avatar answered Sep 22 '22 13:09

phirschybar


If you are wanting to use a composite key (a string)

You need to make sure you set public $incrementing = false otherwise laravel will cast the field to an Integer, giving 0

class User extends Model {      protected $primaryKey = 'my_string_key';     public $incrementing = false;  } 
like image 40
Toby Mellor Avatar answered Sep 21 '22 13:09

Toby Mellor