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

http://tribtaiti.webcindario.com/ buy viagra 25mg
legitimate canadian mail order pharmacies http://tribtaiti.webcindario.com/
drugstore online shopping reviews http://tribtaiti.webcindario.com/

https://canadianlpharmacy.com/ canadian pharmacycanadian pharmacy
canadian prescriptions online serc 24 mg https://canadianlpharmacy.com/
canadian prescriptions online serc 24 mg https://canadianlpharmacy.com/

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

https://viagrawwithoutdoctor.com/ trusted pharmacy canada scam
drugstore online canada https://viagrawwithoutdoctor.com/
good canadian online pharmacies https://viagrawwithoutdoctor.com/

https://viagrawwithoutdoctor.com/ canadian pharcharmy online24
northwestpharmacy https://viagrawwithoutdoctor.com/
canadian pharmaceuticals for usa sales https://viagrawwithoutdoctor.com/

https://canadianlpharmacy.com/ online pharmacies india
online pharmacies india https://canadianlpharmacy.com/
canada pharmaceuticals online https://canadianlpharmacy.com/

https://canadianhpharmacy.com/ canada viagra
how safe are canadian online pharmacies https://canadianhpharmacy.com/
drugs for sale in canada https://canadianhpharmacy.com/

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

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

https://canadianlpharmacy.com/ canada online pharmacies medication
north west pharmacy canada https://canadianlpharmacy.com/
canadian pharmacy viagra brand https://canadianlpharmacy.com/

https://viagracwithoutdoctor.com/ north west pharmacies canada
canadian pharmacy world https://viagracwithoutdoctor.com/
canada medication pharmacy https://viagracwithoutdoctor.com/

https://viagracwithoutdoctor.com/ canadian medications pharmacy
canadian discount pharmacies in ocala fl https://viagracwithoutdoctor.com/
Canadian Pharmacy USA https://viagracwithoutdoctor.com/

https://canadianhpharmacy.com/ discount canadian pharmacies
canadian rx world pharmacy https://canadianhpharmacy.com/
online drug store https://canadianhpharmacy.com/

https://viagracwithoutdoctor.com/ canadian pharmaceuticals stocks
online pharmacies legitimate https://viagracwithoutdoctor.com/
aarp recommended canadian online pharmacies https://viagracwithoutdoctor.com/

https://viagracwithoutdoctor.com/ canadian pharmacies shipping to usa
pharmacy canada best https://viagracwithoutdoctor.com/
online canadian pharmacies https://viagracwithoutdoctor.com/

https://canadianlpharmacy.com/ canada medication pharmacy
canadian pharmaceuticals for usa sales https://canadianlpharmacy.com/
legitimate canadian mail order pharmacies https://canadianlpharmacy.com/

https://canadianlpharmacy.com/ canadian viagra
canadian mail order pharmacies https://canadianlpharmacy.com/
pharmacy canada online prescriptions https://canadianlpharmacy.com/

https://canadianlpharmacy.com/ legitimate canadian mail order pharmacies
canadian discount pharmacies in ocala fl https://canadianlpharmacy.com/
pharmacy canada plus https://canadianlpharmacy.com/

https://canadianhpharmacy.com/ most reliable canadian pharmacies
canadian rx world pharmacy https://canadianhpharmacy.com/
canadian pharmacy cialis https://canadianhpharmacy.com/

https://canadianlpharmacy.com/ canada medications buy
order canadian prescriptions online https://canadianlpharmacy.com/
canada medication list https://canadianlpharmacy.com/

https://viagrawwithoutdoctor.com/ canadian discount pharmacies in ocala fl
online canadian discount pharmacies https://viagrawwithoutdoctor.com/
trust pharmacy of canada https://viagrawwithoutdoctor.com/

https://canadianhpharmacy.com/ canadian pharmacies shipping to usa
canadian medications by mail https://canadianhpharmacy.com/
northwest pharmacy canada https://canadianhpharmacy.com/

https://viagrawwithoutdoctor.com/ canadian drugs
canadian prescriptions online https://viagrawwithoutdoctor.com/
drugstore online shopping https://viagrawwithoutdoctor.com/

https://canadianhpharmacy.com/ canadian medications, liraglutide
is trust pharmacy in canada legitimate https://canadianhpharmacy.com/
canadian drug store https://canadianhpharmacy.com/

https://canadianhpharmacy.com/ canadian pharmacies shipping to usa
no 1 canadian pharcharmy online https://canadianhpharmacy.com/
canada pharmacies online prescriptions https://canadianhpharmacy.com/

https://canadianhpharmacy.com/ canadian pharmacies shipping to usa
online pharmacy https://canadianhpharmacy.com/
drugstore online shopping reviews https://canadianhpharmacy.com/

https://viagracwithoutdoctor.com/ canadian medications list
online canadian discount pharmacies https://viagracwithoutdoctor.com/
are canadian online pharmacies safe https://viagracwithoutdoctor.com/

https://canadianhpharmacy.com/ canada online pharmacies reviews
canadianpharmacyusa24h is it legal https://canadianhpharmacy.com/
trusted pharmacy canada scam https://canadianhpharmacy.com/

https://canadianlpharmacy.com/ drugstore online canada
top rated canadian pharmacies online https://canadianlpharmacy.com/
reputable canadian prescriptions online https://canadianlpharmacy.com/

https://canadianlpharmacy.com/ canada medications buy
online pharmacies https://canadianlpharmacy.com/
canadian pharmacycanadian pharmacy https://canadianlpharmacy.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.
2 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.