关于 laravel
面向 PHP 开发者的 Laravel 12.x 开发技能,涵盖应用和 API 开发。内容通过示例与参考资料介绍路由、数据访问、身份验证和后台任务等实践。
主要功能
- 01路由与中间件模式
- 02Eloquent 模型与查询
- 03迁移与数据库填充
- 04身份验证与 API 开发
- 05队列、缓存与事件
- 06Artisan 命令示例
适用场景
- 01构建 Laravel 应用或 API
- 02设计关联并优化查询
- 03添加身份验证与 API 令牌
- 04排查 Laravel 错误或性能问题
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ rawveg/ skillsforge-marketplace --skill laravel安装后在 Claude Code 中输入/laravel确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
plugin.jsonreferences/index.mdother.md详细介绍
Laravel 技能
全面协助使用 Laravel 12.x 进行开发,包括路由、Eloquent ORM、迁移、身份验证、API 开发和现代 PHP 模式。
何时使用此技能
在以下情况下应触发此技能:
- 构建 Laravel 应用或 API
- 使用 Eloquent 模型、关联和查询
- 设置身份验证、授权或 API 令牌
- 创建数据库迁移、填充器或工厂
- 实现中间件、服务提供者或事件
- 使用 Laravel 内置功能(队列、缓存、验证等)
- 排查 Laravel 错误或性能问题
- 遵循 Laravel 最佳实践和约定
- 使用 Laravel Sanctum 或 Passport 实现 RESTful API
- 使用 Laravel Mix、Vite 或前端资源
快速参考
基本路由
// Basic routes
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
// Route parameters
Route::get('/users/{id}', function ($id) {
return User::find($id);
});
// Named routes
Route::get('/profile', ProfileController::class)->name('profile');
// Route groups with middleware
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::resource('posts', PostController::class);
});
Eloquent 模型基础
// Define a model with relationships
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Post extends Model
{
protected $fillable = ['title', 'content', 'user_id'];
protected $casts = [
'published_at' => 'datetime',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
}
数据库迁移
// Create a migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->text('content');
$table->timestamp('published_at')->nullable();
$table->timestamps();
$table->index(['user_id', 'published_at']);
});
}
public function down(): void
{
Schema::dropIfExists('posts');
}
};
表单验证
// Controller validation
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|max:255',
'content' => 'required',
'email' => 'required|email|unique:users',
'tags' => 'array|min:1',
'tags.*' => 'string|max:50',
]);
return Post::create($validated);
}
// Form Request validation
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => 'required|max:255',
'content' => 'required|min:100',
];
}
}
Eloquent 查询构造器
// Common query patterns
// Eager loading to avoid N+1 queries
$posts = Post::with(['user', 'comments'])
->where('published_at', '<=', now())
->orderBy('published_at', 'desc')
->paginate(15);
// Conditional queries
$query = Post::query();
if ($request->has('search')) {
$query->where('title', 'like', "%{$request->search}%");
}
if ($request->has('author')) {
$query->whereHas('user', function ($q) use ($request) {
$q->where('name', $request->author);
});
}
$posts = $query->get();
API 资源控制器
namespace App\Http\Controllers\Api;
use App\Models\Post;
use App\Http\Resources\PostResource;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
return PostResource::collection(
Post::with('user')->latest()->paginate()
);
}
public function store(Request $request)
{
$post = Post::create($request->validated());
return new PostResource($post);
}
public function show(Post $post)
{
return new PostResource($post->load('user', 'comments'));
}
public function update(Request $request, Post $post)
{
$post->update($request->validated());
return new PostResource($post);
}
}
API 资源(转换器)
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class PostResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'excerpt' => $this->excerpt,
'content' => $this->when($request->routeIs('posts.show'), $this->content),
'author' => new UserResource($this->whenLoaded('user')),
'comments_count' => $this->when($this->comments_count, $this->comments_count),
'published_at' => $this->published_at?->toISOString(),
'created_at' => $this->created_at->toISOString(),
];
}
}
使用 Sanctum 进行身份验证
// API token authentication setup
// In config/sanctum.php - configure stateful domains
// Issue tokens
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
// Login endpoint
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (!Auth::attempt($credentials)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
$token = $request->user()->createToken('api-token')->plainTextToken;
return response()->json(['token' => $token]);
}
// Protect routes
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', fn(Request $r) => $r->user());
});
作业与队列
// Create a job
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class ProcessVideo implements ShouldQueue
{
use InteractsWithQueue, Queueable;
public function __construct(
public Video $video
) {}
public function handle(): void
{
// Process the video
$this->video->process();
}
}
// Dispatch jobs
ProcessVideo::dispatch($video);
ProcessVideo::dispatch($video)->onQueue('videos')->delay(now()->addMinutes(5));
服务容器与依赖注入
// Bind services in AppServiceProvider
use App\Services\PaymentService;
public function register(): void
{
$this->app->singleton(PaymentService::class, function ($app) {
return new PaymentService(
config('services.stripe.secret')
);
});
}
// Use dependency injection in controllers
public function __construct(
protected PaymentService $payment
) {}
public function charge(Request $request)
{
return $this->payment->charge(
$request->user(),
$request->amount
);
}
参考文件
此技能在 references/ 中包含全面的文档:
- other.md - Laravel 12.x 安装指南和核心文档
使用参考文件了解以下内容的详细信息:
- 安装和配置
- 框架架构与概念
- 高级功能和软件包
- 部署与优化
核心概念
MVC 架构
Laravel 遵循模型-视图-控制器模式:
- 模型:表示数据库表的 Eloquent ORM 类
- 视图:用于渲染 HTML 的 Blade 模板
- 控制器:处理 HTTP 请求并返回响应
Eloquent ORM
Laravel 强大的数据库抽象层:
- 活动记录模式:每个模型实例代表一条数据库记录
- 关联:belongsTo、hasMany、belongsToMany、morphMany 等
- 查询构造器:用于构建 SQL 查询的流畅接口
- 预加载:使用
with()避免 N+1 查询问题
路由
定义应用端点:
- 路由方法:get、post、put、patch、delete
- 路由参数:必需的
{id}和可选的{id?} - 路由组:共享中间件、前缀和命名空间
- 资源路由:自动生成 RESTful 路由
中间件
过滤 HTTP 请求:
- 内置中间件:auth、throttle、verified、signed
- 自定义中间件:创建自己的请求/响应过滤器
- 全局中间件:应用于所有路由
- 特定路由中间件:应用于特定路由或路由组
服务容器
Laravel 的依赖注入容器:
- 自动解析:在构造函数中使用类型提示声明依赖项
- 绑定:注册类实现
- 单例:在多个请求间共享同一个实例
Artisan 命令
Laravel 的 CLI 工具:
php artisan make:model Post -mcr # Create model, migration, controller, resource
php artisan migrate # Run migrations
php artisan db:seed # Seed database
php artisan queue:work # Process queue jobs
php artisan optimize:clear # Clear all caches
使用此技能
初学者
从以下内容开始:
- 安装:使用 Composer 设置 Laravel
- 路由:学习在
routes/web.php中定义基本路由 - 控制器:使用
php artisan make:controller创建控制器 - 模型:了解 Eloquent 基础知识和关联
- 迁移:使用迁移定义数据库架构
- Blade 模板:使用 Laravel 模板引擎创建视图
中级用户
重点关注:
- 表单请求:在专用类中进行验证和授权
- API 资源:转换模型以用于 JSON 响应
- 身份验证:使用 Laravel Breeze 或 Sanctum 实现
- 关联:掌握预加载和复杂关联
- 队列:将耗时任务转移到后台作业
- 事件与监听器:解耦应用逻辑
面向高级用户
探索:
- 服务提供者:注册应用服务
- 自定义中间件:创建可复用的请求过滤器
- 包开发:构建可复用的 Laravel 包
- 测试:使用 PHPUnit 编写功能测试和单元测试
- 性能:优化查询、缓存和响应时间
- 部署:CI/CD 流水线和生产环境优化
导航提示
- 查看 快速参考,了解常见代码模式
- 参考官方文档:https://laravel.com/docs/12.x
- 使用
php artisan route:list查看所有已注册的路由 - 使用
php artisan tinker进行交互式调试 - 启用查询日志,调试数据库性能
常见模式
仓储模式
interface PostRepositoryInterface
{
public function all();
public function find(int $id);
public function create(array $data);
}
class PostRepository implements PostRepositoryInterface
{
public function all()
{
return Post::with('user')->latest()->get();
}
public function find(int $id)
{
return Post::with('user', 'comments')->findOrFail($id);
}
}
操作类(单一职责)
class CreatePost
{
public function execute(array $data): Post
{
return DB::transaction(function () use ($data) {
$post = Post::create($data);
$post->tags()->attach($data['tag_ids']);
event(new PostCreated($post));
return $post;
});
}
}
查询范围
class Post extends Model
{
public function scopePublished($query)
{
return $query->where('published_at', '<=', now());
}
public function scopeByAuthor($query, User $user)
{
return $query->where('user_id', $user->id);
}
}
// Usage
Post::published()->byAuthor($user)->get();
资源
官方文档
- Laravel 文档:https://laravel.com/docs/12.x
- API 参考:https://laravel.com/api/12.x
- Laracasts:https://laracasts.com(视频教程)
社区
- Laravel News:https://laravel-news.com
- Laravel 论坛:https://laracasts.com/discuss
- GitHub:https://github.com/laravel/laravel
工具
- Laravel Telescope:调试和监控
- Laravel Horizon:队列监控
- Laravel Debugbar:开发调试
- Laravel IDE Helper:IDE 自动补全
最佳实践
- 使用表单请求:将验证逻辑与控制器分离
- 预加载关联关系:避免 N+1 查询问题
- 使用资源控制器:遵循 RESTful 约定
- 类型提示:利用 PHP 类型声明,获得更好的 IDE 支持
- 数据库事务:将相关数据库操作封装在事务中
- 队列任务:将耗时操作交由后台工作进程处理
- 缓存查询:缓存开销较大的数据库查询
- API 资源:以一致的方式转换 API 数据
- 事件:通过事件和监听器解耦应用逻辑
- 测试:为关键应用逻辑编写测试
注意事项
- Laravel 12.x 要求 PHP 8.2 或更高版本
- 使用 Composer 管理依赖项
- 使用 Vite 编译资源(取代 Laravel Mix)
- 支持多种数据库系统(MySQL、PostgreSQL、SQLite、SQL Server)
- 内置队列、缓存、会话和文件存储支持
- 拥有完善的生态系统,包含官方一方软件包(Sanctum、Horizon、Telescope 等)
评论
支持 Markdown