Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fatenfalfoul's avatar

Many to Many 3 tables

Hi, I'm using Laravel 5.1 (for server requirement) I have three tables: roles: id, name, libelle, permissions(array) application: id, name, description and of course users table

my pivot table contains : user_id, app_id and role_id

The problem is I can just retrieve roles for user or application for user but not user'roles for each application. Can you help me how can I treat that?? (When I tried to treat that using queries in model methods an error appears that mean not a Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation)

Thanks

0 likes
3 replies
fatenfalfoul's avatar

Tnaks for response, but I have three tables that each one belongsToMany for the 2 rest tables, and not only one :(

minjon's avatar

@fatenfalfoul If I get it right, you have established the many-to-many-relationships between every two of the three models (User, Application & Role). Instead, you should establish the many-to many between any two models of your choice and treat the third model as a pivot. For example:

User.php

class User extends Model
{
    public function applications()
    {
        return $this->belongsToMany(Application::class)->withPivot('role');
    }
}

Application.php

class Application extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot('role');
    }
}

myview.blade.php

@foreach($users as $user)

    @foreach($user->applications as $app)

        <p>{{ $app->name }}  {{ $app->pivot->role }}</p>

    @endforeach 

@endforeach 

Please or to participate in this conversation.