This post is from the professional Laravel developer community, original link: learnku.com/laravel/t/2…
Eloquent There’s a little-known function called withCount() that helps you get the number of records associated with an object, including a remote one-to-many relationship. Let’s look at an example.
In our sample small project, we have three models: User, Post, and Comment. All associations can be described using these three models, starting with the app/ user.php model:
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasManyThrough(Comment::class, Post::class);
}
Copy the code
Now let’s try to display the following table on the page – a statistical list of users and their posts and comments:
The implementation is very simple, here is the code for the controller UserController:
public function index()
{
$users = User::withCount(['posts'.'comments'])->get();
return view('users', compact('users'));
}
Copy the code
Passed to thewithCount()For each parameter to the method, a parameter name is eventually created in the model instance_countAttributes of suffixes. So, in the example above, access is availableuser->comments_countProperty to get statistics.
Then, in our view file, we have:
<table class="table">
<thead>
<tr>
<th>User</th>
<th class="text-center">Posts</th>
<th class="text-center">Comments</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td class="text-center"> {{$user->posts_count }}</td>
<td class="text-center"> {{$user->comments_count }}</td>
</tr>
@endforeach
</tbody>
</table>
Copy the code
Note that withCount() can handle both hasMany() relationships and hasManyThrough(). The second order depth of.
Not only that, we can even specify filtering conditions for the relational model when using withCount(). Suppose we have a comment table with a approved status field. The following example shows how to filter this field and even specify an alias:
$users = User::withCount([
'posts'.'comments'.'comments as approved_comments_count'= >function ($query) {
$query->where('approved', 1);
}])
->get();
Copy the code
This allows you to display the statistics in an attempt using $user->approved_comments_count.
For more information about the withCount() method – see the official Laravel documentation.