Hi, today I’m going to share with you some tips and tricks in Laravel Eloquent ORM. There are a lot of semi-hidden functions and less-known ways to achieve more with it. Let’s dive in:


1- The Exists Property

The exists property is used to show whether the object exists in the database or not. When you create a new model instance the exists property will be set to false. Once your model is saved or retrieved from the database the exists property will be set to true.


2- Examining attribute changes

The methods isDirty()isClean(), and wasChanged() examine the internal state of your model and determine how its attributes have changed since their original loading.

isDirty() method find out if any attributes have been changed since the model was loaded. You can also pass attribute name to determine if it’s dirty.

isClean() method is the opposite of isDirty().

wasChanged() method find out if any attributes were changed when the model was last saved within the current request cycle. You can also pass attribute name to determine if it was changed.


3- Increments and Decrements

Instead of this:

You can do this:

You can do this:


4- XorY methods

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


Example 1 – findOrFail():

The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

Instead of:

Do this:

Example 2 – firstOrCreate():

The firstOrCreate method tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter:

Instead of:

Do this:

Example 3 – firstOrNew():

The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:

Instead of:

Do this:


Example 4 – firstOr():

Sometimes you may wish to retrieve the first result of a query or perform some other action if no results are found. The firstOr method will return the first result that is found or, if no results are found, execute the given callback. The result of the callback will be considered the result of the firstOr method


Example 5 – updateOrCreate():

The updateOrCreate method attempts to find a Model matching the constraints passed as the first parameter. If a matching Model is found, it will update the match with the attributes passed as the second parameter. If no matching Model is found a new Model will be created with both the constraints passed as the first parameter and the attributes passed as the second parameter. Like the firstOrCreate method, updateOrCreate persists the model, so there’s no need to call save():

Instead of:

Do this:

Read Also  Laravel .env variable in Blade and Controller


5- Eloquent Model’s boot() method

There is a magical place called boot() in an Eloquent model where you can override the default behavior. One of the most popular examples is setting some field value at the moment of creating the model object:


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

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.



7- The push() method.

You can save a model and its corresponding relationships using the push() method.

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.


8- The find() method.

The find() or findOrFail()method is quite common, but you’d be quite surprised how few people know that it can accept multiple IDs as an array:

But wait, there’s more. you can also specify the attributes to select as the second argument:


9- Get original attributes

After mutating an Eloquent record you can get the original attributes by calling getOriginal()


10- Get changed attributes

Retrieve the changed attributes of a model using getChanges()


11- Reload fresh model

Reload a fresh model instance from the database using fresh()


12- Reload existing model

You can reload an existing model with fresh values from database using refresh()


13- Check if models are the same

Determine if two models have the same ID and belong to the same table using is()


14- Clone a model

You can clone a model using replicate(). It will create a copy of the model into a new, non-existing instance.


15- Custom deleted_at column

By default, Laravel handles soft deletes using deleted_at column. You can change this by explicitly defining the DELETED_AT property.


16- The when() Eloquent.

Instead of using if and else conditionals, Eloquent provides a convenient method when(). For example, when we are filtering some table based on multiple conditions:


17- BelongsTo Default Models

Let’s say you have Post belonging to Author and then Blade code:

Read Also  Create Custom Maintenance Page in Laravel

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.


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


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


20- Order by Mutator

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.


21- Chunk() method for big datasets

When we are working with big datasets instead of getting all the records for some table we can get a certain amount with the chunk() method like this:


22- Create additional things when creating a model

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


23- Transform brackets into an Eloquent query

So, imagine we have the following SQL query:

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:


24- Use hasMany() to create many

If we have a hasMany() relationship, we can use saveMany() to save multiple “child” entries from our “parent” object, all in one sentence:


25- orWhere with multiple parameters

Finally, you can pass an array of parameters to orWhere().
Usual way:

You can do it like this:


26- Default ordering in global scope

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.


27- Force a delete on a soft delete model

In some situations you want to remove a soft deleted model from your database. This can be done by using the forceDelete method.


28- Without events

Sometimes you want to create or update a model without firing any events. In Laravel it is possible to execute a callback without firing any model events for any model type.


29- Convert a model or collection to array

The toArray can convert a model or collection to a plain PHP array.


30- Has

The has method probably doesn’t need much explanation. Chances are you’re using it on a regular basis. The has method checks whether a relationship exists. To stick with the previous example, we could retrieve all the users that have posted a blog by using the following line of code:

We could even expand this check. Let’s say we only want to get the users that have at least 5 blogs. We can do that by adding some parameters to the has method.

But did you also know that you could get all the users that have at least one blog and one comment?
You can nest has statements using the dot notation.


Cheers ! Happy Coding 🙂

    No Comments

    Leave a Reply

    your email address will not be published. required fields are marked *