简体   繁体   中英

Laravel / Sentinel - How to get value through pivot table

I use Sentinel Framework to made authorization and authentication. But I stuck in User Management.

I want to show details like Email - Role but I still stuck here.

My Database:

role: ID, slug, name
user: ID, Email, ...
role_users: user_id, role_id

My Controller

  public function getAll(){
    $user = User::all();
    return view('admin.user.list',['user'=>$user]);
}

My UserModel

public function Role(){
    return $this->belongsToMany('App\Role','role_users','user_id', 'role_id');
}

Then my view

<?php foreach ($user as $u): ?>
<tr>
 <td>{{$u->Role->name}}</td>
</tr>
<?php endforeach; ?>

Then I got an error

Property [slug] does not exist on this collection instance. 

If I write

<td>{{$u->Role}}</td>

It's appears an array like

[{"id":1,"slug":"admin","name":"admin","permissions":null,"created_at":null,"updated_at":null,"pivot":{"user_id":1,"role_id":1}}]

But I can't access to the "slug" property :(

How can I do that ?

Thanks a lot !!!

user model

class User extends Model
    {
        /**
         * The roles that belong to the user.
         */
        public function roles()
        {
            return $this->belongsToMany('App\Role');
        }
    }

Role model

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

controller

 public function getAll(){
    $user = User::all();
    return view('admin.user.list',['user'=>$user]);
}

view

@foreach ($user as $u)
    // becuase many to many you need this
   @foreach ($u->roles as $role) 
         {{$role->name}}
   @endforeach
@endforeach

check Laravel Many To Many Document for more info: Laravel Many To Many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM