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();
  4.  
  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();
  5.  
  6. // havingRaw
  7. Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
  8.  
  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?
  3.  
  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:
  5.  
  6. $q->where('a', 1);
  7. $q->orWhere(['b' => 2, 'c' => 3]);

Tags:

Comments

https://viagracwithoutdoctor.com/ online pharmacies tech school
trusted pharmacy canada scam https://viagracwithoutdoctor.com/
how safe are canadian online pharmacies https://viagracwithoutdoctor.com/

https://canadianhpharmacy.com/ canadian pharmaceuticals
canada medications information https://canadianhpharmacy.com/
online pharmacies in usa https://canadianhpharmacy.com/

https://viagracwithoutdoctor.com/ buy viagra usa
canadian pharmacy viagra brand https://viagracwithoutdoctor.com/
canadian pharmacy no prescription https://viagracwithoutdoctor.com/

https://canadianhpharmacy.com/ online canadian pharmacies
canadian pharmacy cialis https://canadianhpharmacy.com/
online pharmacies in usa https://canadianhpharmacy.com/

https://canadianhpharmacy.com/ canadian online pharmacies reviews
reputable canadian prescriptions online https://canadianhpharmacy.com/
drugs for sale in canada https://canadianhpharmacy.com/

https://canadianlpharmacy.com/ canadian pharmaceuticals reviews
canadian pharmacy viagra brand https://canadianlpharmacy.com/
canadian pharmaceuticals stocks https://canadianlpharmacy.com/

https://canadianlpharmacy.com/ canada online pharmacies medication
prescription drugs without prior prescription https://canadianlpharmacy.com/
canadian drugstore https://canadianlpharmacy.com/

https://viagrawwithoutdoctor.com/ canadian pharmacycanadian pharmacy
canadian pharmaceuticals nafta https://viagrawwithoutdoctor.com/
global pharmacy canada https://viagrawwithoutdoctor.com/

https://viagracwithoutdoctor.com/ northwest pharmacies mail order
canadian medications, liraglutide https://viagracwithoutdoctor.com/
Northwest Pharmacy https://viagracwithoutdoctor.com/

https://viagracwithoutdoctor.com/ canadian medications by mail
canadianpharmacyusa24h is it legal https://viagracwithoutdoctor.com/
northwestpharmacy https://viagracwithoutdoctor.com/

https://viagracwithoutdoctor.com/ canada online pharmacies surrey
northwest pharmacy canada https://viagracwithoutdoctor.com/
canadian discount pharmacies in ocala fl https://viagracwithoutdoctor.com/

https://canadianlpharmacy.com/ the best canadian online pharmacies
good canadian online pharmacies https://canadianlpharmacy.com/
canada pharmaceuticals online https://canadianlpharmacy.com/

https://viagracwithoutdoctor.com/ canada online pharmacies medication
canada online pharmacies for men https://viagracwithoutdoctor.com/
canadian viagra https://viagracwithoutdoctor.com/

https://canadianlpharmacy.com/ northwest pharmacies in canada
canadian pharmaceuticals nafta https://canadianlpharmacy.com/
canadian online pharmacies reviews https://canadianlpharmacy.com/

https://canadianhpharmacy.com/ canadian pharmacies
online pharmacy canada https://canadianhpharmacy.com/
good canadian online pharmacies https://canadianhpharmacy.com/

https://canadianhpharmacy.com/ drugs for sale in mexico
online pharmacies in usa https://canadianhpharmacy.com/
drugstore online india https://canadianhpharmacy.com/

https://canadianlpharmacy.com/ online pharmacies india
drugs for sale on internet https://canadianlpharmacy.com/
canadian pharmaceuticals companies https://canadianlpharmacy.com/

https://canadianhpharmacy.com/ canada vagra
canadian online pharmacies reviews https://canadianhpharmacy.com/
canadian online pharmacies legal https://canadianhpharmacy.com/

https://canadianlpharmacy.com/ north west pharmacy canada
canada medications information https://canadianlpharmacy.com/
canadian online pharmacy https://canadianlpharmacy.com/

https://canadianhpharmacy.com/ canada online pharmacies legitimate
trusted pharmacy canada scam https://canadianhpharmacy.com/
canadian pharmaceuticals companies https://canadianhpharmacy.com/

https://canadianhpharmacy.com/ drugstore online
canada medication https://canadianhpharmacy.com/
canadianpharmacyusa24h is it legal https://canadianhpharmacy.com/

https://viagrawwithoutdoctor.com/ legitimate canadian mail order pharmacies
trust pharmacy of canada https://viagrawwithoutdoctor.com/
online pharmacies legitimate https://viagrawwithoutdoctor.com/

https://viagracwithoutdoctor.com/ canadian online pharmacies legitimate
prescription drugs without prior prescription https://viagracwithoutdoctor.com/
trust pharmacy canada https://viagracwithoutdoctor.com/

https://viagracwithoutdoctor.com/ canada medication list
canada medication pharmacy https://viagracwithoutdoctor.com/
online pharmacies legitimate https://viagracwithoutdoctor.com/

https://canadianlpharmacy.com/ canadian prescriptions online serc 24 mg
trusted pharmacy canada scam https://canadianlpharmacy.com/
canadian pharmaceuticals online https://canadianlpharmacy.com/

https://viagrawwithoutdoctor.com/ drugs for sale in uk
canadian pharmaceuticals online https://viagrawwithoutdoctor.com/
canada online pharmacies reviews https://viagrawwithoutdoctor.com/

https://viagracwithoutdoctor.com/ canadian pharmacy world
canada online pharmacies for men https://viagracwithoutdoctor.com/
trust pharmacy canada reviews https://viagracwithoutdoctor.com/

https://viagracwithoutdoctor.com/ canadian pharmaceuticals reviews
canadian pharmaceuticals online https://viagracwithoutdoctor.com/
canadian medications pharmacy https://viagracwithoutdoctor.com/

https://canadianlpharmacy.com/ is trust pharmacy in canada legitimate
canadian pharmacy cialis https://canadianlpharmacy.com/
no 1 canadian pharcharmy online https://canadianlpharmacy.com/

https://canadianhpharmacy.com/ online canadian discount pharmacies
northwest pharmacies in canada https://canadianhpharmacy.com/
online pharmacies of canada https://canadianhpharmacy.com/

Pages

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.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
6 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.