Laravel 11 – 使用 Sanctum 构建 API

2024年 7月 2日 85.5k 0

Laravel 11 - 使用 Sanctum 构建 API-1

导读:有读者互动,提出经常使用的API开发处理。本文向各位说明Laravel 11的API处理。

步骤 1:安装 Laravel 11

打开终端并安装新的 Laravel 应用程序

composer create-project laravel/laravel sanctum-api

切换到项目文件夹

cd sanctum-api

第 2 步:安装 Sanctum API

运行以下命令使用 API 安装 Sanctum

php artisan install:api

步骤 3:Sanctum 配置

在 app/Models/User.php 中,我们添加了 Sanctum 的 HasApiTokens 类

namespace App\Models;// use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;use Laravel\Sanctum\HasApiTokens;class User extends Authenticatable{    use HasFactory, Notifiable, HasApiTokens;    /**     * The attributes that are mass assignable.     *     * @var array,>     */    protected $fillable = [        'name',        'email',        'password',    ];    /**     * The attributes that should be hidden for serialization.     *     * @var array,>     */    protected $hidden = [        'password',        'remember_token',    ];    /**     * Get the attributes that should be cast.     *     * @return array,>     */    protected function casts(): array{        return [            'email_verified_at' => 'datetime',            'password' => 'hashed',        ];    }}

步骤 4:添加博客迁移和模型

运行以下命令添加博客迁移和模型

php artisan make:model Blog -m

之后,转到数据库/迁移,您将找到创建的迁移文件

use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;return new class extends Migration{    /**     * Run the migrations.     */    public function up(): void{        Schema::create('blogs', function (Blueprint $table) {            $table->id();            $table->string('title');            $table->longText('detail');            $table->timestamps();        });    }    /**     * Reverse the migrations.     */    public function down(): void{        Schema::dropIfExists('blogs');    }};

然后转到 app/Models/Blog.php

namespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;class Blog extends Model{    use HasFactory;    protected $fillable = [        'title', 'detail'    ];}

步骤 5:创建 Eloquent API 资源

运行以下命令创建博客 API 资源

php artisan make:resource BlogResource

然后转到 app/Http/Resources/BlogResource.php

