17611538698
webmaster@21cto.com

Laravel 11 - 使用 Sanctum 构建 API

编程语言 0 181 2024-06-23 07:24:16

图片

导读:有读者互动,提出经常使用的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/BaseController
php artisan make:controller API/RegisterController
php 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
图片
图片
图片
图片
图片
图片
图片
图片

希望对大家有所帮助!~

评论