Life Goes On

COVID-19 marked its one-year anniversary as a global pandemic on March 11, 2021. And on March 17, it will be one year since I’ve been working from home because of the dread virus. There have been a…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Laravel Eloquent Amazing Tips and Tricks

Certain tasks within Laravel’s Eloquent ORM can become very repetitive and tedious within larger applications.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:

This isn’t a very well known trick and, currently, is not mentioned in the Laravel documentation. Let’s take the trivial example of a blog and generate both a model and a migration for posts.

The above can easily be condensed into a single command:

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

Example 1findOrFail():

Instead of:

Do this:

Example 2firstOrCreate():

Instead of:

Do just this:

There is a magical place called boot() in an Eloquent model where you can override default behavior:

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:

In many cases, you may want to be able to access a computed property of an Eloquent model that doesn’t exist as a value in the database. Sorry for the jargon! Let’s look at an example. We have a users table, within which we have two columns: forenames and surname. If we want to display a users full name within one of our views, we’d have to do something like this:

Firstly, it’s likely that we’ll be using that little snippet in multiple places throughout our application and it’s impractical to type that over and over. Secondly, ugh. That syntax is ugly and looks sooooo out of place. Let’s have a look at how we can clean that up a bit with accessors (A.K.A. attributes). Let’s create a new method within our User model.

Similarly to how Eloquent recognises the scopes, anything encapsulated in the words get and Attribute in a method name will automatically be picked up by Eloquent as an accesor. So now, when we try to execute the following snippet, we should get the same result as earlier:

Not only is this reusable and much easier to type, but it’s also much more readable.

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:

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:

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 when():

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:

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.

… for lack of a better term. Eloquent is extremely intelligent with certain methods such as where().

Take the following examples:

Ah, much cleaner!

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.

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 data sets, you can chunk them into pieces.

Instead of:

You can do:

We all know this Artisan command:

But did you know there are three useful flags to generate related files to the model?

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:

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 orWhere().
“Usual” way:

You can do it like this:

These few gems that i normally use but i am sure there will be more of such awesome Laravel Eloquent tips and tricks that you can easily use in one of your project. If you also know any of awesome Eloquent tips then do post them in the comment section below. If you like this article then do comment , follow or even share this article.

Add a comment

Related posts:

FBI Hacked

Thousands of FBI agents had their administrative data such as names, job titles, and phone numbers exposed to the public by a group of hackers. It is reported that the group of hackers exploited the…

Democracy At The Brink

Eugene Robinson of The Washington Post joins Charles Pierce of Esquire in calling out the fact that we are deep into a Constitutional crisis: Robinson points out that in response to Trump’s absurd…

Stablecoin Interview with Vault

Our guest for this podcast is Ranjeet Sodhi, Co-Founder and CEO of Vault, a USD-pegged stablecoin backed by and redeemable for LBMA gold and USD. This interview is <25 minutes long, feel free to…