首页 > 解决方案 > Laravel API 资源:基于用户角色的不同返回

问题描述

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

提前致谢。

标签: laravellaravel-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,
    ];
}

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


推荐阅读