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:
Create laravel 10 project using the following composer command.
composer create-project --prefer-dist laravel/laravel LaravelRelationshipExample
cd LaravelRelationshipExample
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.
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
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);
}
}
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>";
}
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: