Laravel 升级索引
从 5.4 升级到 5.5.0
预计升级耗时:1小时
我们尽量记录每一个可能的破坏性变化。但因为其中一些不兼容变更只存在于框架很不起眼的地方,事实上只有一小部分可能会影响到你的应用程序。
更新依赖
在 composer.json 文件中将 laravel/framework 更新为 5.5.* 。 此外,你还应该将 phpunit/phpunit 依赖关系更新到 ~6.0。
如果你是通过使用 laravel new 来安装 Laravel 程序,则应该使用命令 composer global update 来更新 Laravel 安装程序包。
Laravel Dusk
Laravel Dusk 2.0.0 已经发布,该版本同时兼容 Laravel 5.5 和 Chrome 的 headless 模式测试。
Pusher
Pusher 事件广播驱动现在需要 ~3.0 版本的 Pusher SDK。
Artisan
fire 方法
该方法已重命名为 handle 方法。
optimize 命令
随着对 PHP 操作码缓存的最新改进,不再需要优化 Artisan 命令。你应该从部署脚本中删除对此命令的任何引用,因为它在未来的 Laravel 版本中会被删除。
用户授权
authorizeResouce 控制器方法
当将一个大驼峰命名的模型名称传递给 authorizeResource 方法时,为了和资源 控制器的行为相匹配,生成的路由会用蛇形命名法来命名。
before 策略方法
如果类中不包含与给定名称相匹配的方法,则不会调用策略类的 before 方法。
缓存
数据库驱动
如果你正在使用数据库缓存驱动,那在你第一次部署升级至 Laravel 5.5时,应该先运行 php artisan cache:clear 命令。
Eloquent
belongsToMany 方法
如果你在 Eloquent 模型中重写了 belongsToMany 方法,应该更新方法签名来映射新增的参数:
/**
* 定义多对多关系。
*
* @param string $related
* @param string $table
* @param string $foreignPivotKey
* @param string $relatedPivotKey
* @param string $parentKey
* @param string $relatedKey
* @param string $relation
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function belongsToMany($related, $table = null, $foreignPivotKey = null,
$relatedPivotKey = null,$parentKey = null,
$relatedKey = null, $relation = null)
{
//
}
模型的 is 方法
如果你重写了 Eloquent 模型的 is 方法 ,则应该从该方法中删除 Model 的类型提示。这将允许 is 方法接受 null 作为参数。
/**
* 确定两个模型是否具有相同的ID并且属于同一个表。
*
* @param \Illuminate\Database\Eloquent\Model|null $model
* @return bool
*/
public function is($model)
{
//
}
模型 $events 属性
模型上的 $events 属性应该重命名为 $dispatchesEvents。由于大量用户需要定义事件关系,导致与旧属性名称的冲突,因此进行了更改。
中间表 $parent 属性
Illuminate\Database\Eloquent\Relations\Pivot 类中受保护的 $parent 属性已被重命名为 $pivotParent 。
关联 create 方法
BelongsToMany、HasOneOrMany 以及 MorphOneOrMany 类中的 create 方法已被修改为 $attributes 参数提供默认值。如果你重写了这些方法,你应该更新你的签名来匹配新的定义。
public function create(array $attributes = [])
{
//
}
软删除模型
删除 「软删除」 模型时,模型上的 exists 属性将保持为 true 。
withCount 列格式化
当使用别名 时,withCount 方法将不再自动将 _count 附加到生成的列名称上。例如,在 Laravel 5.4 中,以下查询会将 bar_count 列添加到查询中:
$users = User::withCount('foo as bar')->get();
但是在 Laravel 5.5 中,别名将严格按照给定的方式使用。如果要将 _count 追加到结果列,则必须在定义别名时指定该后缀:
$users = User::withCount('foo as bar_count')->get();
异常格式
在 Laravel 5.5 中,所有的异常(包括验证异常)都被异常处理程序转换成 HTTP 响应。另外,验证错误默认返回的 JSON 格式已经更改。新格式遵循以下规则:
{
"message": "The given data was invalid.",
"errors": {
"field-1": [
"Error 1",
"Error 2"
],
"field-2": [
"Error 1",
"Error 2"
],
}
}
但是,如果你想沿用 Laravel 5.4 错误提示的 JSON 格式,则可以将以下方法添加到 App\Exceptions\Handler 类中:
use Illuminate\Validation\ValidationException;
/**
* 将验证异常转换成 JSON 响应
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
return response()->json($exception->errors(), $exception->status);
}
JSON 身份验证尝试
此更改也会影响通过 JSON 进行的身份验证尝试的验证错误返回的格式。在 Laravel 5.5 中,身份验证失败的 JSON 将按照上述新的格式约定返回错误消息。