AppDividend
Latest Code Tutorials

Laravel HasManyThrough Relationship Example

1,602

Get real time updates directly on you device, subscribe now.

In this tutorial, we will see Laravel HasManyThrough Relationship Example. The “has-many-through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. 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. At first, this relationship is complicated. So let us bring it down to small pieces.

Let us say; we have three models.

  1. Team (id, user_id, name)
  2. User (id, name)
  3. Goal (id, user_id, no.of goals)

So, the relationship is like this.

Team hasMany User (team_id inside User model)

User hasMany Goal (user_id inside Goal model)

See, from the relationship, we can see that here, the User model is an intermediary model.

We can not store the goal_id directly to the Team table because we already store the goal_id in the User table.

So, now User model is in a relationship with the Team model. So, inside User model there is team_id.

Finally, if we need to access how many goals the Team has created then, we can go through User model.

If that type of scenario is generated for your use case then and then you need to define this type of relationship.

Okay, now let us see the Practical Implementation of that Laravel HasManyThrough Relationship.

Laravel HasManyThrough Relationship Example

As always, start our project by installing fresh Laravel.

Step 1: Install Laravel 5.6.

laravel new relationships

Now, go into the project folder.

cd relationships

Open the project in your editor.

code .

Configure the database in the .env file.

Step 2: Create migrations.

Now, as we have discussed earlier, we need to define the team_id inside User table, so let us first add the team_id inside users migration.

// create_users_table

public function up()
{
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('team_id')->unsigned();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
}

Next, create another model with migration call Team.

php artisan make:model Team -m

Define the following schema inside create_teams_table.

// create_teams_table

public function up()
{
    Schema::create('teams', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

Finally, create another model called Goal with its migration.

php artisan make:model Goal -m

Also, write the following schema in the migration file.

Related Posts
1 of 39
// create_goals_table

   /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('goals', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('number_of_goals')->unsigned();
            $table->timestamps();
        });
    }

Now, finally, migrate the schema files using the following command.

php artisan migrate

Step 3: Create a User with team_id.

First, create an auth scaffold using the following command.

php artisan make:auth

Now, we need to Register a User, but the default Laravel register code does not save the team_id. So, we need to manually add the team_id.

Inside app >> Http  >> Auth  folder, you can see a RegisterController.php file. In that file, add one more column inside create() function.

// RegisterController.php

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
         'team_id' => 1
    ]);
}

Also, add the column inside a protected $fillable property in User.php file.

// User.php

protected $fillable = [
    'name', 'email', 'password','team_id'
];

Now, register one user by this URL: http://relationships.test/register

I have registered the four users with team_id. Although, we will create demo teams in next step.

Laravel HasManyThrough Relationship

 

Step 4: Create teams manually inside a database.

We have defined the team_id inside users table but did not have created yet, so let us do that first.

hasManyThrough relationship in Laravel

Step 5: Create goals manually inside a database.

Also, we need to assign the user_id inside goals table, while creating the goals.

hasmanythrough laravel example

 

Step 6: Define the relationships inside models.

Now, inside User.php file. we can define the following relationships.

  1. User hasMany Goals.
  2. User belongsTo Team.
// User.php

public function goals()
{
    return $this->hasMany(Goal::class);
}

public function team()
{
    return $this->belongsTo(Team::class);
}

Next step inside Goal.php file, we can define the following relationship.

  1. Goal belongsTo User
// Goal.php

public function user()
{
     return $this->belongsTo(User::class);
}

Finally, inside Team.php, we can define the following relationship.

  1. Team hasMany User
// Team.php

public function users()
{
     return $this->hasMany(User::class);
}

Step 7: Create a Controller file.

Okay, till now, we have created the migrations and models. We have also defined the relationship between the models. Now, we need to display the data based on defined relationships.

php artisan make:controller TeamController

Now, inside TeamController.php file, define the show() function.

We are using implicit model binding to show a particular team’s data.

// TeamController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;

class TeamController extends Controller
{
    public function show(Team $team)
    {
        dd($team);
    }
}

Define the route for show function inside a web.php file.

// web.php

Route::get('/team/{team}', 'TeamController@show')->name('team.show');

Now, go to this URL: http://relationships.test/team/1.

We have die to dump the object, so we get all the information about the team object that has an ID: 1.

So, we get the different teams based on the passing id.

Our primary goal is to check all the goals; the team has created.

However, the goal_id is not associated directly with the Team model.

The goal_id associated with the User model.

So, what we can do is that we can collect all the goals through the User model.

In that case, we can define the relationship like below inside Team.php model.

// Team.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
    public function users()
    {
        return $this->hasMany(User::class);
    }

    public function goals()
    {
        return $this->hasManyThrough(Goal::class, User::class);
    }
}

Now, you call the goals() function from the TeamController.php file.

// TeamController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;

class TeamController extends Controller
{
    public function show(Team $team)
    {
        $goals = $team->goals()->get();

        return view('team.show', compact('goals'));
    }
}

Create a folder called team inside views and inside that folder, create one blade file called show.blade.php.

Write the following code inside show.blade.php file.

<h3>The team has scored following goals</h3>

@foreach($goals as $goal)
    <p>{{ $goal->number_of_goals }}</p>
@endforeach

Go to this URL: http://relationships.test/team/1

Eloquent hasManyThrough Relationship

 

You can verify this by going to first teams table and pick the ID: 1.

Now, go to the User’s table and see, which users are belongsTo that team_id: 1.

Take those ids and verify the goals inside goals table because it goals table has user_id.

So, this is how you can build up a hasManyThrough relationship in Laravel.

Finally, Laravel HasManyThrough Relationship is over.

1 Comment
  1. Ashish gupta says

    Hi krunal, I wank to ask you, that , How to be concate where conditions of DB row queries with multiple if conditions in laravel 5.6.
    Please reply me as soon as possible.

    thanks..

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.