Laravel ID normalizer

Although Laravel makes use of the "id" column name by default, I have encountered projects where this column name was named differently. Instead of remembering primary keys, why not normalize them?

Laravel1 / 3Level:

Instead of having to adjust "id" to match the primary key name, we're able to use a simple accessor (or attribute) that does this automatically:

/**
 * Get the value of the primary key.
 *
 * @return Attribute
 */
public function id(): Attribute
{
    return Attribute::get(fn ($value) => $value 
      ?? $this->{$this->getKeyName()} 
      ?? null
    );
}

Which results in the following:

// old, lame way 🙁
$id = $model->custom_id; // or was it "customized_id" ?
// new, easy way 😏
$id = $model->id; // don't know, don't care

Behind the scenes, our method will use the primary key of the model to reflect the actual column. And if there is such a thing as an id column, then that value is used by default.

Conclusion

This is a very simple way to normalize the primary key, and saves you from having to remember these names while keeping your code as DRY as cheap hamburger buns. 🍔 You know the ones I'm talking about.