Laravel 11 简化了很多内容,把一些很少需要改动的内容默认隐藏起来,使整个project文件数量减少了很多,如果做纯API的话,再把前端相关的内容删除后就更简洁了。
初始化
先安装laravel installer (Installation - Laravel 11.x - The PHP Framework For Web Artisans)

创建一个project

不使用初始包,测试用Pest简化代码,初始化 git,数据库用 sqlite 方便本地开发

创建 token 模式的验证方式
安装Sanctum来管理 token (Laravel Sanctum - Laravel 11.x - The PHP Framework For Web Artisans)

运行 migrate 后User表就会加上 token字段,然后在 User model里加上HasApiTokens

创建一个 AuthController 来负责管理token

创建login, logout的方法

在 api.php 里加上路由

创建UserController 返回用户信息

创建测试
用Pest来测试,创建AuthTest.php
引入 DatabaseTransactions 就是为了保持数据库干净,测试后会自动Rollback。 token 获得后要使用 header Authorization 来进行认证。在测试过程中可以用Log::debug来打印日志,方便调试。