Upgrade Instructions


#Upgrade Guide

    Upgrading from 5.7 to 5.8.0
High Impact Changes

    Cache TTL in seconds
  • Security improvements for cache locks
  • Markdown file path changes
  • Nexmo/Slack notification channel Changes
Medium Impact Changes

    Container Builder and Tag Service
  • SQLite Version Constraints
  • Replace Helpers with classes for strings and arrays
  • Deprecated Deferred service provider
  • Comply with PSR-16 specification
  • Improve model name endings for irregular plurals
  • Add auto-increment id attribute to custom intermediate table model
  • Support Pheanstalk 4.0 library

Updating from Laravel 5.7 to 5.8

Estimated upgrade time: 1 hour

Note: We try to document every possible change. Because most breaking changes are internal to the framework, only a subset of these changes may affect your application.

Update dependencies

In composer.json, update the laravel/framework dependency to 5.8.*.

Next, check whether the installed third-party packages in the application support Laravel 5.8, and check whether the installed version is correct.

Application Contract

environment Method

Possibility of impact: Very low

Illuminate /Contracts/Foundation/Application Classenvironment The signature of the method has been modified. If this method is overridden in your application, you should update the signature of this method:

/**
 * 获取或检查当前应用程序的环境
 *
 * @param  string|array  $environments
 * @return string|bool
 */public function environment(...$environments);

Newly added method

Possibility of impact: Very low

The following new methods are addedbootstrapPath, configPath, databasePath, environmentPath, resourcePath, storagePath, resolveProvider, bootstrapWith, configurationIsCached, detectEnvironment, environmentFile, environmentFilePath, getCachedConfigPath, getCachedRoutesPath, getLocale, getNamespace, getProviders, hasBeenBootstrapped , loadDeferredProviders, loadEnvironmentFrom, routesAreCached, setLocale, shouldSkipMiddleware, terminate will be added to Illuminate/Contracts/Foundation/Application.

If you implement this interface, you should add these methods to the implementation class.

Authentication

Reset password notification routing parameters

Possibility of impact: Low

When the user clicks the reset password link , Laravel uses the route helper to generate the URL to create a route named with password.reset. When using Laravel 5.7, the token will be passed to the URL without an explicit name. route Helper, for example:

route('password.reset', $token);

When you use Laravel 5.8, the token is passed as an explicit parameter to the route helper:

route('password.reset', ['token' => $token]);

Therefore, If you want to define your own password.reset route, its uri must contain a token parameter.

Default password length changed

Likelihood of impact: Low

The required password length when selecting or resetting a password is changed to at least eight characters .

Cache

TTL in seconds

Possibility of impact: Very high

To allow for more granular expiration times when storing data, the cached data lifetime was changed from minutes to seconds. Illuminate\Cache\Repository class and its extension classes put , putMany , add , remember and The setDefaultCacheTime method, and the put method of all cache stores accomplish this update. Please see the related PR for details.

If you are passing an integer to any of these methods, update your code to ensure that the data being passed in the cache is passed in seconds. Additionally, you can pass a DateTime instance to indicate when the data expires:

// 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));

{Tip} This change makes the Laravel cache system fully compliant with the PSR-16 cache library standard.

Follow PSR-16

Possibility of impact: Medium

In addition to the changes in the above return values, this upgrade also updates Changed the TTL parameters of the put, putMany and add methods in the Illuminate\Cache\Repository class to make them more compliant with PSR-16 specification. The new feature provides a default null, so if you do not specify a TTL value, the cache will be stored permanently and will not expire. Additionally, cache entries will be cleared if their TTL is 0 or less. See the related PR for more information.

KeyWritten The event has also been updated based on these changes.

Lock security improvements

Possibility of impact: High

In Laravel 5.7 and earlier versions of Laravel, some cache drivers provide The "atomic lock" feature may cause the lock to be released early due to some unexpected behavior.

For example: Client A acquired a lock foo that expired in 10 seconds. Client A actually takes 20 seconds to complete its task. During Client A task execution, the lock is automatically released by the cache system. Afterwards Client B acquires lock foo. Eventually Client A completed its task and released the lock foo, but inadvertently released the lock held by Client B. At this time Client C can obtain the lock again.

In order to alleviate this situation, the lock is now generated using an embedded "scope token", which ensures that under normal circumstances, only the lock holder can release the lock.

