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?
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.
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.
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.
Yes
class User extends Eloquent { protected $primaryKey = 'admin_id'; }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With