php - Laravel 不同用户类型的相同控制器
问题描述
我有两种用户类型:教师和学生
对于学生来说,路线是:
GET /me/books
学生应该只用他们的书作为回应。
对于教师来说,路线是:
GET /books
教师应该有所有学生的书作为回应。
我有一个模型:Book
和一个控制器:BookController
。BookController@index
在这种情况下编写方法的最佳方法是什么?在 index 方法中为用户类型使用 switch case 听起来不是最佳实践。
解决方案
您甚至可以保持路线不变。只需为教师和学生使用角色。
如果您不想实现角色,您可以在用户表上为类型(即教师或学生)设置一列。
然后,当请求到达控制器方法时,根据用户的类型,您可以编写查询以获取教师的所有书籍或仅获取分配给用户的书籍以防学生。
public function index()
{
$user = auth()->user();
$query = Book::query();
if($user->type === 'student') {
$query->where(/*some condition to constrain the records*/);
//Or if you have a relation to fetch books for the user
$query = User::query()->with('books');
}
$books = $query->get();
//return json response for ajax request or a view
}
推荐阅读
- reactjs - 无法从 redux reducer 中拉出状态:“无法读取未定义的属性 'tracks'”
- css - IE 只应用一些外部 css 样式表
- javascript - 在模态而不是新窗口中打开目标空白
- java - How to deny the Multi-Window feature?
- html - :last-of-type Or :nth-of-type(n) Where n Is Last Element
- python - 使用 sudo pip install 从运行 python 3.6 的 ubuntu 18.04 安装后如何删除“pafy”?
- veins - Veins+SUMO 变道行为
- sql - 为什么不是所有日期都在“group by”SQL 查询中得到输出?
- javascript - Auth.currentSession 说没有当前用户
- javascript - plotly.js:当悬停模式为 x/y 且不是“最近”时,如何获取被点击的最近点