Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get primary key of Eloquent model instance

I'm happy enough to work on a project with (not) very consistent column names in our MySQL database. We have camelCase, PascalCase, 'Id', ID and it's driving me nuts. I've decided to start using Eloquent in our application (which is NOT Laravel). I would love to have a method of receiving the value of the primary key easily without knowing the column name e.g.

// User's primary key column is called UserID
$user = User::find(1337);
$userId = $user->id(); // = 1337

Is there a Eloquent way of doing this or am I gonna have to add this method myself?

like image 624
Basaa Avatar asked May 26 '15 11:05

Basaa


People also ask

What is primary key in Laravel model?

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.

How do I change my primary key in eloquent?

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.

What is first () in eloquent?

The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.


2 Answers

You should have define a protected field in your model telling Eloquent what the primary key column is:

protected $primaryKey = 'guid';

Then you can access that property in your model

The model's getKey() method should give you value of the primary key, while getKeyName() should tell you what column name is used for the primary key

like image 162
Mark Baker Avatar answered Sep 23 '22 09:09

Mark Baker


If you want to do it dynamically -

app("App\\Models\\" . $modelName)->getKeyName();//Laravel 8
app("App\\" . $modelName)->getKeyName();//Laravel less than 8
like image 1
sagarjadhav Avatar answered Sep 22 '22 09:09

sagarjadhav