Laravel 5.5 版本升级至 6.0

从 5.5 升级到 5.6

更新依赖

修改 composer.json 文件:

  • laravel/framework 版本更新为 5.6.*
  • fideloper/proxy 版本更新为 ~4.0
  • phpunit/phpunit 版本更新至 ~7.0
rm -rf vendor
rm -f composer.lock
composer install

配置文件

logging

<?php

use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;

return [
    
    /*
    |--------------------------------------------------------------------------
    | Default Log Channel
    |--------------------------------------------------------------------------
    |
    | This option defines the default log channel that gets used when writing
    | messages to the logs. The name specified in this option should match
    | one of the channels defined in the "channels" configuration array.
    |
    */
    
    'default' => env('LOG_CHANNEL', 'single'),
    
    /*
    |--------------------------------------------------------------------------
    | Log Channels
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log channels for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Drivers: "single", "daily", "slack", "syslog",
    |                    "errorlog", "monolog",
    |                    "custom", "stack"
    |
    */
    
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
            'ignore_exceptions' => false,
        ],
        
        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
        ],
        
        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 14,
        ],
        
        'slack' => [
            'driver' => 'slack',
            'url' => env('LOG_SLACK_WEBHOOK_URL'),
            'username' => 'Laravel Log',
            'emoji' => ':boom:',
            'level' => 'critical',
        ],
        
        'papertrail' => [
            'driver' => 'monolog',
            'level' => 'debug',
            'handler' => SyslogUdpHandler::class,
            'handler_with' => [
                'host' => env('PAPERTRAIL_URL'),
                'port' => env('PAPERTRAIL_PORT'),
            ],
        ],
        
        'stderr' => [
            'driver' => 'monolog',
            'handler' => StreamHandler::class,
            'formatter' => env('LOG_STDERR_FORMATTER'),
            'with' => [
                'stream' => 'php://stderr',
            ],
        ],
        
        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],
        
        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
        
        'null' => [
            'driver' => 'monolog',
            'handler' => NullHandler::class,
        ],
        
        'emergency' => [
            'path' => storage_path('logs/laravel.log'),
        ],
    ],

];

分页

// 分页器默认使用 Bootstrap 4 生成,如果需要生成 Bootstrap 3 的链接,需要在AppServiceProviderboot 方法中添加:

<?php

namespace App\Providers;

use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     *  引导任何应用程序服务。
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrapThree();
    }
}

可信任代理

App\Http\Middleware\TrustProxies 进行调整,之前是一个数组的 $headers 属性

/**
 * The current proxy header mappings.
 *
 * @var array
 */
protected $headers = [
    Request::HEADER_FORWARDED => 'FORWARDED',
    Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
    Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
    Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
    Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
];

调整为:

/**
 * The current proxy header mappings.
 *
 * @var int
 */
protected $headers = Request::HEADER_X_FORWARDED_ALL;

从 5.6 升级到 5.7

更新依赖

修改 composer.json 文件:

  • laravel/framework 版本更新为 5.7.*

前端模板

blade 模板中:

// Laravel 5.6...
{{ $foo or 'default' }}

// Laravel 5.7...
{{ $foo ?? 'default' }}

路由

Route::redirect 方法,返回 HTTP 状态码为 302,新增 permanentRedirect 方法实现 301 重定向:

// 返回302重定向...
Route::redirect('/foo', '/bar');

// 返回301重定向...
Route::redirect('/foo', '/bar', 301);

// 返回301重定向...
Route::permanentRedirect('/foo', '/bar');

Laravel 5.7 升级到 5.8

更新依赖

修改 composer.json 文件:

  • laravel/framework 版本更新为 5.8.*
rm -f composer.lock
rm -rf vendor/
composer install

遇到问题:

Class Dingo\Api\Exception\Handler contains 1 abstract method and must there
  fore be declared abstract or implement the remaining methods (Illuminate\Co
  ntracts\Debug\ExceptionHandler::shouldReport)

dingo/api 的版本差异问题,更新 ding/api 的版本:
修改 composer.json 文件中的 "dingo/api": "2.0.0",

"dingo/api": "^2.1",

再重新执行:

rm -f composer.lock
rm -rf vendor/
composer install

缓存

缓存 TTL 以秒为单位:

// Laravel 5.7 - 存储数据30分钟
Cache::put('foo', 'bar', 30);

// Laravel 5.8 - 存储数据30秒
Cache::put('foo', 'bar', 30);

