0
0
Laravelframework~30 mins

Has-many-through in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Has-Many-Through Relationship in Laravel
📖 Scenario: You are creating a simple Laravel app to manage countries, their users, and the posts those users write.Each Country has many Users, and each User has many Posts.You want to get all posts written by users from a specific country using Laravel's hasManyThrough relationship.
🎯 Goal: Build a Laravel model relationship using hasManyThrough so you can access all posts of a country through its users.
📋 What You'll Learn
Create a Country model with a hasManyThrough relationship to Post
Create User and Post models with correct foreign keys
Use exact method and variable names as instructed
Follow Laravel conventions for model relationships
💡 Why This Matters
🌍 Real World
This pattern is useful when you want to access related data through an intermediate model, like getting all posts from users of a country without querying users separately.
💼 Career
Understanding hasManyThrough relationships is important for Laravel developers to write clean, efficient code for complex data relations.
Progress0 / 4 steps
1
Create the initial models and database tables
Create three Laravel models: Country, User, and Post. Each model should have the following database columns:

- countries: id (primary key), name (string)
- users: id (primary key), country_id (foreign key), name (string)
- posts: id (primary key), user_id (foreign key), title (string)

Write the Eloquent model classes Country, User, and Post with the correct protected $fillable properties for name and title where applicable.
Laravel
Need a hint?

Remember to add protected $fillable arrays in each model for mass assignment.

2
Add the hasMany relationship from Country to User
In the Country model, add a public method called users that returns a hasMany relationship to the User model using the foreign key country_id.
Laravel
Need a hint?

Use hasMany with the foreign key 'country_id' in the users method.

3
Add the hasManyThrough relationship from Country to Post
In the Country model, add a public method called posts that returns a hasManyThrough relationship to the Post model through the User model. Use the foreign keys country_id on User and user_id on Post.
Laravel
Need a hint?

Use hasManyThrough with Post::class, User::class, and the foreign keys 'country_id' and 'user_id'.

4
Use the hasManyThrough relationship in a controller
In a Laravel controller method, write code to find the Country with id 1 and get all its posts using the posts relationship. Assign the posts collection to a variable called $countryPosts.
Laravel
Need a hint?

Use Country::find(1) to get the country, then access posts property.