Laravel 7.X 于2020年3月发布,引入了多项重要改进,以下是核心特性解析:
1. Laravel Airlock(Sanctum)
轻量级API认证系统,支持SPA/移动应用认证:
php
// 配置路由
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
2. 自定义Eloquent类型转换
支持自定义转换逻辑:
php
class User extends Model {
protected $casts = [
'options' => Json::class,
'birthday' => DateCast::class // 自定义转换器
];
}
3. Blade组件增强
新增组件标签语法:
blade
<x-alert type="error" :message="$message"/>
4. HTTP客户端优化
内置Guzzle封装,支持并行请求:
php
use Illuminate\Support\Facades\Http;
$response = Http::withToken($token)->post('https://api.example.com/data', [
'key' => 'value'
]);
5. 路由模型绑定优化
支持自定义键名和范围约束:
php
Route::get('users/{user:uuid}', function (User $user) {
return $user;
})->where('uuid', '[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}');
6. 多邮件驱动配置
支持同时配置多个邮件服务:
env
MAIL_MAILER=ses
MAIL_FROM_ADDRESS=notify@example.com
BACKUP_MAIL_MAILER=smtp
BACKUP_MAIL_HOST=backup.smtp.com
7. CORS原生支持
通过配置文件处理跨域请求:
php
// config/cors.php
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['https://app.example.com'],
8. 查询时类型转换
数据库查询阶段直接转换类型:
php
$users = User::query()
->select(['id', 'options'])
->withCasts(['options' => 'array'])
->get();
9. 新的字符串辅助函数
php
Str::of('Laravel 7')->after('Laravel '); // "7"
Str::of('/foo/bar')->replaceLast('/', ''); // "/foo"
10. 测试方法增强
新增expectException()等测试辅助方法:
php
$this->expectException(CustomException::class);
$this->get('/invalid-route');
性能提示 :路由缓存命令优化为单行操作:
php artisan route:cache相比6.X版本减少30%内存占用