0
votes

I have 4 tables:

user(id,role_id)

role(id)

permission_role(role_id,permission_id)

permission(id, name)

User model

 <?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;

    /**
     * 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',
    ];
    public function roles()
{
     return $this->hasOne('App\Role', 'id', 'role_id');
}
}

Role model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{
    public function users()
{
    return $this->belongsTo('App\User','role_id','id');
}
public function permissions()
    {
        return $this->belongsToMany('App\Permission','permission_role');
    }
}

Permission model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
   public function roles()
    {
       return $this->belongsToMany('App\Role','permission_role');
    }
}

and i want to test in my controller to see if user have permission delete_article via if condition, any help? and thanks

1

1 Answers

0
votes

In you Role model Something like this you need to do (Many to Many)

//.......................
public function permissions()
{
    return $this->belongsToMany('App\Permission','permission_role''role_id', 'permission_id');
}
//......................

See Many to Many relationship: Link

And to get the data into your controller

//..........................................
$user = get data with role and permission
$roles= $user->roles;
foreach($roles as $role){
   foreach($role->permissions as $permission){
      $permissiona_name = $permission->name;
   }
}
//...........................

first check with var_dump($user)

Many to many with pivot (see Retrieving Intermediate Table Columns section)

return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');

See also "Has Many Through"