Laravel Model Secret

Mohasin Hossain
2 min readFeb 13, 2022

In this tutorial, I am going to show you some Laravel Model Secret that will really help you to be a better Laravel developer.

Sometimes you may face such a wired situation that the column is not returning what you actually want that time this secret will help you some.

Imagine your User model in your Laravel application. There is some code like below.

So, in the user model, the birthday column has multiple return values like we are casting, using an accessor even it can come from another table through relationship or the default column value in the user table.

return User::first()->birthday;

Now, what do you think if I call the birthday column like above from the user table what will return it actually? the casting value or accessor value or default value or the relationship value if exists.

It’s okay, let me show you the secret Laravel itself doing under the hood when we return a column value.

When we return a column value Laravel check multiple things & return the value in a very specific order. let me explain the order that Laravel does.

At first Laravel checks if the column is using an accessor if the column using an accessor then accessor value returns. Secondly, if it’s not using any accessor the Laravel check if the column is casting, if the column is casting then it returns the casting value. Thirdly if the column has no accessor or even casting the Laravel returns the default database column value. And last but least if the column has no accessor, not casting yet, and does not exist in the user table then Laravel returns the Relationship value if has.

So in short, the order is accessor > casting > default column value> relationship value

In conclusion, this is something you may not find in Laravel documentation, I just tried to show you the secret of how it works under the hood! Please feel free to leave a comment if you have any feedback, questions or want me to write about another PHP/Laravel related topic.

--

--

Mohasin Hossain

Senior Software Engineer | Mentor @ADPList | Backend focused | PHP, JavaScript, Laravel, Vue.js, Nuxt.js, MySQL, TDD, CI/CD, Docker, Linux