5 Best Laravel 6/7/8 Eloquent Methods
Today we are going to discuss the best laravel eloquent methods.
When we work with eloquent models laravel provides us with a lot of inbuilt methods that make our life easier. Some of them are explained below.
Eloquent method toQuery()
Let’s assume that we have a model collection of messages. Now we want to update the same status to all the models like read_at timestamp. But how we can do that, we have to iterate over each model and update the status.
To solve this issue we have a very interesting eloquent method which is called toQuery(). So, now we can call this method with the collection and then perform the update status action.
use App\Models\Messages; $messages = Messages::where('receiver', auth()->user()->id)->orWhere(‘sender’, auth()->user()->id)->get(); Or $messages = auth()->user()->messages(); //if have relationship for messages $messages->toQuery()->update([ ‘read_at’ => now(), ]);
Eloquent method modelKeys()
Sometimes we want only primary keys of the models like we have a list of posts and we want to get the primary keys of all the posts written by a particular author. We have another interesting eloquent method that is modelKeys. We can use this method with any collection of models and get the collection of primary keys of all the models.
$user->posts->modelKeys(); Or $posts = Post::where(‘author_id’, $user->id)->get(); $posts->modelKeys();
Eloquent method fresh()
Let’s assume we get the collection of models but after sometime we want to refresh this collection from the database. But we don’t want to write the whole thing again, so we can use the fresh eloquent method to refresh the collection from the database. Even we can refresh a single relationship also.
// refresh the inventory before adding the new item to the cart. $inventory->fresh(); $product->addToCart();
Eloquent method only()
If we want some particular models having given primary keys then we can use this eloquent method.
$products->only([3423, 5463, 6784]);
It will return all the products having these primary keys.
Eloquent method except()
It is similar to the eloquent method except() but returns the opposite result. Like it will return the models not having the given primary keys.
$products->except([3423, 5463, 6784]);
It will return all the products not having these primary keys.
These are few best laravel eloquent methods. But yes, there are more like these so, we will discuss them in the next article.
Hope it will help you, Happy LaraCode.