namespace App\Http\Resources;use Illuminate\Http\Request;use Illuminate\Http\Resources\Json\JsonResource;class BlogResource extends JsonResource{    // Transform the resource into an array.    public function toArray(Request $request): array{        return [            'id' => $this->id,            'title' => $this->title,            'detail' => $this->detail,            'created_at' => $this->created_at->format('d/m/Y'),            'updated_at' => $this->updated_at->format('d/m/Y'),        ];    }}

步骤 6:创建控制器文件

运行以下命令添加 BaseController & RegisterController & BlogController

php artisan make:controller API/BaseControllerphp artisan make:controller API/RegisterControllerphp artisan make:controller API/BlogController

然后转到 app/Http/Controllers/API/BaseController.php 并添加此代码

namespace App\Http\Controllers\API;use App\Http\Controllers\Controller;use Illuminate\Http\Request;class BaseController extends Controller{    // success response method    public function sendResponse($result, $message){        $response = [            'success' => true,            'data'    => $result,            'message' => $message,        ];        return response()->json($response, 200);    }    // return error response    public function sendError($error, $errorMessages = [], $code = 404){        $response = [            'success' => false,            'message' => $error,        ];        if(!empty($errorMessages)){            $response['data'] = $errorMessages;        }        return response()->json($response, $code);    }}

现在转到 app/Http/Controllers/API/BaseController.php

namespace App\Http\Controllers\API;use App\Http\Controllers\Controller;use Illuminate\Http\Request;use App\Models\User;use Illuminate\Support\Facades\Auth;use Illuminate\Http\JsonResponse;use Illuminate\Support\Facades\Validator;class RegisterController extends BaseController{    // Register api    public function register(Request $request): JsonResponse{        $validator = Validator::make($request->all(), [            'name' => 'required',            'email' => 'required|email',            'password' => 'required',            'c_password' => 'required|same:password',        ]);        if($validator->fails()){            return $this->sendError('Validation Error.', $validator->errors());        }        $input = $request->all();        $input['password'] = bcrypt($input['password']);        $user = User::create($input);        $success['token'] =  $user->createToken('MyApp')->plainTextToken;        $success['name'] =  $user->name;        return $this->sendResponse($success, 'User register successfully.');    }    // Login api    public function login(Request $request): JsonResponse{        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){            $user = Auth::user();            $success['token'] =  $user->createToken('MyApp')->plainTextToken;            $success['name'] =  $user->name;            return $this->sendResponse($success, 'User login successfully.');        }        else{            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);        }    }}

最后,转到 app/Http/Controllers/API/BlogController.php

namespace App\Http\Controllers\API;use App\Http\Controllers\Controller;use Illuminate\Http\Request;use App\Http\Controllers\API\BaseController;use App\Models\Blog;use App\Http\Resources\BlogResource;use Illuminate\Http\JsonResponse;use Illuminate\Support\Facades\Validator;class BlogController extends BaseController{    // Display a listing of the resource.    public function index(): JsonResponse{        $blogs = Blog::all();        return $this->sendResponse(BlogResource::collection($blogs), 'Blogs retrieved successfully.');    }    // Store a newly created resource in storage.    public function store(Request $request): JsonResponse{        $input = $request->all();        $validator = Validator::make($input, [            'title' => 'required',            'detail' => 'required'        ]);        if($validator->fails()){            return $this->sendError('Validation Error.', $validator->errors());        }        $blog = Blog::create($input);        return $this->sendResponse(new BlogResource($blog), 'Blog created successfully.');    }    // Display the specified resource.    public function show($id): JsonResponse{        $blog = Blog::find($id);        if (is_null($blog)) {            return $this->sendError('Blog not found.');        }        return $this->sendResponse(new BlogResource($blog), 'Blog retrieved successfully.');    }    // Update the specified resource in storage.    public function update(Request $request, Blog $blog): JsonResponse{        $input = $request->all();        $validator = Validator::make($input, [            'title' => 'required',            'detail' => 'required'        ]);        if($validator->fails()){            return $this->sendError('Validation Error.', $validator->errors());        }        $blog->title = $input['title'];        $blog->detail = $input['detail'];        $blog->save();        return $this->sendResponse(new BlogResource($blog), 'Blog updated successfully.');    }    // Remove the specified resource from storage.    public function destroy(Blog $blog): JsonResponse{        $blog->delete();        return $this->sendResponse([], 'Blog deleted successfully.');    }}

步骤 7:创建 API 路由

在此步骤中,我们将为登录、注册和博客创建 API 路由。

转到 routes/api.php

use Illuminate\Http\Request;use Illuminate\Support\Facades\Route;use App\Http\Controllers\API\RegisterController;use App\Http\Controllers\API\BlogController;Route::controller(RegisterController::class)->group(function(){    Route::post('register', 'register')->name('register');    Route::post('login', 'login')->name('login');});Route::middleware('auth:sanctum')->group( function () {    Route::apiResource('blogs', BlogController::class);    Route::get('user', function (Request $request) {        return $request->user();    })->name('user');});

步骤 8:运行 Laravel 应用程序

运行数据库迁移(迁移前在 .env 中设置数据库连接)

php artisan serve

启动本地开发服务器

php artisan serve

步骤 9:检查 API

现在,去你的 Postman 检查 api

确保在详细信息 API 中,我们将使用下面列出的以下标头

'headers' => [    'Accept' => 'application/json',    'Authorization' => 'Bearer '.$accessToken,]

现在,您可以简单地运行上面列出的 URL,如下屏幕截图所示:

Postman
Laravel 11 - 使用 Sanctum 构建 API-2
Laravel 11 - 使用 Sanctum 构建 API-3
Laravel 11 - 使用 Sanctum 构建 API-4
Laravel 11 - 使用 Sanctum 构建 API-5
Laravel 11 - 使用 Sanctum 构建 API-6
Laravel 11 - 使用 Sanctum 构建 API-7
Laravel 11 - 使用 Sanctum 构建 API-8
Laravel 11 - 使用 Sanctum 构建 API-9

希望对大家有所帮助!~

相关文章

塑造我成为 CTO 之路的“秘诀”
“人工智能教母”的公司估值达 10 亿美金
教授吐槽:985 高校成高级蓝翔!研究生基本废了,只为房子、票子……
Windows 蓝屏中断提醒开发者:Rust 比 C/C++ 更好
Claude 3.5 Sonnet 在伽利略幻觉指数中名列前茅
上海新增 11 款已完成登记生成式 AI 服务

发布评论