laravel5.1-第11.2章-开发API-列表+详情 laravel5.1-第11.2章-开发API-列表+详情

2023-07-04

一、注册路由

修改 routes/api.php

Route::group(['prefix'=>'api/v1'],function(){
   Route::resource('lessons', 'LessonsController');
});

查看路由列表

php artisan route:list

https://file.lulublog.cn/images/3/2023/07/xZ8O84a78Zo11N8O1C3s4hAON4dzZH.jpg

二、课程列表

修改 app/Lesson.php

protected $hidden = ['created_at', 'updated_at'];

创建 Lesson resource

php artisan make:resource Lesson

修改创建的文件:app/Http/Resources/Lesson.php

public function toArray($request)
{
   return [
       'id' => $this->id,
       'title' => $this->title,
       'content' => $this->content,
       'isFree' => (boolean)$this->free,
   ];
}

修改控制器:app/Http/Controllers/LessonsController.php

public function index()
{
   $lessons = Lesson::all();
   $data = [
       'list' => $lessons,
   ];
   return response()->json($data)->setStatusCode(200);
}

启动服务

php artisan serve

访问:http://localhost:8000/api/v1/lessons

三、课程详情

修改控制器:app/Http/Controllers/LessonsController.php

public function show($id)
{
   return Lesson::find($id);
}

访问:http://127.0.0.1:8000/api/v1/lessons/

阅读 359