// Laravel 5.7 / 5.8 - 存储数据30秒
Cache::put('foo', 'bar', now()->addSeconds(30));

调整地方:

Cache::store('redis')->put('access_token', $result->access_token, ($result->expires_in / 60) - 20);

修改为:

Cache::store('redis')->put('access_token', $result->access_token, $result->expires_in - 200);

Eloquent

Eloquent 模型命名中的不规则复数结尾:

// Laravel 5.7...
App\Feedback.php -> feedback (正确的复数形式)
App\UserFeedback.php -> user_feedbacks (错误的复数形式)

// Laravel 5.8
App\Feedback.php -> feedback (正确的复数形式)
App\UserFeedback.php -> user_feedback (正确的复数形式)

如果在模型中没有正确的使用复数名称,需要修改模型中的 $table 属性进行指定:

/**
 * 与模型关联的数据表名称。
 *
 * @var string
 */
protected $table = 'user_feedbacks';

辅助函数

优先使用字符串和数组类而不是辅助函数

所有的 array_* and str_* 全局辅助函数 都被废弃。你需要直接使用 Illuminate\Support\Arr 和 Illuminate\Support\Str 提供的方法。

调整地方:
系统中的所有使用 str_random 都需要替换为:Str::random

bootstrap.php 文件中添加定义的函数:

function getStrRandom(int $length = 16)
{
    return Str::random($length);
}

之后直接将所有的 str_random 替换为 getStrRandom

Laravel 5.8 升级到 6.0

更新依赖

composer.json 文件中修改:

 "laravel/framework": "^6.0",

检查使用的第三方的软件包,是否适配 Laravel 6 版本:
"hieu-le/active": "~3.5", 修改为 "hieu-le/active": "~4.0",
"laravel/framework": "5.8.*", 修改为 "laravel/framework": "^6.0",
"spatie/laravel-permission": "^2.12", 修改为 "spatie/laravel-permission": "~3.0",
"tymon/jwt-auth": "1.0.0-rc.4.1" 修改为 "tymon/jwt-auth": "1.0.0-rc.5"

"phpunit/phpunit": "~7.0", 修改为 "phpunit/phpunit": "^8.0",

> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

In cache.php line 91:

  Call to undefined function str_slug()


Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

全局搜索 str_slug 函数,进行替换

config/cache.php

'prefix' => env(
        'CACHE_PREFIX',
        str_slug(env('APP_NAME', 'laravel'), '_').'_cache'
    ),

config/session.php

'cookie' => env(
        'SESSION_COOKIE',
        str_slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),

以上两处的 str_slug 需要替换为 Str::slug

Carbon

Carbon 1.x 不再被支持,需要升级到 Carbon 2

Eloquent

BelongsTo::update 方法

为了保持一致性,现在 BelongsTo 关系模型的 update 方法起到了临时更新查询的作用,这意味着它不提供批量赋值保护或触发 Eloquent 事件。这使得该关联关系与所有其它关联关系类型的 update 方法一致。
如果你通过 BelongsTo 更新关联关系连接的模型,并获取批量赋值更新保护和事件触发,则需要在模型自身上调用 update 方法:

// 临时查询…没有批量赋值保护或事件触发…
$post->user()->update(['foo' => 'bar']);

// 模型更新…提供批量赋值保护和事件触发…
$post->user->update(['foo' => 'bar']);

Arrayable 类和 toArray 方法

toArray 将会把任何属性类型强制转换为数组

主键类型声明:

如果数据库的表使用的是字符串作为模型的主键,则需要在模型属性中添加 $keyType 声明密钥类型:

/**
 * 主键 ID 的「类型」。
 *
 * @var string
 */
protected $keyType = 'string';

队列重试限制:

之前的 Laravel 版本中,php artisan queue:work 命令会无限期重试队列任务,从 Laravel 6.0 开始,该命令默认只会重试队列任务一次,如果你想要强制任务无限期重试,可以通过 --tries=0 指定

php artisan queue:work --tries=0

Request

Input 被移除,如果有在使用 Input::get 需要替换成 Request::input

路由 URL 生成 & 提取参数

Route::get('/profile/{location?}', function ($location = null) {
    //
})->name('profile');

// Laravel 5.8: http://example.com/profile/active
echo route('profile', ['status' => 'active']);

// Laravel 6.0: http://example.com/profile?status=active
echo route('profile', ['status' => 'active']);    

发表评论

您的电子邮箱地址不会被公开。