What Is Counting Related Models In Laravel Framework

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Defining relationships as functions provides powerful method chaining and querying capabilities.Today we are going to discuss how to Count Related Models In Laravel is to get the amount of related records inside of the main object with help of withCount() function. It also works with two layers, inside of hasManyThrough relations.

What Is Counting Related Models In Laravel Framework

Counting Related Models

The "has-many-through" relationship provides a convenient shortcut for accessing distant relations via an intermediate relation.

To learn about "has-many-through" relationship in laravel visit our  Bajarangisoft site.

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models. For example:


Create three models and migration files: UserPost and Comment. using below commands

php artisan make:model User -m
php artisan make:model Post  -m
php artisan make:model Comment -m


Open User.php add below

public function posts()
{
    return $this->hasMany('App\Post');
}

public function comments()
{
    return $this->hasManyThrough('App\Comments', 'App\Post');
}


Create route and controller to access data.
Route in Web.php
Route::get('Index','DemoController@index');


Create DemoController.php using below command in command prompt
php artisan make:controller DemoController


To access data from controller implement below code in DemoController

<?php

namespace App\Http\Controllers;
use App\Post;
use App\Http\Requests;
use App\Http\Controllers\AppBaseController;

class DemoController extends AppBaseController
{
    public function index()
    {
        $posts = App\Post::withCount('comments')->get();
        foreach ($posts as $post)
        {
            echo $post->comments_count;
        }
    }


You may add the "counts" for multiple relations as well as add constraints to the queries:

use Illuminate\Database\Eloquent\Builder;

$posts = App\Post::withCount(['votes', 'comments' => function (Builder $query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
 

You may also alias the relationship count result, allowing multiple counts on the same relationship:

use Illuminate\Database\Eloquent\Builder;

$posts = App\Post::withCount([
    'comments',
    'comments as pending_comments_count' => function (Builder $query) {
        $query->where('approved', false);
    },
])->get();

echo $posts[0]->comments_count;

echo $posts[0]->pending_comments_count;


If you're combining withCount with a select statement, ensure that you call withCount after the select method:

$posts = App\Post::select(['title', 'body'])->withCount('comments')->get();

echo $posts[0]->title;
echo $posts[0]->body;
echo $posts[0]->comments_count;
 

In addition, using the loadCount method, you may load a relationship count after the parent model has already been retrieved:

$book = App\Book::first();

$book->loadCount('genres');


If you need to set additional query constraints on the eager loading query, you may pass an array keyed by the relationships you wish to load. The array values should be Closure instances which receive the query builder instance:

$book->loadCount(['reviews' => function ($query) {
$query->where('rating', 5);
}])

Related Post