How to retrieve related records using Eloquent relationships in Laravel?

To retrieve related records using Eloquent relationships in Laravel, you can make use of the various types of relationships provided by Laravel, such as hasOne, hasMany, belongsTo, belongsToMany, etc. Here are the steps to retrieve related records using Eloquent relationships:

  1. Define the relationship in your models: In your model classes, define the relationships between the tables using the appropriate Eloquent relationship methods. For example, if you have a User model and a Post model, and each user can have multiple posts, you would define a hasMany relationship in the User model and a belongsTo relationship in the Post model.
// User.php public function posts() { return $this->hasMany(Post::class); } // Post.php public function user() { return $this->belongsTo(User::class); }
  1. Access related records using the relationship methods: Once you have defined the relationships, you can access related records using the relationship methods. For example, to retrieve all posts for a user, you can use the posts method on the User model:
$user = User::find(1); $posts = $user->posts;

This will retrieve all posts associated with the user.

  1. Lazy loading relationships: By default, relationships are lazily loaded. This means that relationships are not loaded until they are accessed. So when you access the posts property on the $user object, Laravel will automatically retrieve the related posts.

  2. Eager loading relationships: If you want to retrieve the related records upfront to avoid N+1 query problems, you can use eager loading. Eager loading allows you to retrieve all the related records in a single query. You can use the with method to specify the relationships to be eager loaded:

$users = User::with('posts')->get();

This will retrieve all the users along with their related posts in a single query, improving performance.

These are the basic steps to retrieve related records using Eloquent relationships in Laravel. You can explore more advanced features and customization options in the Laravel documentation for Eloquent relationships.