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:
$article = Article::find($article_id); $article->read_count++; $article->save();
You can do this:
$article = Article::find($article_id); $article->increment('read_count');
Also these will work:
Article::find($article_id)->increment('read_count'); Article::find($article_id)->increment('read_count', 10); // +10 Product::find($produce_id)->decrement('stock'); // -1
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:
$user = User::find($id); if (!$user) { abort (404); }
Do this:
$user = User::findOrFail($id); Example 2 – firstOrCreate():
Instead of:
$user = User::where('email', $email)->first(); if (!$user) { User::create([ 'email' => $email ]); }
Do just this:
$user = User::firstOrCreate(['email' => $email]);
3. Model boot() method
There is a magical place called boot() in an Eloquent model where you can override default behavior:
class User extends Model { public static function boot() { parent::boot(); static::updating(function($model) { // do some logging // override some property like $model->something = transform($something); }); } }
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.
public static function boot() { parent::boot(); self::creating(function ($model) { $model->uuid = (string)Uuid::generate(); }); }
4. Relationship with conditions and ordering
This is a typical way to define relationship:
public function users() { return $this->hasMany('App\User'); }
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:
public function approvedUsers() { return $this->hasMany('App\User')->where('approved', 1)->orderBy('email'); }
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:
class User extends Model { protected $table = 'users'; protected $fillable = ['email', 'password']; // which fields can be filled with User::create() protected $dates = ['created_at', 'deleted_at']; // which fields will be Carbon-ized protected $appends = ['field1', 'field2']; // additional values returned in JSON }
But wait, there’s more:
protected $primaryKey = 'uuid'; // it doesn't have to be "id" public $incrementing = false; // and it doesn't even have to be auto-incrementing! protected $perPage = 25; // Yes, you can override pagination count PER MODEL (default 15) const CREATED_AT = 'created_at'; const UPDATED_AT = 'updated_at'; // Yes, even those names can be overridden public $timestamps = false; // or even not used at all
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?
$user = User::find(1);
I’m quite surprised how few people know about that it can accept multiple IDs as an array:
$users = User::find([1,2,3]);
7. WhereX
There’s an elegant way to turn this:
$users = User::where('approved', 1)->get();
Into this:
$users = User::whereApproved(1)->get();
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:
8. Order by relationship
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:
public function latestPost() { return $this->hasOne(\App\Post::class)->latest(); }
And then, in our controller, we can do this “magic”:
$users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');
9. Eloquent::when() – no more if-else’s
Many of us write conditional queries with “if-else”, something like this:
if (request('filter_by') == 'likes') { $query->where('likes', '>', request('likes_amount', 0)); } if (request('filter_by') == 'date') { $query->orderBy('created_at', request('ordering_rule', 'desc')); }
But there’s a better way – to use when():
$query = Author::query(); $query->when(request('filter_by') == 'likes', function ($q) { return $q->where('likes', '>', request('likes_amount', 0)); }); $query->when(request('filter_by') == 'date', function ($q) { return $q->orderBy('created_at', request('ordering_rule', 'desc')); });
It may not feel shorter or more elegant, but the most powerful is passing of the parameters:
$query = User::query(); $query->when(request('role', false), function ($q, $role) { return $q->where('role_id', $role); }); $authors = $query->get();
10. BelongsTo Default Models
Let’s say you have Post belonging to Author and then Blade code:
{{ $post->author->name }}
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:
{{ $post->author->name ?? '' }}
But you can do it on Eloquent relationship level:
public function author() { return $this->belongsTo('App\Author')->withDefault(); }
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.
public function author() { return $this->belongsTo('App\Author')->withDefault([ 'name' => 'Guest Author' ]); }
11. Order by Mutator
Imagine you have this:
function getFullNameAttribute() { return $this->attributes['first_name'] . ' ' . $this->attributes['last_name']; }
Now, you want to order by that full_name? This won’t work:
$clients = Client::orderBy('full_name')->get(); // doesn't work
The solution is quite simple. We need to order the results after we get them.
$clients = Client::get()->sortBy('full_name'); // works!
Notice that the function name is different – it’s not orderBy, it’s sortBy.
12. 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.
protected static function boot() { parent::boot(); // Order by name ASC static::addGlobalScope('order', function (Builder $builder) { $builder->orderBy('name', 'asc'); }); }
Read more about Query Scopes here.
13. Raw query methods
Sometimes we need to add raw queries to our Eloquent statements. Luckily, there are functions for that.
// whereRaw $orders = DB::table('orders') ->whereRaw('price > IF(state = "TX", ?, 100)', [200]) ->get(); // havingRaw Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get(); // orderByRaw User::where('created_at', '>', '2016-01-01') ->orderByRaw('(updated_at - created_at) desc') ->get();
14. Replicate: make a copy of a row
Short one. Without deep explanations, here’s the best way to make a copy of database entry:
$task = Tasks::find(1); $newTask = $task->replicate(); $newTask->save();
15. Chunk() method for big tables
Not exactly Eloquent related, it’s more about Collection, but still powerful – to process bigger datasets, you can chunk them into pieces.
Instead of:
$users = User::all(); foreach ($users as $user) { // ...
You can do:
User::chunk(100, function ($users) { foreach ($users as $user) { // ... } });
16. Create additional things when creating a model
We all know this Artisan command:
php artisan make:model Company But did you know there are three useful flags to generate related files to the model? php artisan make:model Company -mcr -m will create a migration file -c will create a controller -r will indicate that controller should be resourceful
17. Override updated_at when saving
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:
$product = Product::find($id); $product->updated_at = '2019-01-01 10:00:00'; $product->save(['timestamps' => false]);
Here we’re overriding default updated_at with our pre-defined one.
18. What is the result of an update()?
Have you ever wondered what this code actually returns?
$result = $products->whereNull('category_id')->update(['category_id' => 2]);
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.
19. Transform brackets into an Eloquent query
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:
$q->where('gender', 'Male'); $q->orWhere('age', '>=', 18); $q->where('gender', 'Female'); $q->orWhere('age', '>=', 65);
The order will be incorrect. The right way is a little more complicated, using closure functions as sub-queries:
$q->where(function ($query) { $query->where('gender', 'Male') ->where('age', '>=', 18); })->orWhere(function($query) { $query->where('gender', 'Female') ->where('age', '>=', 65); })
20. orWhere with multiple parameters
Finally, you can pass an array of parameters to orWhere().
“Usual” way:
$q->where('a', 1); $q->orWhere('b', 2); $q->orWhere('c', 3); You can do it like this: $q->where('a', 1); $q->orWhere(['b' => 2, 'c' => 3]);
Comments
viagra (not verified)
Thu, 2019-12-05 11:43
Permalink
generic viagra sales
my web blog :: buy uk viagra online
AlfredoLow (not verified)
Fri, 2020-01-31 03:57
Permalink
Northwest Pharmacy
http://tribtaiti.webcindario.com/ buy viagra 25mg
legitimate canadian mail order pharmacies http://tribtaiti.webcindario.com/
drugstore online shopping reviews http://tribtaiti.webcindario.com/
AlfredoLow (not verified)
Sun, 2020-02-02 20:39
Permalink
canadian pharmacy viagra brand
https://viagracwithoutdoctor.com/ drugs for sale usa
online pharmacy canada https://viagracwithoutdoctor.com/
northwest pharmacies in canada https://viagracwithoutdoctor.com/
AlfredoLow (not verified)
Sun, 2020-02-02 22:48
Permalink
canadian drugstore
https://canadianlpharmacy.com/ canadian pharmacycanadian pharmacy
canadian prescriptions online serc 24 mg https://canadianlpharmacy.com/
canadian prescriptions online serc 24 mg https://canadianlpharmacy.com/
AlfredoLow (not verified)
Sun, 2020-02-02 23:59
Permalink
pharmacy times
https://viagrawwithoutdoctor.com/ drugs for sale in uk
canadian rx https://viagrawwithoutdoctor.com/
canadian pharmacies that ship to us https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 01:07
Permalink
canadian pharmacy king
https://viagrawwithoutdoctor.com/ canada drugs
canadian rx world pharmacy https://viagrawwithoutdoctor.com/
canadian pharmacy king https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 02:12
Permalink
canadian pharmacy no prescription
https://canadianhpharmacy.com/ canadian medications list
no 1 canadian pharcharmy online https://canadianhpharmacy.com/
pharmacy canada 24 https://canadianhpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 03:14
Permalink
canadian discount pharmacies in canada
https://viagracwithoutdoctor.com/ canadian pharmacy world
canadian pharmacy online 24 https://viagracwithoutdoctor.com/
no 1 canadian pharcharmy online https://viagracwithoutdoctor.com/
Ned (not verified)
Wed, 2020-08-12 07:03
Permalink
Add new comment | Moi Verhole
Hi, I do think this is an excellent site. I stumbledupon it
;) I may revisit yet again since i have book
marked it. Money and freedom is the best way to change, may
you be rich and continue to guide others. adreamoftrains best website hosting website hosting services
AlfredoLow (not verified)
Mon, 2020-02-03 04:20
Permalink
drugstore online reviews
https://viagrawwithoutdoctor.com/ trusted pharmacy canada scam
drugstore online canada https://viagrawwithoutdoctor.com/
good canadian online pharmacies https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 05:30
Permalink
canada online pharmacies reviews
https://viagrawwithoutdoctor.com/ canadian pharcharmy online24
northwestpharmacy https://viagrawwithoutdoctor.com/
canadian pharmaceuticals for usa sales https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 06:36
Permalink
most reliable canadian online pharmacies
https://canadianlpharmacy.com/ canadian drug store
canada medication list https://canadianlpharmacy.com/
pharmacy https://canadianlpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 07:40
Permalink
canadian medications 247
https://viagrawwithoutdoctor.com/ buy vistagra online safe
pharmacy https://viagrawwithoutdoctor.com/
canadian medications online https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 08:43
Permalink
buy viagrow pro
https://canadianlpharmacy.com/ online pharmacies india
online pharmacies india https://canadianlpharmacy.com/
canada pharmaceuticals online https://canadianlpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 09:49
Permalink
Northwest Pharmacy
https://canadianhpharmacy.com/ canada viagra
how safe are canadian online pharmacies https://canadianhpharmacy.com/
drugs for sale in canada https://canadianhpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 10:59
Permalink
canada medication cost
https://viagrawwithoutdoctor.com/ cialis from canada
online pharmacies mexico https://viagrawwithoutdoctor.com/
pharmacy canada plus https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 12:06
Permalink
drugstore online canada
https://viagrawwithoutdoctor.com/ aarp recommended canadian pharmacies
north west pharmacy canada https://viagrawwithoutdoctor.com/
canada vagra https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 13:12
Permalink
cialis from canada
https://viagrawwithoutdoctor.com/ canada medications cheap
drugs for sale https://viagrawwithoutdoctor.com/
canada drug pharmacy https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 14:53
Permalink
online pharmacy
https://viagrawwithoutdoctor.com/ buy vistagra usa
canadian pharmacys https://viagrawwithoutdoctor.com/
canada pharmaceuticals online https://viagrawwithoutdoctor.com/
Makayla (not verified)
Sun, 2020-06-21 12:08
Permalink
Add new comment | Moi Verhole
Wonderful blog! I found it while browsing on Yahoo News.
Do you have any suggestions on how to get listed in Yahoo News?
I've been trying for a while but I never seem to
get there! Many thanks
Feel free to surf to my website ... g him
AlfredoLow (not verified)
Mon, 2020-02-03 15:44
Permalink
canadian mail order pharmacies
https://canadianlpharmacy.com/ canada medication
drugstore online shopping https://canadianlpharmacy.com/
drugs for sale deep web https://canadianlpharmacy.com/
Ezekiel (not verified)
Mon, 2020-08-24 02:32
Permalink
Add new comment | Moi Verhole
Excellent beat ! I wish to apprentice while you amend your site, how could i subscribe for a blog site?
The account helped me a acceptable deal. I had been a little bit acquainted of this
your broadcast offered bright clear idea
Also visit my web page - cheap flights
AlfredoLow (not verified)
Mon, 2020-02-03 15:51
Permalink
online pharmacies legitimate
https://canadianlpharmacy.com/ canada online pharmacies medication
north west pharmacy canada https://canadianlpharmacy.com/
canadian pharmacy viagra brand https://canadianlpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 16:27
Permalink
are canadian online pharmacies safe
https://canadianhpharmacy.com/ online pharmacy
drugs for sale https://canadianhpharmacy.com/
canadian discount pharmacies in canada https://canadianhpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 17:05
Permalink
canada viagra
https://viagracwithoutdoctor.com/ north west pharmacies canada
canadian pharmacy world https://viagracwithoutdoctor.com/
canada medication pharmacy https://viagracwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 17:47
Permalink
drugs for sale in uk
https://viagrawwithoutdoctor.com/ canadian cialis
canadian rxlist https://viagrawwithoutdoctor.com/
canadian pharmacies stendra https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 18:31
Permalink
canadian drugs
https://viagracwithoutdoctor.com/ canadian medications pharmacy
canadian discount pharmacies in ocala fl https://viagracwithoutdoctor.com/
Canadian Pharmacy USA https://viagracwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 19:16
Permalink
drugs for sale online
https://canadianhpharmacy.com/ discount canadian pharmacies
canadian rx world pharmacy https://canadianhpharmacy.com/
online drug store https://canadianhpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 20:02
Permalink
buy viagra now
https://viagracwithoutdoctor.com/ canadian pharmaceuticals stocks
online pharmacies legitimate https://viagracwithoutdoctor.com/
aarp recommended canadian online pharmacies https://viagracwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 20:55
Permalink
canadian drugs
https://viagracwithoutdoctor.com/ canadian pharmacies shipping to usa
pharmacy canada best https://viagracwithoutdoctor.com/
online canadian pharmacies https://viagracwithoutdoctor.com/
AlfredoLow (not verified)
Mon, 2020-02-03 21:50
Permalink
canadian pharmacy king
https://canadianlpharmacy.com/ canada medication pharmacy
canadian pharmaceuticals for usa sales https://canadianlpharmacy.com/
legitimate canadian mail order pharmacies https://canadianlpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 22:43
Permalink
drugstore online canada
https://canadianlpharmacy.com/ canadian viagra
canadian mail order pharmacies https://canadianlpharmacy.com/
pharmacy canada online prescriptions https://canadianlpharmacy.com/
AlfredoLow (not verified)
Mon, 2020-02-03 23:25
Permalink
canadian drugstore
https://viagracwithoutdoctor.com/ canadian drug
canada drug https://viagracwithoutdoctor.com/
canadian pharmacy king https://viagracwithoutdoctor.com/
AlfredoLow (not verified)
Tue, 2020-02-04 00:18
Permalink
drugs for sale online
https://canadianlpharmacy.com/ legitimate canadian mail order pharmacies
canadian discount pharmacies in ocala fl https://canadianlpharmacy.com/
pharmacy canada plus https://canadianlpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 01:03
Permalink
canadian drugstore
https://canadianhpharmacy.com/ most reliable canadian pharmacies
canadian rx world pharmacy https://canadianhpharmacy.com/
canadian pharmacy cialis https://canadianhpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 01:47
Permalink
best canadian pharmacies online
https://canadianlpharmacy.com/ canada medications buy
order canadian prescriptions online https://canadianlpharmacy.com/
canada medication list https://canadianlpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 02:37
Permalink
prescription drugs without prior prescription
https://viagrawwithoutdoctor.com/ canadian discount pharmacies in ocala fl
online canadian discount pharmacies https://viagrawwithoutdoctor.com/
trust pharmacy of canada https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Tue, 2020-02-04 03:22
Permalink
canadian drugstore
https://viagracwithoutdoctor.com/ drugs for sale in uk
drugstore online https://viagracwithoutdoctor.com/
canadian pharmaceuticals online https://viagracwithoutdoctor.com/
AlfredoLow (not verified)
Tue, 2020-02-04 04:05
Permalink
online canadian pharmacy
https://canadianhpharmacy.com/ canadian pharmacies shipping to usa
canadian medications by mail https://canadianhpharmacy.com/
northwest pharmacy canada https://canadianhpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 04:49
Permalink
canada drug
https://viagrawwithoutdoctor.com/ canadian drugs
canadian prescriptions online https://viagrawwithoutdoctor.com/
drugstore online shopping https://viagrawwithoutdoctor.com/
AlfredoLow (not verified)
Tue, 2020-02-04 05:31
Permalink
trusted pharmacy canada scam
https://canadianhpharmacy.com/ canadian medications, liraglutide
is trust pharmacy in canada legitimate https://canadianhpharmacy.com/
canadian drug store https://canadianhpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 06:16
Permalink
canadian pharmaceuticals reviews
https://canadianhpharmacy.com/ canadian pharmacies shipping to usa
no 1 canadian pharcharmy online https://canadianhpharmacy.com/
canada pharmacies online prescriptions https://canadianhpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 07:04
Permalink
canadian pharmaceuticals companies
https://canadianhpharmacy.com/ canadian pharmacies shipping to usa
online pharmacy https://canadianhpharmacy.com/
drugstore online shopping reviews https://canadianhpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 07:50
Permalink
canadian discount pharmacies in canada
https://canadianlpharmacy.com/ canada online pharmacies legitimate
drugs for sale on internet https://canadianlpharmacy.com/
pharmacy near me https://canadianlpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 08:34
Permalink
pharmacy times
https://viagracwithoutdoctor.com/ canadian medications list
online canadian discount pharmacies https://viagracwithoutdoctor.com/
are canadian online pharmacies safe https://viagracwithoutdoctor.com/
AlfredoLow (not verified)
Tue, 2020-02-04 09:16
Permalink
canada medication prices
https://canadianlpharmacy.com/ pharmacy times
canadian medications by mail https://canadianlpharmacy.com/
canadian medications https://canadianlpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 09:58
Permalink
canadian medications 247
https://canadianhpharmacy.com/ canada online pharmacies reviews
canadianpharmacyusa24h is it legal https://canadianhpharmacy.com/
trusted pharmacy canada scam https://canadianhpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 10:41
Permalink
canadian pharmacies that ship to us
https://canadianlpharmacy.com/ drugstore online canada
top rated canadian pharmacies online https://canadianlpharmacy.com/
reputable canadian prescriptions online https://canadianlpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 11:23
Permalink
canada medication prices
https://canadianlpharmacy.com/ canada medications buy
online pharmacies https://canadianlpharmacy.com/
canadian pharmacycanadian pharmacy https://canadianlpharmacy.com/
AlfredoLow (not verified)
Tue, 2020-02-04 12:07
Permalink
the best canadian online pharmacies
https://viagracwithoutdoctor.com/ canadian medications pharmacy
canadian pharmacy meds https://viagracwithoutdoctor.com/
canada medication prices https://viagracwithoutdoctor.com/
Pages
Add new comment