20 Of The Lesser-Known Tips And Tricks For Laravel Eloquent Eloquent ORM appears like a simple mechanism in the first instance. But upon taking a closer look, we come to discover that it withholds numerous functions that are semi-hidden. There are also a few lesser-known ways using which the functions can be put to the best possible avail. Only the best Laravel developers India may be aware of the tips and techniques mentioned in this article. Cyblance is the best Laravel development company for your Laravel Eloquent development requirements. Let us consider some Laravel Eloquent ORM tricks in this article:
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
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
Eloquent has several functions that are a combination of two methods. They may go as“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 spot known as the boot () in an Eloquent model. One can override the default behavior over here. 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); });
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
} }
One of the most illustrated Eloquent examples involves setting the field value at the same time when one creates a model object. How does one go about generating a UUID field at the same time? public static function boot() { parent::boot(); self::creating(function ($model) { $model->uuid = (string)Uuid::generate(); }); }
4. Relationships involving conditions and ordering The following is a typical way in which a relationship is defined: public function users() { return $this->hasMany('App\User'); }
We can also add where or orderBy at this point. Just as an instance, in case you require a specific relationship for privileged users, which is ordered by email as well, this can be achieved in the following way: public function approvedUsers() { return $this->hasMany('App\User')->where('approved', 1)->orderBy('email'); }
5. Model properties: timestamps, appends, etc. In the Eloquent model, there are some parameters which are in the format of properties of that particular class. The following are the most frequently used among them. class User extends Model { protected $table = 'users';
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
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 }
There are some more as well. 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
6. Find multiple entries find() is among the most frequently used methods. $user = User::find(1);
Interestingly, find () accepts multiple ids as an array $users = User::find([1,2,3]);
7. WhereX There’s an elegant way in which the function can be used. Turn this $users = User::where('approved', 1)->get();
Into this: $users = User::whereApproved(1)->get();
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
This exemplifies that a user can not just change the name of any field, but also use it as a suffix to where. It will work. Let us now take a look at the pre-defined methods in Eloquent, which are related to date/time. User::whereDate('created_at', date('Y-m-d')); User::whereDay('created_at', date('d')); User::whereMonth('created_at', date('m')); User::whereYear('created_at', date('Y'));
8. Order by relationship This particular trick is more towards the complicated side. Let us consider a unique instance. One has forum topics but intends to order them by the latest post. This is a frequent requirement in forums, wherein one prefers to have the recently updated posts towards the top. To proceed with the requirement, a separate relationship is first described for the latest post over the topic. public function latestPost() { return $this->hasOne(\App\Post::class)->latest(); }
Then one uses the following code in the controller. $users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');
9. Eloquent::when() – no more if-else’s We characteristically write conditional queries with “if-else” in the following way. 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')); }
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
But, when() may be used in a better way. $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')); });
This does not appear shortly. It does not appear more elegant either. But the passing of parameters is more powerful. $query = User::query(); $query->when(request('role', false), function ($q, $role) { return $q->where('role_id', $role); }); $authors = $query->get();
10. Belongs to Default Models Let’s suppose you have a post, which belongs to the Author and the Blade code: {{ $post->author->name }}
What happens if the author is deleted, or is not set due to any reason? You’ll get an error message, which says something like ‘property of non-object’. Using the following method prevents the same. {{ $post->author->name ?? '' }}
You can also do it at the Eloquent relationship level public function author() { return $this->belongsTo('App\Author')->withDefault(); }
In the example mentioned, an empty App\Author model is returned by the author() relation. This is the case when no author is attached to the post. We can also assign default property values to the default model. public function author() {
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
return $this->belongsTo('App\Author')->withDefault([ 'name' => 'Guest Author' ]); }
11. Order by Mutator Let us suppose that the following is the case: function getFullNameAttribute() { return $this->attributes['first_name'] . ' ' . $this->attributes['last_name']; }
When do you want to order this by full_name? , the following won’t work $clients = Client::orderBy('full_name')->get(); // doesn't work
The resolution is simple. We order the results after getting them. $clients = Client::get()->sortBy('full_name'); // works!
Here, notice the difference in the function name. It’s not orderBy. It’s a sortBy.
12. Default ordering in the global scope What happens if one wants User::all () to always be ordered by name field? One can assign a global scope. Let us return to the boot () method, which we have already mentioned above. protected static function boot() { parent::boot(); // Order by name ASC static::addGlobalScope('order', function (Builder $builder) { $builder->orderBy('name', 'asc'); }); }
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
13. Raw query methods There are times when one needs to add raw queries to Eloquent statements. A few functions are available for the same as well. // 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. Replication: make a copy of a row The following is the simplest way to make a copy of a database entry. $task = Tasks::find(1); $newTask = $task->replicate(); $newTask->save();
15. Chunk() method for big tables This is not necessarily related to Eloquent and is more related to the Collection. Nevertheless, Chunk () is powerful and particularly useful for the processing of bigger datasets. The bigger datasets can be chunked into pieces.
Instead of: $users = User::all(); foreach ($users as $user) { // ...
You can do: User::chunk(100, function ($users) {
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
foreach ($users as $user) { // ... } });
16. When creating a model, create additional things We are well acquainted with this Artisan command: php artisan make:model Company
Numerous Eloquent users are not aware of the three useful flags that generate the files related to the model. php artisan make:model Company -mcr
● -m will create a migration file ● -c will create a controller ● -r will indicate that the controller should be resourceful
17. Override updated_at when saving ->save() method can also accept parameters. Correspondingly, it can be used while ignoring update_at default functionality, which needs to be filled with the current timestamp. $product = Product::find($id); $product->updated_at = '2019-01-01 10:00:00'; $product->save(['timestamps' => false]);
Over here, we override the default update_at with the one that we have predefined.
18. What does update () result into? In your option, what does the following code return? $result = $products->whereNull('category_id')->update(['category_id' => 2]);
It is in the database that an update is performed. But what would that $result have?
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
The $result would contain affected rows. In case you need to check the numbers of rows that were affected, there is no requirement to call anything else. The update () returns this number for you.
19. Transform brackets into an Eloquent query Let us consider the case wherein one has a mix of and & or in his SQL query. ... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65)
Here is the wrong way to translate this into Eloquent $q->where('gender', 'Male'); $q->orWhere('age', '>=', 18); $q->where('gender', 'Female'); $q->orWhere('age', '>=', 65);
This is wrong because it is difficult to manage the order in this way. The right way, however, is more complicated and uses closure functions for 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 One can pass an array of parameters to orWhere(). Here is the Ususal way to accomplish the same. $q->where('a', 1); $q->orWhere('b', 2); $q->orWhere('c', 3);
But you can also do it like this. $q->where('a', 1); $q->orWhere(['b' => 2, 'c' => 3]);
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube
How Cyblance can help you with Laravel Eloquent coding When you intend to outsource Laravel Eloquent development or Laravel development, you will look out for a top Laravel development company. Cyblance is the best Laravel development company for your requirements. Our Laravel developers India have detailed know-how about using Laravel right, and have requisite relevant working experience as well. You can trust them to get the best custom outcomes from Laravel Eloquent development.
Conclusion: Eloquent makes a measurable difference to work processes and ROIs when done right. This reflects over project efficiency, turnaround times, time to market, and the sustainability and scalability of projects. They become hassle-free and free from bottlenecks. App management becomes easier. You can trust our proficient Laravel developers India with your Laravel Eloquent development requirements. Cyblance is the best Laravel development company, and you can hire Laravel developers India from us.
Follow Us On: Facebook Twitter LinkedIn Instagram Pinterest YouTube