好的,Laravel 8.x 引入了多项重要更新,主要特性如下:
1. 路由改进
-
路由缓存优化 :支持缓存包含闭包路由的应用(需使用
Route::enforceSchema),提升性能。 -
路由模型绑定简写:可直接在路由参数中使用模型类型提示:
```php use App\Models\User; Route::get('users/{user}', function (User $user) { return $user->email; }); ``` -
自定义路由键 :模型可通过
getRouteKeyName方法定义绑定字段。
2. 模型工厂类
模型工厂从闭包升级为类:
php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory {
protected $model = User::class;
public function definition() {
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
];
}
}
调用方式:
php
User::factory()->count(5)->create();
3. 迁移文件压缩
使用 Schema::create 时支持 compressed 选项生成更小的迁移文件。
4. Blade 组件优化
-
组件别名 :通过
component方法注册别名:phpBlade::component('alert', AlertComponent::class); -
内联组件:可直接在模板中定义组件逻辑。
5. 事件监听器改进
支持基于接口的模型事件监听:
php
use Illuminate\Contracts\Events\Dispatcher;
class UserObserver {
public function creating(User $user) {
// ...
}
}
6. 队列批处理
新增 Bus::batch 方法管理队列任务批次:
php
use Illuminate\Bus\Batch;
Batch::jobs([
new ProcessPodcast,
new SendNotification,
])->then(function (Batch $batch) {
// 成功回调
})->catch(function (Batch $batch, Throwable $e) {
// 失败处理
})->dispatch();
7. 测试辅助方法
assertDeleted:验证模型是否被软删除。assertNotSoftDeleted:验证模型未被软删除。
8. Jetstream 与 Fortify
- Jetstream:提供带有 Livewire/Inertia.js 的认证脚手架。
- Fortify:作为 Jetstream 的后端引擎,处理注册、登录等核心逻辑。
9. 其他更新
-
rateLimiter:增强的请求频率限制器。 -
maintenance mode:维护模式支持预渲染视图。 -
time testing:测试时可通过travel方法模拟时间流逝:php$this->travel(5)->minutes(); // 向前推进5分钟
注意:升级时需检查模型工厂、路由缓存等特性的兼容性。建议参考官方文档进行迁移。