如何在laravel中显示Json字段值

时间:2018-06-02 18:18:35

标签: json laravel laravel-blade

我的数据库名称中有一个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');
}

1 个答案:

答案 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