本文目录导读:

我来详细介绍 PHP Jetstream 的使用方法。
什么是 Laravel Jetstream
Jetstream 是 Laravel 的官方认证和团队管理脚手架,提供了完整的登录、注册、邮箱验证、双因素认证等功能。
安装步骤
创建新项目并安装 Jetstream
# 创建新项目 composer create-project laravel/laravel your-app-name # 进入项目目录 cd your-app-name # 安装 Jetstream composer require laravel/jetstream # 安装 Livewire 版(推荐)或 Inertia 版 php artisan jetstream:install livewire # 或者 php artisan jetstream:install inertia # 或者使用团队功能 php artisan jetstream:install livewire --teams # 安装前端依赖 npm install npm run build # 运行迁移 php artisan migrate
主要功能
登录和注册
// 登录路由已经自动配置 // 访问 /login 或 /register 即可
邮箱验证
// 在 User model 中已内置
// 自动处理邮箱验证逻辑
public function mustVerifyEmail(): bool
{
return true; // 强制要求邮箱验证
}
双因素认证(2FA)
// 用户设置页面包含 2FA 配置 // 在设置中启用 Google Authenticator
配置文件
// config/jetstream.php 中的主要配置
return [
'features' => [
Features::registration(), // 注册功能
Features::emailVerification(), // 邮箱验证
Features::twoFactorAuthentication(), // 双因素认证
Features::updateProfileInformation(), // 更新个人信息
Features::updatePasswords(), // 更新密码
Features::apiTokens(), // API 令牌
Features::teams(), // 团队功能
],
];
自定义视图
修改认证页面
# 发布认证视图 php artisan vendor:publish --tag=jetstream-views
自定义注册表单
// resources/views/auth/register.blade.php
<x-guest-layout>
<x-jet-authentication-card>
<x-slot name="logo">
<!-- 自定义 logo -->
</x-slot>
<x-jet-validation-errors class="mb-4" />
<form method="POST" action="{{ route('register') }}">
@csrf
<!-- 自定义字段 -->
<div>
<x-jet-label for="name" value="{{ __('Name') }}" />
<x-jet-input id="name" class="block mt-1 w-full" type="text" name="name" required autofocus autocomplete="name" />
</div>
<!-- 添加自定义字段 -->
<div class="mt-4">
<x-jet-label for="username" value="{{ __('Username') }}" />
<x-jet-input id="username" class="block mt-1 w-full" type="text" name="username" required />
</div>
<!-- 密码、确认密码、邮箱等 -->
</form>
</x-jet-authentication-card>
</x-guest-layout>
自定义路由
// routes/web.php 中添加自定义路由
Route::middleware(['auth:sanctum', 'verified'])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
// 自定义受保护路由
Route::get('/profile', [ProfileController::class, 'show'])->name('profile.show');
});
Action 类
Jetstream 使用 Action 类来处理特定操作:
// app/Actions/Fortify/UpdateUserProfileInformation.php
namespace App\Actions\Fortify;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\UpdatesUserProfileInformation;
class UpdateUserProfileInformation implements UpdatesUserProfileInformation
{
public function update($user, array $input)
{
// 自定义验证规则
$validatedData = Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'max:255'],
'username' => ['required', 'string', 'max:255', Rule::unique('users')->ignore($user->id)],
])->validate();
// 更新用户
return $user->forceFill($validatedData)->save();
}
}
团队功能(如果启用)
// 创建团队
use Laravel\Jetstream\Jetstream;
$team = Jetstream::newTeamModel()->create([
'user_id' => auth()->id(),
'name' => '我的团队',
]);
// 添加成员
$team->users()->attach($userId, ['role' => 'admin']);
// 检查团队角色
if ($team->hasUser(auth()->user()) && $team->userIsAdmin(auth()->user())) {
// 管理员操作
}
权限和中间件
// 使用权限中间件
Route::middleware(['auth:sanctum', 'can:update,team'])->group(function () {
Route::get('/team/settings', [TeamController::class, 'settings']);
});
// 在控制器中检查权限
public function update(Team $team)
{
$this->authorize('update', $team);
// 操作
}
常见问题和解决方案
修改默认登录跳转地址
// app/Providers/RouteServiceProvider.php public const HOME = '/dashboard'; // 修改路径 // 或者自定义 RedirectIfAuthenticated
添加自定义字段到注册
- 修改
FortifyServiceProvider.php - 创建自定义 Action
- 更新数据库迁移
// app/Providers/FortifyServiceProvider.php
public function boot()
{
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::registerView(function () {
return view('auth.register');
});
}
禁用注册功能
// config/fortify.php
'features' => [
Features::registration(), // 注释掉这一行
],
最佳实践
- 自定义 Policy:为团队和资源添加访问控制
- 深度定制:通过发布视图和 Action 类实现深度定制
- 性能优化:使用 Laravel 内置的缓存和队列功能
- 安全加固:启用 HTTPS、添加安全中间件
Jetstream 提供了完整的认证体系,你可以在此基础上快速构建强大的 Web 应用,如果你需要更具体的功能或是遇到问题,欢迎继续提问!