Laravel Eloquent Tips & Tricks
At this point, Every Laravel developer knows there are many documents available for Eloquent. But, we are not using many available functions. This blog will focus on common useful functions which we can use in every module creation.
Eloquent ORM provides a very powerful Active Record implementation working with your database. Every database table has its Model which is used to interact with the table.
There are lots of features available with Laravel Eloquent which is hard to know them all, This blog will show the features which are less known or useful on daily coding.
- Find Multiple Entries
- We already know the find method, right?
$user = User::find(1);
- But it is less known that find can accept multiple IDs as an array.
$users = User::find([1,2,3]);
- The push() Method
- Most of the time developers try to use the save method to store models and again the same method to store relationships. But the push() method can be used to store Model and relationship at a time.
$user = User::where(‘name’, ‘pratik’)->first(); $user->age = 31; $user->address->city = ‘Ahmedabad’; $user->push();
- So Save only saves the original model but push saves the relational model as well.
- Use of WhereX
$users = User::where(‘name’, ‘pratik’)->get();Into this
$users = User::whereName(‘pratik’)->get();
-
- Interesting right? Yes, you can change any field and append it as a suffix to where and it will work like a charm.
- when() method can say goodbye to if-else while making query
- Instead of using if else on query creation you can use Eloquent when() method like below.
$query = Post::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 does not seem shorter but it’s more powerful once we need to pass some parameters.
$query = User::query(); $query->when(request('role', false), function ($q, $role) { return $q->where('role_id', $role); }); $authors = $query->get();
- saveMany() method to use multiple records in one call.
- If you have hasmany relations with some child model you can save multiple records of the child model in one call like below.
$post = Post::find(1); $post->comments()->saveMany([ New Comment([‘message’ => ‘First Message’ ]), New Comment([‘message’ => ‘Second Message’ ]) ]);
- replicate() method is for copy of row
- If you want to make a copy of a row just use the replicate() method as below.
$post = Post::find(1); $newPost = $post->replicate(); $newPost->save();
- Chunk() method for large dataset
- This is not exactly an Eloquent related function but it is used after using Eloquent to get a collection. If you have too many records in collection you can chunk it to your desired amount like below.
$users = User::all(); User::chunk(100, function ($users) { foreach ($users as $user) { // ... } });
- orWhere() method can be used with multiple parameters
-
- We already know the use of the orWhere method but maybe some of us don’t know we can use the orWhere method with multiple parameters as an array.
$q->where('a', 1); $q->orWhere(['b' => 2, 'c' => 3]);
- Model boot() method
- This is the place of the model where you can change the default behaviour like below.
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); }); } }
- It is mainly used to set default values to some fields.
Conclusion
There are many good functions in Eloquent which are not that famous but it is very useful. I hope you will find above mentioned tips and tricks useful and can be implemented in daily routine working with Laravel & Eloquent. Please feel free to contact us and connect on social media if required any more details.