No news is good news
Eloquent ORM seems like a simple mechanism, but under the hood, there’s a lot of semi-hidden functions and less-known ways to achieve more with it. In this article, I will show you a few tricks.
Instead of this:
You can do this:
Also these will work:
Eloquent has quite a few functions that combine two methods, like “please do X, otherwise do Y”.
Example 1 –
Example 2 –
Do just this:
There is a magical place called boot() in an Eloquent model where you can override default behavior:
Probably one of the most popular examples is setting some field value at the moment of creating the model object. Let’s say you want to generate UUID field at that moment.
This is a typical way to define relationship:
But did you know that at this point we can already add where or orderBy?
For example, if you want a specific relationship for some type of users, also ordered by email, you can do this:
There are a few “parameters” of an Eloquent model, in the form of properties of that class. The most popular ones are probably these:
But wait, there’s more:
And there’s even more, I’ve listed the most interesting ones, for more please check out the code of default abstract Model class and check out all the traits used.
Everyone knows the
find() method, right?
I’m quite surprised how few people know about that it can accept multiple IDs as an array:
There’s an elegant way to turn this:
Yes, you can change the name of any field and append it as a suffix to “where” and it will work by magic.
Also, there are some pre-defined methods in Eloquent, related to date/time:
A little more complicated “trick”. What if you have forum topics but want to order them by latest post? Pretty common requirement in forums with last updated topics on the top, right?
First, describe a separate relationship for the latest post on the topic:
And then, in our controller, we can do this “magic”:
Many of us write conditional queries with “
if-else”, something like this:
But there’s a better way – to use
It may not feel shorter or more elegant, but the most powerful is passing of the parameters:
Let’s say you have Post belonging to Author and then Blade code:
But what if the author is deleted, or isn’t set for some reason? You will get an error, something like “property of non-object”.
Of course, you can prevent it like this:
But you can do it on Eloquent relationship level:
In this example, the
author() relation will return an empty App\Author model if no author is attached to the post.
Furthermore, we can assign default property values to that default model.
Imagine you have this:
Now, you want to order by that full_name? This won’t work:
The solution is quite simple. We need to order the results after we get them.
Notice that the function name is different – it’s not orderBy, it’s sortBy.
What if you want to have
User::all() always be ordered by name field? You can assign a global scope. Let’s go back to the
boot() method, which we mentioned already above.
Read more about Query Scopes here.
Sometimes we need to add raw queries to our Eloquent statements. Luckily, there are functions for that.
Short one. Without deep explanations, here’s the best way to make a copy of database entry:
Not exactly Eloquent related, it’s more about Collection, but still powerful – to process bigger datasets, you can chunk them into pieces.
We all know this Artisan command:
But did you know there are three useful flags to generate related files to the model?
- -m will create a migration file
- -c will create a controller
- -r will indicate that controller should be resourceful
Did you know that
->save() method can accept parameters? As a result, we can tell it to “ignore” updated_at default functionality to be filled with current timestamp. See this:
Here we’re overriding default updated_at with our pre-defined one.
Have you ever wondered what this code actually returns?
I mean, the update is performed in the database, but what would that $result contain?
The answer is affected rows. So if you need to check how many rows were affected, you don’t need to call anything else –
update() method will return this number for you.
What if you have and-or mix in your SQL query, like this:
… WHERE (gender = ‘Male’ and age >= 18) or (gender = ‘Female’ and age >= 65)
How to translate it into Eloquent? This is the wrong way:
The order will be incorrect. The right way is a little more complicated, using closure functions as sub-queries:
Finally, you can pass an array of parameters to
You can do it like this:
I’m sure there are even more hidden gems, but I hope at least a few of the ones above were new to you.