Laravel API 资源:根据用户角色不同的回报

M a*_*a D 1 laravel laravel-5

这是我第一次在 Laravel 5.8 中使用 Api Resource 将数据返回到应用程序。有一个User模型包含有关用户的一些公共和私人信息。用户可以查看他/她的所有信息(如姓名、电话号码、电子邮件等),但其他人只能查看姓名和用户名。我该如何在 Api 资源中处理这个问题?

提前致谢。

Sal*_*301 5

您可以使用条件属性

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'username' => $this->username,
        'email' => $this->when(auth()->id() == $this->id, 'email'),
        'phone_number' => $this->when(auth()->id() == $this->id, 'phone'),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}
Run Code Online (Sandbox Code Playgroud)

仅当经过身份验证的用户尝试查看自己的信息时,才会返回电子邮件和电话号码