Laravel: posts and their comments
Define a one-to-many relationship and load it without N+1 queries.
advancedPHP / Laravel· PHP & Laravel
The task
A post has many comments, and each comment belongs to one post.
- In
Post, add acomments()relationship (hasMany). - In
Comment, add apost()relationship (belongsTo). - In
PostController@index, load the 10 newest posts with their comments and the number of comments, using as few queries as possible (no N+1).
What you'll build
The finished result. Try it out, then build it yourself below.
Demo · drag the bottom edge to make it taller