问题描述
我如何基于请求用于授权的访问令牌中的范围返回laravel模型,类似于如何与身份和电子邮件范围here不一致。我想基本上基于令牌范围在模型中“动态”隐藏/显示特定属性
这会在控制器或模型中定义吗?
解决方法
决定使用Laravel API Resources和conditional attributes
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,'username' => $this->username,'email' => $this->when($request->user()->tokenCan('email'),$this->email),];
}
}