Laravel Eloquent Tips and Tricks
Add columns without breaking tables
we add a school_name column to the contacts table
To add it right after the phone column, we write ->after(phone)
Increments and Decrements
Instead of this:
You can do this:
Also these will work:
Boot Method
There is a magical place called boot() in an Eloquent model where you can override default behavior:
If you want to generate some DB column value when creating a record, add it to the model’s boot() method. For example, if you have a field “number” and want to assign the next available number to the new record (like job::max(‘number’) + 1), do this:
Count on relationship
Laravel allows you to return to the total number of rows of a relationship module instead of getting a full data object.
Define a relation jobs
firstOr(function() {})
When searching for the first record, you want to perform some actions, when you don’t find it.
firstOrFail()
throws a404
Exception. You can usefirstOr(function() {})
instead. Laravel got your covered.
Automatic Column Value When Creating Records
If you want to generate some DB column value when creating record, add it to model’s
boot()
method. For example, if you have a field "position" and want to assign the next available position to the new record (likeCountry::max('position') + 1)
, do this:
Find Many
Eloquent method
find()
may accept multiple parameters, and then it returns a Collection of all records found, not just one Model:
Find by Key
You can also find multiple records with
whereKey()
method which takes care of which field is exactly your primary key (id
is the default but you may override it in Eloquent model):
Soft-Deletes with Query Builder
Don’t forget that soft-deletes will exclude entries when you use Eloquent, but won’t work if you use Query Builder.