For getting every new tutorial link Please join our telegram group

Part 12 how to count a model relationship records by withCount() method in laravel

How to count relationship data with main model in laravel by using withCount() eloquent method with hindi video.

Also ask: withCount() method in laravel, how to count laravel relationship data.

Laravel eloquent withCount() method

When you want to count a model related records in laravel then use withCount() method. We pass one or more relationship names in this method which data count.

Let understand by example there are three models Post, View and Comment now we get all posts data with count number of views and comments.

Post Model

In Post model define two relations views and comments.

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    
    public function comments() {
        return $this->hasMany(Comment::class);
    }

    public function views() {
        return $this->hasMany(View::class);
    }
}
PostController

Now we get all posts data with their related views and comments count. withCount() method add extra column in array which name define as add a '_count' after relationship name like 'views_count

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller{
    public function index(){
       $Posts = Post::withCount(['comments', 'views'])->get();

       foreach($posts as $post){
      		echo "Post Name".$post->name;
      		echo "Total Views".$post->views_count;
      		echo "Total Comments".$post->comments_count;
     	}

     	dd($Posts);
    }
}

Here we explain laravel eloquent concepts with advanced web tutorial. Also provide laravel tutorial with hindi videos.

php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Related tutorial links