Laravel 7.X 引入了多个重要特性,以下是核心更新概览:


1. 路由模型绑定优化

  • 自定义键名:支持通过非 id 字段绑定路由参数(如 slug)。
    // 路由定义
    Route::get('posts/{post:slug}', function (Post $post) {
        return $post;
    });
    


2. 自定义 Eloquent 类型转换

  • 类型转换类:支持自定义 Castable 接口处理复杂数据类型转换。
    class User extends Model {
        protected $casts = [
            'options' => JsonCast::class, // 自定义转换类
        ];
    }
    


3. HTTP 客户端

  • 内置 HTTP 请求库:简化 API 调用,支持并发请求与模拟测试。
    $response = Http::withToken($token)->post('https://api.example.com/data', [
        'key' => 'value'
    ]);
    


4. 路由签名 URL

  • 防篡改链接:通过 URL::signedRoute() 生成带签名的临时访问链接。
    $url = URL::signedRoute('unsubscribe', ['user' => 1]);
    // 验证签名
    Route::get('unsubscribe/{user}', function (Request $request) {
        if (!$request->hasValidSignature()) {
            abort(403);
        }
    });
    


5. CORS 中间件

  • 跨域支持:内置 HandleCors 中间件,替代手动配置 CORS 头。
    // Kernel.php
    protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,
    ];
    


6. Blade 组件增强

  • 动态组件:通过 <x-dynamic-component> 动态渲染组件。
    <x-dynamic-component :component="$componentName" :data="$data" />
    


7. 队列优化

  • 失败作业批处理:通过 php artisan queue:failed-batch 重试整个批次的失败任务。
    $batch = Bus::batch([ ... ])->then(function (Batch $batch) {
        // 成功回调
    })->catch(function (Batch $batch, Throwable $e) {
        // 失败回调
    })->dispatch();
    


8. Artisan 命令改进

  • 命令交互提示:支持 ask()confirm() 等方法实现交互式命令行。
    $name = $this->ask('What is your name?');
    


9. Eloquent 子查询优化

  • 子查询增强:支持在 selectorderBy 中直接使用子查询。
    User::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::temporarySignedRouteURL::signedRoute

完整特性参考 Laravel 7 官方文档

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