How to Get Relationship with Count in Laravel 10

In the vast landscape of web development, Laravel stands out as a powerful PHP framework known for its elegant syntax and developer-friendly features. Laravel provides a convenient way to define and manage database relationships, making it easier for developers to work with data.

In this tutorial, we'll explore the process of establishing a relationship with a count in Laravel 10. Specifically, we'll create a scenario involving two models - Post and Comment.

A Post can have multiple comments, and we want to effortlessly retrieve the count of comments associated with each post.

So, let's see how to get relationship count in laravel 8/9/10.

Eloquent withCount(): Get Related Records

Here's a step-by-step guide on how to establish a relationship with a count in Laravel:

Step 1: Set up a new Laravel project

Create laravel 10 project using the following composer command.

composer create-project --prefer-dist laravel/laravel LaravelRelationshipExample
cd LaravelRelationshipExample

 

Step 2: Create Models

Create two models, for example, Post and Comment:

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

This will generate migration files for both models.

 

Step 3: Define the Database Schema

Edit the generated migration files to define the schema for the posts and comments tables. Add the following code to the respective migration files.

create_posts_table.php

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

create_comments_table.php

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('post_id');
        $table->text('content');
        $table->timestamps();

        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
    });
}

Run the migrations:

php artisan migrate

 

Step 4: Define the Eloquent Models

Define the relationship into the model like the below code example:


Post.php

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'content'];

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

Comment.php

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $fillable = ['post_id', 'content'];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

 

Step 5: Use the Relationship with Count

Now, you can use the relationship with count in your application. For example, to get the number of comments for each post, you can do:

$posts = Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo "Post: {$post->title}, Comments: {$post->comments_count} <br>";
}

 

Get Count Using hasManyThrough Relations:

Now, we'll give relationship count using hasManyThrough:

public function posts()
{
    return $this->hasMany(Post::class);
}

public function comments()
{
    return $this->hasManyThrough(Comment::class, Post::class);
}

Here's our UserController code:

public function index()
{
    $users = User::withCount(['posts', 'comments'])->get();
    return view('users', compact('users'));
}

You can get a count like the below example:

@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

// techsolutionstuff.com

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS