Laravel 7.X 引入了多个重要特性,以下是核心更新概览:
1. 路由模型绑定优化
-
自定义键名 :支持通过非
id字段绑定路由参数(如slug)。php// 路由定义 Route::get('posts/{post:slug}', function (Post $post) { return $post; });
2. 自定义 Eloquent 类型转换
-
类型转换类 :支持自定义
Castable接口处理复杂数据类型转换。phpclass User extends Model { protected $casts = [ 'options' => JsonCast::class, // 自定义转换类 ]; }
3. HTTP 客户端
-
内置 HTTP 请求库 :简化 API 调用,支持并发请求与模拟测试。
php$response = Http::withToken($token)->post('https://api.example.com/data', [ 'key' => 'value' ]);
4. 路由签名 URL
-
防篡改链接 :通过
URL::signedRoute()生成带签名的临时访问链接。php$url = URL::signedRoute('unsubscribe', ['user' => 1]); // 验证签名 Route::get('unsubscribe/{user}', function (Request $request) { if (!$request->hasValidSignature()) { abort(403); } });
5. CORS 中间件
-
跨域支持 :内置
HandleCors中间件,替代手动配置 CORS 头。php// Kernel.php protected $middleware = [ \Fruitcake\Cors\HandleCors::class, ];
6. Blade 组件增强
-
动态组件 :通过
<x-dynamic-component>动态渲染组件。blade<x-dynamic-component :component="$componentName" :data="$data" />
7. 队列优化
-
失败作业批处理 :通过
php artisan queue:failed-batch重试整个批次的失败任务。php$batch = Bus::batch([ ... ])->then(function (Batch $batch) { // 成功回调 })->catch(function (Batch $batch, Throwable $e) { // 失败回调 })->dispatch();
8. Artisan 命令改进
-
命令交互提示 :支持
ask()、confirm()等方法实现交互式命令行。php$name = $this->ask('What is your name?');
9. Eloquent 子查询优化
-
子查询增强 :支持在
select和orderBy中直接使用子查询。phpUser::select(['id', 'name', Post::select('title')->whereColumn('posts.user_id', 'users.id') ]);
10. 其他更新
- Symfony 5 支持:依赖升级至 Symfony 5.X。
- 中文文档:提供官方中文文档支持。
- Carbon 时区扩展 :内置
Carbon扩展支持时区转换。
升级注意事项
- PHP 版本:需 PHP ≥ 7.2.5。
- 依赖冲突 :检查
composer.json中第三方包兼容性。 - 路由签名 :替换旧的
URL::temporarySignedRoute为URL::signedRoute。
完整特性参考 Laravel 7 官方文档。