Status message

Maintenant, vous regardez: Laravel Eloquent Tips and Tricks

Laravel Eloquent Tips and Tricks

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:

  1. $article = Article::find($article_id);
  2. $article->read_count++;
  3. $article->save();

You can do this:

  1. $article = Article::find($article_id);
  2. $article->increment('read_count');

Also these will work:

  1. Article::find($article_id)->increment('read_count');
  2. Article::find($article_id)->increment('read_count', 10); // +10
  3. 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:

  1. $user = User::find($id);
  2. if (!$user) { abort (404); }

Do this:

  1. $user = User::findOrFail($id);
  2. Example 2 – firstOrCreate():

Instead of:

  1. $user = User::where('email', $email)->first();
  2. if (!$user) {
  3. User::create([
  4. 'email' => $email
  5. ]);
  6. }

Do just this:

  1. $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:

  1. class User extends Model
  2. {
  3. public static function boot()
  4. {
  5. parent::boot();
  6. static::updating(function($model)
  7. {
  8. // do some logging
  9. // override some property like $model->something = transform($something);
  10. });
  11. }
  12. }

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.

  1. public static function boot()
  2. {
  3. parent::boot();
  4. self::creating(function ($model) {
  5. $model->uuid = (string)Uuid::generate();
  6. });
  7. }

4. Relationship with conditions and ordering

This is a typical way to define relationship:

  1. public function users() {
  2. return $this->hasMany('App\User');
  3. }

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:

  1. public function approvedUsers() {
  2. return $this->hasMany('App\User')->where('approved', 1)->orderBy('email');
  3. }

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:

  1. class User extends Model {
  2. protected $table = 'users';
  3. protected $fillable = ['email', 'password']; // which fields can be filled with User::create()
  4. protected $dates = ['created_at', 'deleted_at']; // which fields will be Carbon-ized
  5. protected $appends = ['field1', 'field2']; // additional values returned in JSON
  6. }

But wait, there’s more:

  1. protected $primaryKey = 'uuid'; // it doesn't have to be "id"
  2. public $incrementing = false; // and it doesn't even have to be auto-incrementing!
  3. protected $perPage = 25; // Yes, you can override pagination count PER MODEL (default 15)
  4. const CREATED_AT = 'created_at';
  5. const UPDATED_AT = 'updated_at'; // Yes, even those names can be overridden
  6. 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?

  1. $user = User::find(1);

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

  1. $users = User::find([1,2,3]);

7. WhereX

There’s an elegant way to turn this:

  1. $users = User::where('approved', 1)->get();

Into this:

  1. $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:

  1. User::whereDate('created_at', date('Y-m-d'));
  2. User::whereDay('created_at', date('d'));
  3. User::whereMonth('created_at', date('m'));
  4. User::whereYear('created_at', date('Y'));

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:

  1. public function latestPost()
  2. {
  3. return $this->hasOne(\App\Post::class)->latest();
  4. }

And then, in our controller, we can do this “magic”:

  1. $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:

  1. if (request('filter_by') == 'likes') {
  2. $query->where('likes', '>', request('likes_amount', 0));
  3. }
  4. if (request('filter_by') == 'date') {
  5. $query->orderBy('created_at', request('ordering_rule', 'desc'));
  6. }

But there’s a better way – to use when():

  1. $query = Author::query();
  2. $query->when(request('filter_by') == 'likes', function ($q) {
  3. return $q->where('likes', '>', request('likes_amount', 0));
  4. });
  5. $query->when(request('filter_by') == 'date', function ($q) {
  6. return $q->orderBy('created_at', request('ordering_rule', 'desc'));
  7. });

It may not feel shorter or more elegant, but the most powerful is passing of the parameters:

  1. $query = User::query();
  2. $query->when(request('role', false), function ($q, $role) {
  3. return $q->where('role_id', $role);
  4. });
  5. $authors = $query->get();

