Post and Comment models. Each post can have many comments. What will be the output of $post->comments->count() if the post has 3 comments?<?php
$post = Post::find(1);
echo $post->comments->count();In Laravel, a one-to-many relationship means one post can have many comments. The comments property returns a collection of related comments. Counting them returns the number of comments.
Comment model that belongs to a Post, what will echo $comment->post->title; output if the comment belongs to a post titled 'Hello World'?<?php
$comment = Comment::find(5);
echo $comment->post->title;The belongsTo relationship returns the parent model instance. Accessing post->title gives the title of the related post.
User and Role models in Laravel?Many-to-many relationships in Laravel use belongsToMany to connect models through a pivot table.
$posts = Post::all();
foreach ($posts as $post) {
echo $post->comments->count();
}Without eager loading, Laravel runs one query for posts and one query per post for comments, causing many queries (N+1 problem). Eager loading loads all related comments in one query.
Laravel relationships let you define how different data models connect, just like real-world objects relate to each other, making data easier to manage and understand.