If you are using the lock using the Cache::lock()->get(Closure) method, no changes are required:

Cache::lock('foo', 10)->get(function () {    // 锁将会被安全的自动释放});

However, if To manually call Cache::lock()->release() , you must update your code to maintain an instance of the lock. Then, after completing the task, the release method can be called on the same lock instance. For example:

if (($lock = Cache::lock('foo', 10))->get()) {    // 执行任务…    $lock->release();}

Sometimes you may want to acquire a lock in one process and release it in another process. For example, you could acquire a lock during a web request and want to release the lock when the queued job triggered by that request ends. In this case, you should pass the lock's scope "owner token" to the queued job so that the job can re-instantiate the lock with the given token:

// 在控制器中…$podcast = Podcast::find(1);
if (($lock = Cache::lock('foo', 120))->get()) {
    ProcessPodcast::dispatch($podcast, $lock->owner());}// 在进程广播队列中…
Cache::restoreLock('foo', $this->owner)->release();

If you want to do this without respecting To release a lock without its current owner, you can use the following forceRelease methods:

Cache::lock('foo')->forceRelease();

Repository and Store Contract

Potential Impact: Very Low

In order to fully comply with the requirements of PSR-16, Illuminate\Contracts\Cache\Repository of the contract The return values ​​of the put and forever methods and the put, putMany of the Illuminate\Contracts\Cache\Store contract and forever methods have been changed from void to bool.

Collection

firstWhere Method

Possibility of impact: very low

firstWhere The method parameter has been changed to match the signature of the where method. If you are overriding this method, you should update the method's parameters to match its parent:

/**
 * Get the first item by the given key value pair.
 *
 * @param  string  $key
 * @param  mixed  $operator
 * @param  mixed  $value
 * @return mixed
 */public function firstWhere($key, $operator = null, $value = null);

Terminal

Kernel Contract

Impact Likelihood: Very Low

terminate method has been added to the Illuminate/Contracts/Console/Kernel contract. If you implement this interface, you should add this method to the implementing class.

Container

Generator & Tag Service

Likelihood of Impact: Medium

Container'stagged Method uses a PHP generator to lazily instantiate the service with the given tag. Because of this change, tagged methods return iterable types instead of arrays. If your method uses a type-hinted return value, be sure to change the type hint to iterable as well.

In addition, the tag service can no longer be accessed directly through the array offset value, such as $container->tagged('foo')[0].

resolve Method

Impact likelihood: Very low

resolve Method receives a new boolean Parameter that indicates whether the event should fire/execute during object instantiation (resolution callback). If you override this method, you must update the method signature to match the parent method.

addContextualBinding Method

Possibility of impact: Very low

##Illuminate\Contracts\Container\Container The contract adds the addContextualBinding method. If you want to implement this interface, you should add this method to your implementation.

tagged Method

Impact likelihood: Low
tagged Method now returns iterable instead type instead of array type. If your code parameters have type hints, find all tagged method hints of array type and change the type hint to iterable type.

flush Method

Possibility of impact: Very low

Illuminate\Contracts\Container\Container The contract adds the flush method. If you want to implement this interface, you should add this method to your implementation.

Database

MySQL JSON value not surrounded by quotes

Likelihood of impact: Low

When using MySQL and MariaDB , the JSON value returned by the Query constructor will not be surrounded by quotes. Other databases will behave consistent with this:

$value = DB::table('users')->value('options->language');
dump($value);
// Laravel 5.7...
'"en"'
// Laravel 5.8...
'en'

Therefore, the ->> operator is no longer supported or required.

SQLite

Likelihood of Impact: Moderate

Starting with Laravel 5.8, the earliest version of SQLite supported is SQLite 3.7.11. If you are using an earlier version of SQLite, you should upgrade (it is recommended to upgrade to SQLite 3.8.8).

Eloquent

Irregular plural endings in model names

Likelihood of impact: Moderate

As of Laravel 5.8, included Model names with compound names ending in irregular plurals are now pluralized correctly.

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

If your model name does not correctly use the plural name, you define $table in the model You can still continue to use it after the attribute:

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

Custom relay model with increasing ID

If you define a many-to-many relationship with a custom relay model, Moreover, this relay model has an auto-incremented primary key. You should ensure that this custom relay model class defines an incrementing attribute with a value of true:

/**
 * 标识 ID 是否自增
 *
 * @var bool
 */public $incrementing = true;

loadCount Method

Possibility of impact: Low

Added in base classIlluminate\Database\Eloquent\Model loadCount method. If your application also defines the loadCount method, it may conflict with the one in Eloquent.

originalIsEquivalent Method

Likelihood of Impact: Very Low

Illuminate\Database\Eloquent\Concerns\HasAttributes The originalIsEquivalent member method in the trait has been changed from protected to public.

deleted_at Automatic soft-deletion conversion of attributes

Likelihood of impact: Low

When your Eloquent model uses the Illuminate\Database\Eloquent\SoftDeletes trait, the deleted_at member attribute will now be automatically converted to a Carbon instance. You can override this behavior by writing your custom accessor for the member property or by manually adding it to the casts attribute:

protected $casts = ['deleted_at' => 'string'];

BelongsTo'sgetForeignKey Method

Impact Likelihood: Low

BelongsTo getForeignKey and # in the relationship The ##getQualifiedForeignKey methods have been renamed to getForeignKeyName and getQualifiedForeignKeyName respectively, making the method names consistent with other relationships provided by Laravel.

Event

fire Method

Impact likelihood: Low

The fire method in the Illuminate/Events/Dispatcher class (deprecated in Larevel 5.4) has been removed. You should use its alternative
dispatch .

ExceptionHandler

ExceptionHandler Contract

Likelihood of impact: Low

Illuminate \Contracts\Debug\ExceptionHandler A new shouldReport method has been added to the contract. Now when you implement the exception handler interface, you need to implement this method as well.

renderHttpException Method

Impact likelihood: Low

##Illuminate\Foundation\Exceptions\Handler

The signature of the renderHttpException method in the class has been changed. Now if you override this method in an exception handler, you should change the signature of the method to be consistent with its parent class:

/**
 * 将给定的 Http 异常转换为 Http 响应。
 *
 * @参数 \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface  $e
 * @返回 \Symfony\Component\HttpFoundation\Response
 */protected function renderHttpException(HttpExceptionInterface $e);
Facades

Facade Service Resolution

Possibility of impact: Low

getFacadeAccessor

method can now only return a string representing the service container identity, previously the method would return an object instance. Mail


Markdown file path change

Likelihood of impact: High

If you are already using

The vendor:publish

command publishes Laravel's Markdown email component. You need to rename the /resources/views/vendor/mail/markdown path to text. And the

markdownComponentPaths

method has been renamed to textComponentPaths. If you are overriding this method, you should update the method name to match its parent class.

PendingMail

Change of method parameters in the class

Possibility of impact: very low

The

send, sendNow, queue, later and # in the Illuminate\Mail\PendingMail class The ##fill method has been changed to accept an Illuminate\Contracts\Mail\Mailable instance as parameter instead of an Illuminate\Mail\Mailable instance. If you want to override a method, you need to update its parameters to be consistent with its parent class.

Queue

Pheanstalk 4.0

Likelihood of Impact: Medium

Laravel 5.8 provides support

~4.0 Release version of the Pheanstalk queue. If you are using the Pheanstalk library in your application, please upgrade your library to the ~4.0 release version through Composer.

Job Contract

Possibility of impact: Very low

isReleased, hasFailed The and markAsFailed methods have been added to the Illuminate\Contracts\Queue\Job contract. If you are implementing this interface, you should add these methods to your implementation code.

Job::failed & FailingJob Class

Potential Impact: Very Low

In In Laravel 5.7, when a queue task fails, the queue worker will execute the

FailingJob::handle method. In Laravel 5.8, the logic in the FailingJob class has been migrated to the fail method, which is defined in this task class. Because of this, the fail method is included in the Illuminate\Contracts\Queue\Job contract.

Illuminate\Queue\Jobs\Job The base class contains the implementation of fail, and there is no need to change any code in regular applications. However, if you are building a custom queue driver and have a task class that does not inherit from the task base class provided by Laravel, you should implement it manually in your custom task classfail method. As a reference for implementation, you can check out Laravel's task base class.

This change allows customizing the queue driver to gain more control over the task deletion process.

Redis Blocking Pop

Possibility of impact: Very low

It is now safe to use the "blocking pop" feature of the Redis queue driver. Previously, if the Redis service or worker was offline while retrieving tasks, tasks in the queue might be lost (a small probability event). To make blocking pops safe, a new Redis list will be created for each Laravel queue with the

:notify suffix.

Request

TransformsRequest Middleware

Impact Likelihood: Low

Now, when request input When it is an array, the

Illuminate\Foundation\Http\Middleware\TransformsRequest middleware's transform method will receive the "fully qualified" request input key:

'employee' => [    'name' => 'Taylor Otwell',],/**
    * 转换给定的值.
    *
    * @param  string  $key
    * @param  mixed  $value
    * @return mixed
    */protected function transform($key, $value){    dump($key); // 'employee.name' (Laravel 5.8)    dump($key); // 'name' (Laravel 5.7)}

Route

UrlGenerator Protocol

Possibility of impact: Very low

previous Method has been added to Illuminate\Contracts\Routing\UrlGenerator contract. If you want to call this interface, you should add this method to your implementation.

cachedSchema

Features in Illuminate/Routing/UrlGenerator

Possibility of impact: Very low

## The

$cachedSchema property in #Illuminate/Routing/UrlGenerator (deprecated in Laravel 5.7) has been changed to $cachedScheme.

Sessions

StartSession Middleware

Possibility of impact: Very low

Persistence of Session The logic has been moved from the

terminate() method to the handle() method. If you override methods within them, you should update them to reflect the changes.

Support

Prefer string and array classes over helper functions

Likelihood of impact: Medium

All

array_* and str_* global helper functions are deprecated. You need to use the methods provided by Illuminate\Support\Arr and Illuminate\Support\Str directly.

The impact of this adjustment is marked as medium because these helper functions are moved to the new laravel/helpers extension package for better backward compatibility.

Delayed Service Provider

Impact Likelihood: Medium

Service provider's

defer indicating whether to deferred the provider Boolean properties have been deprecated. Now, if you want to mark a service provider as deferred, you need to implement the Illuminate\Contracts\Support\DeferrableProvider contract.

Testing

PHPUnit 8

Possibility of impact: Optional

By default, Laravel 5.8 uses PHPUnit 7. However, you can upgrade to PHPUnit 8, but this requires PHP >= 7.2. Please read the PHPUnit 8 release announcement for more details.

setUp and tearDown methods now require a void return type:

protected function setUp(): voidprotected function tearDown(): void

Validation

Validator Contract

Possibility of impact: Very low

validated method added in Illuminate\Contracts\Validation\Validator:

/**
 * 获取已验证的属性和值。
 *
 * @return array
 */public function validated();

If you call this interface, you need to add the implementation of this method.

ValidatesAttributes Attributes

Likelihood of Impact: Very Low

##Illuminate\Validation\Concerns\ValidatesAttributes

The visibility of the parseTable, getQueryColumn and requireParameterCount methods in the attribute is adjusted from protected to public.

DatabasePresenceVerifier

Class

Likelihood of Impact: Very Low

Illuminate\Validation\DatabasePresenceVerifier

Class The table method visibility is adjusted from protected to public.

Validator Class

Likelihood of Impact: Very Low

Illuminate\Validation\Validator Class getPresenceVerifierFor method visibility adjusted from protected to public.

Email verification

Impact possibility: very low

Email verification rules now check whether the email address is compatible with RFC5630, so that the verification logic and SwiftMailer remain consistent. In Laravel 5.7, the email rule only verifies that email addresses are RFC822 compliant.

So when using Laravel 5.8, email addresses that were previously considered invalid will now be considered valid, such as (e.g hej@bär.se). Normally, this is considered a bug fix; however, we include it here as a reminder. If you encounter any issues with this change, please let us know.

View

getData Method

Possibility of impact: Very low

Illuminate\Contracts\View A new getData method has been added to the \View contract. If you call this interface, you need to add the implementation of this method.

Notifications

Nexmo / Slack notification channels

Potential impact: High

Nexmo and Slack notification channels have been advanced Official expansion is in progress. To use these channels in your own application, you need to install the following extension packages:

composer require laravel/nexmo-notification-channel
composer require laravel/slack-notification-channel

Others

We also encourage you to check the change log of the laravel/laravel code repository. Although many of these updates are not required, you can keep these files in your application in sync with the code repository. Some of these updates are already mentioned in this upgrade guide, but there are many other minor updates (such as changes to configuration files or annotations) that are not listed. You can see which updates are more important to you through the GitHub comparison tool.

This article was first published on the LearnKu.com website.