Skip to content
Advertisement

Laravel 5.5 How to get eloquent relationship count?

I have three tables as define below

User

  • id
  • name

Post

  • id
  • text
  • user_id

Comments

  • id
  • text
  • post_id

This is User model User.php

JavaScript

This is my post model Post.php

JavaScript

Issue:

I want to display no.of comments per user using eloquent eager loading.

Can anyone help me with that? Thanks in advance.

Advertisement

Answer

You may define a new hasManyThrough relationship (docs) for user’s comments:

JavaScript

Now you can count each user’s comments (Laravel docs):

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement