logo
Published on

Authors

Laravel API开发实践

1. 创建模型

$ php artisan make:model Lesson -m

--migration or -m 代表自动创建一个数据库迁移文件

2. 创建数据库迁移

Schema::create('lessonss', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->text('body');
    $table->boolean('free');
    $table->timestamps();
});

3. 执行数据库迁移

$ php artisan migrate

4.创建控制器

$ php artisan make:controller App\\Api\\Controllers\\LessonsController

5.添加路由

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
    $api->group(['namespace' =>
'App\Api\Controllers'], function ($api) {
        $api->get('lessons', 'LessonsController@index');
        $api->get('lessons/{id}', 'LessonsController@show');
    });
});

6.添加控制器方法

public function index()
{
    $lessons =  Lesson::all();

    return response()->json($data);
}

7.创建返回数据的模板

use App\Lesson;
use League\Fractal\TransformerAbstract;

class LessonTransformer extends TransformerAbstract
{
    public function transform(Lesson $lesson)
    {
        return [
            'title' =>
$lesson['title'],
            'content' =>
$lesson['body'],
            'is_free' =>
(boolean)$lesson['free']
        ];
    }
}

8.修改控制器方法,让返回数据使用模板

public function index()
{
    $lessons =  Lesson::all();

    return $this->collection($lessons,new LessonTransformer());
}

9.使用Dingo的helpers

use Dingo\Api\Routing\Helpers;

class Controller extends BaseController
{
    use Helpers,AuthorizesRequests, DispatchesJobs, ValidatesRequests;

}