我的数据库名称中有一个json字段是权限 {"read": true, "create": true}
。现在,我想在我的刀片视图中显示此信息。我试过这种方式,但它显示错误。
@foreach($users as $user)
<tr>
<td>{{$user->roles->permissions}}</td>
</tr>
@endforeach
显示此错误消息。
Property [permissions] does not exist on this collection instance.
用户模型
public function roles()
{
return $this->belongsToMany(Role::class,'user_roles');
}
答案 0 :(得分:0)
我测试了这个场景并且没问题。我希望对你有用:
我的route
:
Route::get('/test', function (Request $request) {
$users=\App\User::with('roles')->get();
return view('welcome',compact('users'));
});
在roles
模型中定义user
方法:
public function roles()
{
return $this->belongsToMany(Role::class,'user_roles');;
}
并在permissions
中获取view
:
@foreach($users as $user)
@foreach($user->roles as $role)
<tr>
<td>{{$role}}</td>
</tr>
@endforea
@endforeach
我用这些表进行测试
user_roles
user_id | role_id
-----------------
1 | 2
1 | 2
roles
:
id | permissions
-----------------
1 | {"read": true, "create": true}
2 | {"read": true, "create": false}
users
:
id | name | email | password | remember_token | created_at|updated_at
----------------------------------------------------------------------
1 | alihossein|ali@gmail.com|XXXXX|UIWKK67ei5CCuiv1OXilKY2aRkTfSqGLpqJch0F9YmenGSorsQGHVvWiX6kP| 2018-05-28 22:25:14 | 2018-05-28 22:25:14