10. BelongsTo Default Models
Let’s say you have Post belonging to Author and then Blade code:

  1. {{ $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:

  1. {{ $post->author->name ?? '' }}

But you can do it on Eloquent relationship level:

  1. public function author()
  2. {
  3. return $this->belongsTo('App\Author')->withDefault();
  4. }

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.

  1. public function author()
  2. {
  3. return $this->belongsTo('App\Author')->withDefault([
  4. 'name' => 'Guest Author'
  5. ]);
  6. }

11. Order by Mutator
Imagine you have this:

  1. function getFullNameAttribute()
  2. {
  3. return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
  4. }

Now, you want to order by that full_name? This won’t work:

  1. $clients = Client::orderBy('full_name')->get(); // doesn't work

The solution is quite simple. We need to order the results after we get them.

  1. $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.

  1. protected static function boot()
  2. {
  3. parent::boot();
  5. // Order by name ASC
  6. static::addGlobalScope('order', function (Builder $builder) {
  7. $builder->orderBy('name', 'asc');
  8. });
  9. }

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.

  1. // whereRaw
  2. $orders = DB::table('orders')
  3. ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
  4. ->get();
  6. // havingRaw
  7. Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
  9. // orderByRaw
  10. User::where('created_at', '>', '2016-01-01')
  11. ->orderByRaw('(updated_at - created_at) desc')
  12. ->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:

  1. $task = Tasks::find(1);
  2. $newTask = $task->replicate();
  3. $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:

  1. $users = User::all();
  2. foreach ($users as $user) {
  3. // ...

You can do:

  1. User::chunk(100, function ($users) {
  2. foreach ($users as $user) {
  3. // ...
  4. }
  5. });

16. Create additional things when creating a model
We all know this Artisan command:

  1. php artisan make:model Company
  2. But did you know there are three useful flags to generate related files to the model?
  4. php artisan make:model Company -mcr
  5. -m will create a migration file
  6. -c will create a controller
  7. -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:

  1. $product = Product::find($id);
  2. $product->updated_at = '2019-01-01 10:00:00';
  3. $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?

  1. $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:

  1. ... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65)

How to translate it into Eloquent? This is the wrong way:

  1. $q->where('gender', 'Male');
  2. $q->orWhere('age', '>=', 18);
  3. $q->where('gender', 'Female');
  4. $q->orWhere('age', '>=', 65);

The order will be incorrect. The right way is a little more complicated, using closure functions as sub-queries:

  1. $q->where(function ($query) {
  2. $query->where('gender', 'Male')
  3. ->where('age', '>=', 18);
  4. })->orWhere(function($query) {
  5. $query->where('gender', 'Female')
  6. ->where('age', '>=', 65);
  7. })

20. orWhere with multiple parameters
Finally, you can pass an array of parameters to orWhere().
“Usual” way:

  1. $q->where('a', 1);
  2. $q->orWhere('b', 2);
  3. $q->orWhere('c', 3);
  4. You can do it like this:
  6. $q->where('a', 1);
  7. $q->orWhere(['b' => 2, 'c' => 3]);


Comments drugs for sale deep web
canada drug
canadian pharmacy no prescription canadian pharmacies stendra
canadian discount pharmacies in ocala fl
reputable canadian prescriptions online drugs for sale
online canadian discount pharmacies
canadian discount pharmacies in canada online pharmacy
order canadian prescriptions online
best canadian pharmacies online drugs for sale usa
canadian pharmacy viagra brand
online pharmacies tech school drugs for sale usa
canadian discount pharmacies in canada
canada medication pharmacy canadian pharmaceuticals for usa sales
best canadian pharmacy
drugstore online india canadianpharmacyusa24h is it legal
canadian medications by mail
canadian pharmacycanadian pharmacy best canadian mail order pharmacies
canadian medications 247
northwest pharmacy canada best canadian pharmacies online
canadianpharmacyusa24h is it legal
canadian pharmaceuticals for usa sales canadian pharmacies-24h
canadian prescriptions online
canadian pharmacies that are legit reputable canadian prescriptions online
aarp recommended canadian pharmacies
pharmacy times most reliable canadian pharmacies
canadian medications list
buy viagrow are canadian online pharmacies safe
pharmacy canada reviews
online canadian pharmacy most reliable canadian online pharmacies
online pharmacies india
drugs for sale in uk canadian medications list
most reliable canadian pharmacies
pharmacy near me canadian medications list
trust pharmacy canada reviews
canadianpharmacyusa24h northwest pharmacy canada
canadian pharmacies that ship to us
canadian online pharmacies legal canada medication prices
online pharmacies of canada
canada medication pharmacy canadian pharmaceuticals stocks
canada pharmaceuticals online
canadian pharmaceuticals most reliable canadian online pharmacies
canada pharmacies online prescriptions
canadian pharmacies without an rx drugstore online canada
canada online pharmacies legitimate
canadian discount pharmacies in canada cialis from canada
good canadian online pharmacies
prescriptions from canada without northwest pharmacies in canada
northwest pharmacies mail order
canadian prescriptions online canada medications buy
canada medication pharmacy
canadianpharmacyusa24h is it legal aarp recommended canadian pharmacies
canada online pharmacy
northwest pharmacy canada


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
11 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.