文档
Laravel 入门教程:从零构建一个 Task API
1. 背景
Laravel 是目前 PHP 生态最流行的框架。本教程带你从零搭建一个 RESTful Task API,学会路由、控制器、模型、迁移和 Eloquent ORM 的核心用法。
2. 前置概念
| 概念 | 说明 |
|---|---|
| 路由 (Route) | 将 URL 映射到控制器方法 |
| 控制器 (Controller) | 处理 HTTP 请求逻辑 |
| 模型 (Model) | Eloquent ORM 的数据实体 |
| 迁移 (Migration) | 数据库版本控制 |
| 中间件 (Middleware) | 请求过滤层 |
3. 分步操作
步骤一:创建项目
composer create-project laravel/laravel task-api
cd task-api
php artisan serve
步骤二:创建 Task 模型和迁移
php artisan make:model Task -m
编辑 database/migrations/xxxx_create_tasks_table.php:
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description')->nullable();
$table->enum('status', ['pending', 'in_progress', 'done'])->default('pending');
$table->timestamps();
});
运行迁移:
php artisan migrate
步骤三:编辑模型
app/Models/Task.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
use HasFactory;
protected $fillable = ['title', 'description', 'status'];
protected $casts = [
'status' => 'string',
];
}
步骤四:创建控制器
php artisan make:controller Api/TaskController
app/Http/Controllers/Api/TaskController.php:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Task;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class TaskController extends Controller
{
public function index(): JsonResponse
{
return response()->json(Task::all());
}
public function store(Request $request): JsonResponse
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string',
]);
$task = Task::create($validated);
return response()->json($task, 201);
}
public function show(Task $task): JsonResponse
{
return response()->json($task);
}
public function update(Request $request, Task $task): JsonResponse
{
$validated = $request->validate([
'title' => 'sometimes|string|max:255',
'description' => 'nullable|string',
'status' => 'sometimes|in:pending,in_progress,done',
]);
$task->update($validated);
return response()->json($task);
}
public function destroy(Task $task): JsonResponse
{
$task->delete();
return response()->json(null, 204);
}
}
步骤五:注册 API 路由
routes/api.php:
Route::apiResource('tasks', \App\Http\Controllers\Api\TaskController::class);
4. 验证
# 创建
curl -X POST http://localhost:8000/api/tasks \
-H "Content-Type: application/json" \
-d '{"title":"学习 Laravel","description":"阅读官方文档"}'
# 列表
curl http://localhost:8000/api/tasks
# 更新
curl -X PUT http://localhost:8000/api/tasks/1 \
-H "Content-Type: application/json" \
-d '{"status":"done"}'
# 删除
curl -X DELETE http://localhost:8000/api/tasks/1
5. 思考题
- 如何为 Task 添加用户关联(多对一)?
- 如何使用
apiResource的except限制路由? - 如何自定义
404时的 JSON 响应格式?