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.
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(), ]);
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();
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();
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.
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.
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…