Laravel 9.x 是 Laravel 框架的重要版本更新,于2022年2月发布,主要特性如下:
1. PHP 8.0+ 强制依赖
- 最低要求 PHP 8.0
- 全面支持 PHP 8.1 新特性(枚举、只读属性等)
php
// PHP 8.1 枚举示例
enum Status: string {
case Pending = 'pending';
case Active = 'active';
}
2. Symfony 6.x 组件升级
- 邮件组件升级至 Symfony Mailer(替换 Swift Mailer)
- 改进的邮件发送队列处理
php
Mail::to('user@example.com')->queue(new OrderShipped($order));
3. 模型访问器/修改器新语法
- 更简洁的模型属性处理方式
php
// 传统方式
public function getNameAttribute($value) { /* ... */ }
// 9.x 新语法
protected function name(): Attribute {
return Attribute::make(
get: fn ($value) => strtoupper($value),
set: fn ($value) => strtolower($value),
);
}
4. 匿名迁移类
- 避免迁移类命名冲突
php
use Illuminate\Database\Migrations\Migration;
return new class extends Migration {
public function up() { /* ... */ }
};
5. 路由控制器改进
- 路由组控制器自动前缀
php
// 所有路由自动应用 UserController
Route::controller(UserController::class)->group(function () {
Route::get('/profile', 'showProfile');
Route::put('/profile', 'updateProfile');
});
6. SCOUT 数据库引擎
- 新增轻量级全文搜索方案
bash
composer require laravel/scout
php artisan scout:install
7. 测试辅助函数增强
freezeTime()时间冻结travelTo()时间穿梭
php
// 测试时间控制
$this->freezeTime();
$this->travelTo(now()->addDays(7));
8. Flysystem 3.x 集成
- 云存储操作标准化
php
Storage::disk('s3')->put('file.jpg', $content);
9. Ignition 错误页升级
- 增强的错误调试界面
- 代码片段上下文展示优化
- 解决方案建议功能
10. 查询构造器接口
- 强类型查询构建支持
php
DB::table('users')->where('votes', '>', 0)->get();
其他重要更新
| 模块 | 变更内容 |
|---|---|
| 前端脚手架 | 移除 Bootstrap,默认使用 Vite |
| 事件监听器 | 支持监听器队列自动发现 |
| 任务调度 | 新增 everyMinute() 快捷方法 |
| 加密机制 | 使用 OpenSSL 替代 Mcrypt |
建议升级前使用官方升级指南进行兼容性检查:
bash
composer create-project laravel/laravel example-app