2016-09-21 82 views
3

我试图修改laravel中JWT的身份验证方法的json输出,使其显示角色为数组。JWT Laravel - 修改json输出的内容

所以在这里我

created_at : “2016年8月18日十二时33分14秒” 电子邮件 : “[email protected]” ID : last_logged_in : “2016年9月21日16时37分35秒” 名 : “Dhenn” 角色 : “{0:一DMIN, 1:用户“} 的updated_at : ”2016年9月21日16时37分35秒“

但我不能。我试图修改我的jwt.auth php文件,但它返回了一个错误,我设置了一个非属性对象。

这里是智威汤逊 - auth.php的当前设置

public function authenticate($token = false) 
{ 
    $id = $this->getPayload($token)->get('sub'); 

    if (! $this->auth->byId($id)) { 
     return false; 
    } 

    $user = $this->auth->user(); 
    return $user; 
} 

虽然,我有错误尝试此:

public function authenticate($token = false) 
{ 
    $id = $this->getPayload($token)->get('sub'); 

    if (! $this->auth->byId($id)) { 
     return false; 
    } 



    $user = $this->auth->user(); 

    foreach ($user as $roles) { 
      $roles->roles = explode(",", $roles->roles); 
     } 
    return $user; 
} 

回答

1

你说这是你的用户对象:

{ email : "[email protected]" 
    id : 1 
    last_logged_in : "2016-09-21 16:37:35" 
    name : "Dhenn" 
    roles : "{0: admin, 1: user"} 
    updated_at : "2016-09-21 16:37:35" } 

假设$this->auth->user();回报这一点,你的迭代foreach ($user as $roles) {是不正确的,因为$user应该是一个对象不是一个数组。通过这种方法,您可以尝试通过此对象的每个属性,但是我想你想要迭代角色数组。 这应该是这样的:

foreach($user->roles as $role) ... // assuming roles is an array 

roles似乎是一个编码JSON字符串,所以你需要太解码。

foreach(json_decode($user->roles) as $role) ... 

或者直接:$user->roles = json_decode($user->roles)

0

好的,谢谢你的帮助。我想出了答案。

这是我的代码终于工作。

public function authenticate($token = false) 
{ 
    $id = $this->getPayload($token)->get('sub'); 

    if (! $this->auth->byId($id)) { 
     return false; 
    } 
    $user = $this->auth->user(); 
    $user->roles = explode(",", $user->roles); 
    return $user; 
} 
+0

现在我明白了,你想要的东西 - 的JSON编码的角色角色的列表(见上面我更新的答案)。顺带回来,展示你自己的解决方案! – everyman