Complete the code to define a one-to-many relationship method in a Laravel model.
public function posts() {
return $this->[1](Post::class);
}The hasMany method defines a one-to-many relationship in Laravel models.
Complete the code to retrieve all posts for a user using the relationship.
$user = User::find(1); $posts = $user->[1];
The relationship method is named posts, so accessing it as a property returns all related posts.
Fix the error in the relationship method by completing the code correctly.
public function comments() {
return $this->[1](Comment::class);
}The hasMany method is used to define a one-to-many relationship from the current model to the Comment model.
Fill both blanks to define a one-to-many relationship with a custom foreign key.
public function orders() {
return $this->[1](Order::class, '[2]');
}The hasMany method defines the relationship, and the foreign key is usually the current model's name with _id, here user_id.
Fill all three blanks to create a one-to-many relationship with a custom foreign key and local key.
public function reviews() {
return $this->[1](Review::class, '[2]', '[3]');
}The hasMany method is used with the foreign key user_id and the local key id to define the relationship.