Updated April 10, 2023
Definition of Laravel withcount
The Laravel has a unique function called withCount() which is used to fetch the number of associated records present in the main object. It is also implied on both single and multiple layers and works together with many relationships inside. When the user needs to count the rows on the relation model, he can just run withCount(). The model of laravel withcount is built with many through relation layers. In this article, using laravel withcount, implementation, configuration, and some standard examples of Laravel count are discussed in brief.
Overview of laravel withcount
In simple, the Laravel withCount() is used to count the rows present in the relational model and fetch the amount of associated or related records present in the main object. It can be implemented with many relationships like one-to-one, one to many, many to many, polymorphic relationship, querying relationship, dynamic relationship, and so on.
Why use laravel withcount?
There is multiple process present within each relationship and each serves a unique purpose. For example, in the below code, there are three models, comments, posts, and users. All the relationships used here should be pre-defined in the app/ user.php model file.
Simple count example is defined in the below code:
$category = Categories :: withCount ('document') -> get();
//count of documents present in categories.
Multiple count example is defined in the below code,
$category = Categories :: withCount ('document', 'files') -> get();
//count of documents and files present in categories.
A conditional example of withCount() is given below,
$category = Categories :: withCount ('document' = function ($query) )
{
$query -> where ('status', 1);
}]} -> get ();
//displays the count of documents present in categories.
public function comment ()
{
return $this -> has Many (comment::user);
}
public function post()
{
return $this -> hasManyThrough (post ::user, comment::user);
To display the list of users, posts, and feeds there is a method to imply user controller code which is defined.
public function value ()
{
$user = User :: withCount (['posts', 'feeds']) -> get ();
return view('user', compact('user'));
}
How to use laravel withCount()?
The values defined in the specified withCount() methods turn into the main object count. So here the user has to define $user -> total count of the post and $user -> total count of the feeds. All are defined as variables. The counting related models can enable the user to count the related model for the provided relationship without feeding the models. To achieve this, the user can choose the withCount() technique. The withCount() technique provides the {relation_count} and the attributes on the resultant models.
Use app\ feeds\ post;
$ post = Post:: withCount ('comments') -> get();
For each ($post $feeds $post)
{
echo $post->comments_count;
}
When it is passed in array to withCount() method, the user can add the count in the multiple relations and also add the extra constraints to the developed queries.
use Illuminate\ Database\ Eloquent\ Build;
$post = Post :: withCount (['post', 'feeds'=> function (build $query)
{
$query -> where ('content', 'feed', 'code%');
}]) -> get();
Echo $posts[0] -> Post_count;
echo $posts[0] – > feeds_count;
the user can alias the result count of the relationship which enables the user to work on multiple counts present in the same relationship.
$post = Post:: withCount ([
‘feeds',
feeds are ttotal pending counts in the pos' => function (Build $query)
{
$query- > where('approved', true);
},
]) -> get();
echo $posts[0] -> Post_count;
echo $posts[0] -> total pending counts in the post;
in the deferred loading on the count, the user loads a count of relationships after retrieving the parent model.
$comic = comic :: first();
$comic -> loadCount ('genres');
If the user has to fix an additional query on the total query count, he can then pass the array key by the relationship that the user needs to count accordingly. The value of the array should be closed to receive the instance by builder option.
$comic -> loadCount (['pages' => function ($query)
{
$query->where ('price', 500);
}])
Laravel withcount Examples
The customized select statements and relationship counting can be combined with withCount() statement and implied after the select method.
$comic = Post:: select(['title', 'body'])
-> withCount ('feeds')
-> get ();
In addition withCount() method, the laravel also offers withmax, withmin, withsum, withavg, and withexist methods. It replaces a relation _ function _ row attributes on the resultant models
$comics = comic :: withSum('pages', 'price') -> get();
foreach ($feeds as $post)
{
echo $comic ->price _ sum _ pages;
}
The user can also give the aggregate function result with another name and it should be mentioned in the general alias.
$comics = comics:: withSum ('price _ sum _ pages'as 'price', 'pages') -> get();
foreach ($($feeds as $post);
{
echo $comic ->price _ sum _ pages;
}
Similar to the load count method, the deferred version is possible and the extra operation is executed in the models which can be retrieved already.
$comic = comic :: first();
$comic -> loadSum ('pages', 'price');
If the user uses both select and aggregate statements in withCount(), he should check that he can call all the aggregated methods only after the select method.
$comic = Post:: select(['title', 'body'])
-> withexceeds ('feeds')
-> get ();
The counting-related models are also possible by using relationship and withCount() in laravel. If the user has to load a morph in the relationship he can relate the model count for different entities which is returned by relationships. It can be availed using the withCount() method in the combination of a morph to a relationship with morphwithcount methods.
Conclusion
In the above-given examples, the comics and posts are much related to creating the feed models. So the activity feed has the morph to relation called parent which enables to fetch the post count or feed count for the instances on the activity feed. The post has many tags and feeds or comments, but all data can be retrieved individually.
Recommended Articles
We hope that this EDUCBA information on “Laravel withcount” was beneficial to you. You can view EDUCBA’s recommended articles for more information.