前言
虽然一般情况下我们通常需要进行验证和异常处理,但是这次主要是介绍API的实施步骤,所以其他的简单介绍一下就过了。
创建Laravel项目
使用 Composer
命令安装 Laravel 10。
composer create-project --prefer-dist laravel/laravel projectName
其中,projectName
是你的项目名称
设置API
php artisan install:api
快速创建模型(Model)、工厂(Factory)、迁移(Migration)和种子(Seeder)
php artisan make:model Todo -mfs
# INFO Model [app/Models/Todo.php] created successfully.
# INFO Factory [database/factories/TodoFactory.php] created successfully.
# INFO Migration [database/migrations/create_todos_table.php] created successfully.
# INFO Seeder [database/seeders/TodoSeeder.php] created successfully.
创建 Model 数据模型和其对应的数据表(table)
php artisan make:model Todos -m
内容如下:
//create_todos_table.php
<?php
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('todos', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('todos');
}
};
接着运行migrations
来创建表:
php artisan migrate
创建 Controller
php artisan make:controller TodoController --resource
Laravel 带有资源控制器的概念,资源控制器将经典的CRUD操作划分成一套具有恒定URI和调用方法的动作。
实现POST请求
TodoController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Models\Todo;
class TodoController extends Controller
{
public function store(Request $request) {
$todo = Todo::create($request->only('title'));
return response()->json(['todo' => $todo]);
}
}
Models\Todo.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
use HasFactory;
protected $fillable = ['title'];
}
- 设置 Route
在routes/api.php
中定义API路由:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::apiResource('todos', \App\Http\Controllers\TodoController::class);
测试
请求http://localhost:8080/api/todos
接口
实现GET请求
TodoController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Models\Todo;
class TodoController extends Controller
{
public function index() {
$todos = Todo::all();
return response()->json(['todos' => $todos]);
}
}
实现PUT请求
TodoController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Models\Todo;
class TodoController extends Controller
{
public function update(Request $request, $id) {
$todo = Todo::findOrFail($id);
$todo->update($request->only('title'));
return response()->json(['todo' => $todo]);
}
}
实现Delete请求
TodoController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Models\Todo;
class TodoController extends Controller
{
public function update(Request $request, $id) {
$todo = Todo::findOrFail($id);
$todo->delete();
return response()->json(null, 204);
}
}
Delete:http://localhost:8080/api/todos/1
评论(0)