Get primary key of Eloquent model instance

32,390

Solution 1

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

Solution 2

If you want to do it dynamically -

app("App\\Models\\" . $modelName)->getKeyName();//Laravel 8
app("App\\" . $modelName)->getKeyName();//Laravel less than 8
Share:
32,390
Basaa
Author by

Basaa

Experienced in Web Development, C# and Java. Working on my first 3D game in LWJGL!

Updated on July 09, 2022

Comments

  • Basaa
    Basaa almost 2 years

    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?