首页 > 解决方案 > Laravel 不同用户类型的相同控制器

问题描述

我有两种用户类型:教师和学生

对于学生来说,路线是:

GET /me/books

学生应该只用他们的书作为回应。

对于教师来说,路线是:

GET /books

教师应该有所有学生的书作为回应。

我有一个模型:Book和一个控制器:BookControllerBookController@index在这种情况下编写方法的最佳方法是什么?在 index 方法中为用户类型使用 switch case 听起来不是最佳实践。

标签: phplaravellaravel-controller

解决方案


您甚至可以保持路线不变。只需为教师和学生使用角色。

如果您不想实现角色,您可以在用户表上为类型(即教师或学生)设置一列。

然后,当请求到达控制器方法时,根据用户的类型,您可以编写查询以获取教师的所有书籍或仅获取分配给用户的书籍以防学生。

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
}

推荐阅读