Larvel – Eloquent way to connect three tables using two pivots

  join, laravel, php, pivot

New to laravel,

I have three tables users, roles, and permissions. Those are connected with the following two pivot tables role_user, and permission_role

Here I want to connect three tables so I can get a result like many-to-many and one-to-many relationship. For instance, I can get all permissions and roles for the given user (one-to-many) and vise-versa for roles and permissions to each other. Also, I want to get all users and respective roles and permissions and vise-versa for roles and permissions.

I have just solved the issue getting roles for the given user with the help of the community but now I stuck to get the above mention result. Can anyone help me to make it happen?

DB Diagram

enter image description here

User Model

<?php

namespace App;

use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];


    public function roles() {
        return $this->belongsToMany('AppAdminRole');
    }
}

Role Model

<?php

namespace AppAdmin;

use IlluminateDatabaseEloquentModel;

class Role extends Model
{
    protected $fillable = ['name', 'display'];

    public function permissions()
    {
        return $this->belongsToMany('AppAdminPermission');
    }

    public function admin_users()
    {
        return $this->belongsToMany('AppAdminAdmin');
    }

    public function users()
    {
        return $this->belongsToMany('AppUser');
    }

}

Permission Model

<?php

namespace AppAdmin;

use IlluminateDatabaseEloquentModel;

class Permission extends Model
{
    protected $fillable = ['model', 'can'];

    public function roles()
    {
        return $this->belongsToMany('AppAdminRole');
    }
}

Source: Laravel StackOverflow

Leave a Reply