All individual subscriptions are 50% off this week only!

MarkyzZz
1 year ago

Laravel Polymorphic relationship on same table (different user managers)

Posted 1 year ago by MarkyzZz

I have the users table, where each user can be assigned to a manager. I have 3 types of Managers (Country Manager, Area Manager and Fleet Manager). One Area manager can have many Fleet Manager and Country Manager, and one Country Manager can have many Fleet Manager. My users table have the columns fleet_manager_id, country_manager_id,area_manager_id that reference on id of users table. The question is that i don't know how to set a polymorphic relationship on same table. Migration:

Schema::table('users', function (Blueprint $table) {
    $table->integer('fleet_manager_id')->unsigned()->nullable();
    $table->foreign('fleet_manager_id')->references('id')->on('users');
    $table->integer('country_manager_id')->unsigned()->nullable();
    $table->foreign('country_manager_id')->references('id')->on('users');
    $table->integer('area_manager_id')->unsigned()->nullable();
    $table->foreign('area_manager_id')->references('id')->on('users');
});

My User Model:

public function fleetManagers()
{
    return $this->hasMany(User::class, 'fleet_manager_id');
}

public function countryManager()
{
    return $this->belongsTo(User::class, 'country_manager_id');
}

public function areaManager()
{
    return $this->belongsTo(User::class, 'area_manager_id');
}

Please sign in or create an account to participate in this conversation.