laravel - Laravel API 资源:基于用户角色的不同返回
问题描述
这是我第一次在 Laravel 5.8 中使用 Api Resource 将数据返回给应用程序。有一个User
模型包含有关用户的一些公共和私人信息。用户可以查看他/她的所有信息(与姓名、电话号码、电子邮件等相同),但其他人只能查看姓名和用户名。我如何在 Api Resource 中处理这个问题?
提前致谢。
解决方案
您可以使用条件属性
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,
];
}
这只会在经过身份验证的用户尝试查看自己的信息时返回电子邮件和电话号码
推荐阅读
- java - Main 不会调用数组
- r - 在 ggplot2 中创建(按包)绘图后,更改图例中的跟踪名称
- mongodb - MongoExport SASL 身份验证步骤:身份验证失败
- algorithm - 将给定问题优化为线性时间,而不用担心空间
- javascript - React 中的“无法读取未定义的属性‘映射’”,这里有什么问题?
- java - 使用 Apache POI 更改 Excel 折线图中的数据范围
- javascript - 将日期格式转换为另一种日期格式
- ios - 将 DJI SDK 集成到 Osmo Mobile 2 的自定义视频应用程序中
- java - Java 命名类:何时使用支持?但也考虑到 Helper 和 Utils
- r - 与 nls() 的非线性拟合在初始参数估计时给了我奇异梯度矩阵。为什么?