Laravel Eloquent Tips and Tricks make you more productivity #1

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.

1. Increments and Decrements

Instead of this:

You can do this:

Also these will work:

2. XorY methods

Eloquent has quite a few functions that combine two methods, like “please do X, otherwise do Y”.

Example 1 — findOrFail():

Instead of:

Do this:

Example 2 — firstOrCreate():

Instead of:

Do just this:

3. Model boot() method

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.

4. Relationship with conditions and ordering

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:

5. Model properties: timestamps, appends etc.

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.

6. Find multiple entries

Everyone knows the find() method, right?

I’m quite surprised how few people know about that it can accept multiple IDs as an array:

7. WhereX
There’s an elegant way to turn this:

Into 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:

That’s It, If you enjoyed these Eloquent tips dont forget clapp it 😝

DevOps Engineer & Fullstack Developer, someone who has a high curiosity 😁