Support the ongoing development of Laravel.io →
Requests Input Views
Last updated 7 months ago.
0

Providing you have your relationship between posts and comments set up correctly, you can simply pass the posts.

If you are then looping through the posts using say,

foreach ($posts as $post)

then each post contains a post object and post->comments will contain a collection of comments for that post.

As collections have a count() method, you can round this off by adding

Comments ({{ $post->comments->count() }})

to your view.

Last updated 7 months ago.
0

petercoles said:

Providing you have your relationship between posts and comments set up correctly, you can simply pass the posts.

If you are then looping through the posts using say,

foreach ($posts as $post)

then each post contains a post object and post->comments will contain a collection of comments for that post.

As collections have a count() method, you can round this off by adding

Comments ({{ $post->comments->count() }})

to your view.

That is exactly what I'm looking for. But how do I make sure I have the correct setup?

Building the db from migrations I was unable to use foreign keys. It gave me an error I was unable to resolve.

Last updated 7 months ago.
0

Am I correct in assuming I need to fix my db setup to include foreign keys?

Last updated 7 months ago.
0

You would setup your Comments table to have a post_id column. That would be your key. Then you would setup the relationship:

// Posts model
$this->hasMany('Comment');

// Comments model
$this->belongsTo('Post');

It maybe your database doesn't support foreign keys as an index, but setting a column name with an id from the other table will be similar.

Last updated 7 months ago.
0

Where in the above do you point to the column post_id as being the fk we're interested in? How would it know?

Last updated 7 months ago.
0
protected $table = 'posts';
protected $primaryKey = 'id';
$this->hasMany('Comment');

The above gives me an error: syntax error, unexpected '$this' (T_VARIABLE), expecting function (T_FUNCTION)

Last updated 7 months ago.
0

It seems I just got the structure wrong. I found my answer here: http://laravel.com/docs/eloquent#one-to-many

Thank you for the help!

Last updated 7 months ago.
0

Sign in to participate in this thread!

LoadForge

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 Laravel.io - All rights reserved.