Eloquent Has Many Through Relationship

The “has-many-through” relationship provides a shortcut for accessing distant relations via an intermediate relation.

We are going to have a country table which will need a new Country role which we’ll migration at the same time:

php artisan make:model Country -m

Since we need a new foreign key (country_id) on the users table, we’ll create a new migration for this:

php artisan make:migration add_country_id_column_to_users --table=users

Open up the migration and add the first to up function and second to down function:

$table->integer('country_id');
$table->dropColumn('country_id');

Now open your country table migration to add a name column:

$table->string('name');

Now migrate this

php artisan migrate

Create a few countries. Attach your user to one of these new countries by editing and inputting the ID.

Now we need to define this Many Through relationship in the model. Open up Country model and add:

    public function posts(){
        return $this->hasManyThrough('App\Models\Post','App\Models\User');
    }
The first argument passed to the hasManyThrough function is the name of the final model we wish to access, while the second argument is the name of the intermediate model which has the foreign ID of this model (country_id).

Now let’s see this lookup in action. Add this to routes:

Route::get('/user/country', function(){
    $country = Country::find(4);
    foreach($country->posts as $post){
        echo $post->title;
    }
});
We find by country ID which then finds the user that owns the post to get the post title.

Leave a Reply

Your email address will not be published. Required fields are marked *