donglian4770 2019-08-05 11:11
浏览 79

Laravel - 路由:控制器嵌套控制器

My routes:

Route::apiResource('courses', 'CourseController');
Route::apiResource('courses.classrooms', 'ClassroomController');

List: php artisan route:list

api/v1/courses/{course}
api/v1/courses/{course}/classrooms/{classroom}

My question is: all my functions in classroom controller needs the course, something like that

public function index($course_id)
{
  $classroom = Classroom::where('course_id', $course_id)->get();
  return $classroom;
}

public function store($course_id, Request $request)
{
// ...
  $classroom->course_id = $course_id;
// ...
}

public function show($course_id, $id)
{
  $classroom = Classroom::where('course_id', $course_id)->find($id);
  return $classroom;
}
// ...

Have some Policy/Helper in Laravel to accomplish this automatically?

I believe it's not necessary to add the property $course_id in all functions manually, what can I do?

  • 写回答

2条回答 默认 最新

  • duan7664 2019-08-05 11:18
    关注

    You can use a group to enclose all your routes. Something like:

     Route::group(['prefix' => '{course}'], function () {
    
    // you can place your routes here
    
    });
    

    So all the routes that exist in that group will already have the course value in the url path and you don't have to "rewrite it" for every route.

    If that field is set by you for example an env variable then inside your RouteServiceProvider you can put the prefix you want in the mapApiRoutes function.

     protected function mapApiRoutes()
        {
            Route::prefix('/api/v1/courses/'.config('app.myVariable'))
                 ->middleware('api')
                 ->namespace($this->namespace)
                 ->group(base_path('routes/api.php'));
        }
    

    That way ALL your api endpoints will start with that prefix and you can have it in all the endpoints.

    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据