Posted 2020-08-14 with tags Laravel, Laravel 5.2, Laravel 5.5, web development

5.2 to 5.3

Starting from https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0:

  • Update laravel/framework to 5.3.* in composer.json file.
  • Update symfony/css-selector and symfony/dom-crawler 3.1.* in require-dev section composer.json.
  • 5.2 deprecations: https://laravel.com/docs/5.3/upgrade#5.2-deprecations
    • Illuminate\Contracts\Bus\SelfHandling contract; it can be removed from jobs.
    • lists method on Collection, query builder, and Eloquent query builder objects renamed to pluck.
    • Implicit controller routes using Route::controller deprecated.
    • get, post, and other route helper functions removed; use Route facade instead.
    • database session driver from 5.1 has been renamed to legacy-database and will be removed.
    • Str::randomBytes function deprecated; use random_bytes native PHP function instead.
    • Str::equals function deprecated; use hash_equals native PHP function instead.
    • Illuminate\View\Expression deprecated in favor of Illuminate\Support\HtmlString.
    • WincacheStore cache driver removed.
  • Remove arguments from the boot method on EventServiceProvider, RouteServiceProvider, and AuthServiceProvider classes. Convert any calls to the removed arguments to use the equivalent facade instead. For example, instead of calling methods on the $dispatcher argument, you may simply call the Event facade. Make sure to import any facades used.
  • The first, last, and where methods on the Arr class, in addition to their associated global helper functions, now pass the "value" as the first parameter to the given callback Closure, instead of the "key" being passed first.
  • make:console command renamed to make:command.
  • Default authentication controllers have been split into four smaller controllers, replace with new controllers from GitHub. Ensure Auth::routes() method is called in your routes file in order to register the proper routes for the new authentication controllers. If you had any custom logic in the old controllers, ensure it is re-implemented.
    • https://raw.githubusercontent.com/laravel/laravel/5.3/app/Http/Controllers/Auth/ResetPasswordController.php
    • https://raw.githubusercontent.com/laravel/laravel/5.3/app/Http/Controllers/Auth/RegisterController.php
    • https://raw.githubusercontent.com/laravel/laravel/5.3/app/Http/Controllers/Auth/LoginController.php
    • https://raw.githubusercontent.com/laravel/laravel/5.3/app/Http/Controllers/Auth/ForgotPasswordController.php
  • Password reset emails now use the new Laravel notifications feature. To customize the password reset notification override the sendPasswordResetNotification method of the Illuminate\Auth\Passwords\CanResetPassword trait. The User model must use the new Illuminate\Notifications\Notifiable trait for password reset emails to be delivered. Don't forget to register the Illuminate\Notifications\NotificationServiceProvider::class in the providers array of config/app.php.
  • AuthorizesResources trait has been merged with the AuthorizesRequests trait; remove the AuthorizesResources trait from app/Http/Controllers/Controller.php.
  • Blade custom directive $expression callback outer-most parentheses are no longer included in the expression passed to your directive callback. Review the Blade extension documentation and verify any custom Blade directives still work.
  • Add the new BroadcastServiceProvider to your app/Providers directory; get it here, and then add it to the providers array of config/app.php. Next, add the new broadcasting.php configuration file to the config directory.
  • When calling the Cache::extend method with a closure, $this will be bound to the CacheManager instance, enabling the invokation of its methods from within the closure.
  • Upgrade your laravel/cashier package to the ~7.0 release, which upgrades a few internal methods for compatibility with Laravel 5.3 and is not a breaking change.
  • The first, last, and contains collection methods all pass the "value" as the first parameter to their given callback closure, instead of $key being passed first. This type of change does more harm than good.
  • The collection where method now performs a loose comparison instead of a strict comparison; to perform a strict comparison, use the whereStrict method. The 'whereLoosemethod has been removed from the collection class. Thewheremethod also no longer accepts a third parameter to indicate "strictness"; instead usewhereorwhereStrict`.
  • The "name" key has been added to config/app.php; set it for your application.
  • You can no longer access session variables or the authenticated user in a controller's constructor because the required middleware has not run yet. Instead you may define a closure based middleware directly in your controller's constructor as long as you are using Laravel 5.3.4 or above. You may also access the session data or the authenticated user by type-hinting the Illuminate\Http\Request class on your controller method.
  • Query builder now returns Illuminate\Support\Collection instead of plain arrays, bringing consistency to the returned result types. If you do not want to migrate your query builder results to Collections, instead chain the all method to in addition to the get or pluck methods to return a plain PHP array and maintaining backwards compatibility.
  • Eloquent getRelation method no longer throws a BadMethodCallException if the relation can't be loaded, and instead throws an Illuminate\Database\Eloquent\RelationNotFoundException which only affects your app if you were manually catching the BadMethodCallException.
  • $morphClass property of Eloquent models removed in favor of a "morph map", which provides support for eager loading and resolves bugs with polymorphic relations. Those relying on the $morphClass property should migrate to Relation::morphMap in the boot method of your AppServiceProvider.
  • Eloquent scopes now respect the leading boolean of scope constraints. For example, if are starting with an orWhere constraint it will no longer be converted to normal where. If you were leveraging this feature (for example: using multiple orWhere constraints in a loop) verify that the first condition is a normal where to avoid logic issues. If your scopes begin with where constraints no action is required. If unsure, verify your SQL using the toSql method.
  • JoinClause class updated to unify its syntax with query builder and the optional $where parameter of the on clause has been removed. Add a "where" condition by explicitly using one of the where methods offered by the query builder. The operator of the on clause is now validated and can no longer contain invalid values, and the $bindings property was removed. In order to manipulate join bindings directly use the addBinding method.
  • Mcrypt removed in favor of the newer encryption implementation based on OpenSSL. If still using an Mcrypt based cipher (defined in config/app.php), update the cipher to AES-256-CBC and set your key to a random 32 byte string generated with php artisan key:generate. If storing encrypted data using the Mcrypt encrypter, install the laravel/legacy-encrypter package to decrypt your encrypted data and re-encrypt it using the new OpenSSL encrypter.
  • Base exception handler class requires an Illuminate\Container\Container instance to be passed to its constructor; only affects app if a custom __construct method has been defined in app/Exceptions/Handler.php, in which case pass a container instance into the parent::__construct like so: parent::__construct(app());
  • Add the unauthenticated method to your App\Exceptions\Handler class in order to convert authentication exceptions into HTTP responses. Find the new unauthenticated method here: https://github.com/laravel/laravel/blob/5.3/app/Exceptions/Handler.php
  • Update can middleware in $routeMiddleware property of HTTP kernel to the following class: 'can' => \Illuminate\Auth\Middleware\Authorize::class
  • can middleware now throws an instance of Illuminate\Auth\AuthenticationException if the user is not authenticated. If you were manually catching a different exception type, update your application to catch this exception. This change will not affect most applications.
  • Route model binding is now accomplished using middleware; add the Illuminate\Routing\Middleware\SubstituteBindings to your web middleware group in app/Http/Kernel.php.
  • Register a route middleware for binding substitution in the $routeMiddleware property of your HTTP kernel: 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, and once registered add the 'bindings' element to the api middleware group array.
  • For the new Laravel 5.3 driver based notification system register the Illuminate\Notifications\NotificationServiceProvider in the providers array of config/app.php. Also add 'Notification' => Illuminate\Support\Facades\Notification::class to the aliases array of config/app.php. Use the Illuminate\Notifications\Notifiable trait in order to receive notifications.
  • Customizing the paginator's HTML is now easier; instead of defining a "Presenter" class, define a simple Blade template. Customize the pagination views by exporting them to your resources/views/vendor directory using the php artisan vendor:publish --tag=laravel-pagination command which will place the views in the resources/views/vendor/pagination directory. The default.blade.php file is used for the default pagination view; edit this file to modify the pagination HTML.
  • In your queue configuration rename all expire configuration items to retry_after, and Beanstalk configuration's ttr item should similarly renamed.
  • Queueing closures no longer supported; instead convert the closure to a class and queue an instance of the class.
  • Illuminate\Queue\SerializesModels trait now properly serializes instances of Illuminate\Database\Eloquent\Collection (which is most likely not a breaking change for most applications). If your application is dependent on collections not being re-retrieved from the database by queued jobs, verify that this is not a breaking change.
  • No longer necessary to specify the --daemon option when calling the queue:work Artisan command; instead php artisan queue:work will run the worker in daemon mode. To process a single job use the --once option.
  • If using the database driver to store queued jobs, drop the jobs_queue_reserved_reserved_at_index index then drop the reserved column from the jobs table (it's no longer required when using the database driver). Then add a new compound index on the queue and reserved_at columns: $table->index(['queue', 'reserved_at']);.
  • Many job events such as JobProcessing and JobProcessed no longer contain the $data property; update your application to call $event->job->payload() to get the equivalent data.
  • Update the signature of the Queue::failing method in your AppServiceProvider.
  • If using the --timeout option for queue workers verify that the PHP pcntl extension is installed.
  • If queueing jobs using the old Queue::push('ClassName@method'); syntax, Eloquent models will no longer be automatically serialized and re-retrieved by the queue. To automatically serialize your Eloquent models for a given job, use the Illuminate\Queue\SerializesModels trait on your job class with the new push syntax: Queue::push(new ClassName);.
  • Previously route parameters registered using Route::resource were not "singularized", which could lead to unexpected behavior when registering route model bindings. In Laravel 5.3, all resource route parameters are singularized by default.
  • URL prefixes no longer affect the route names assigned to routes when using Route::resource, since this behavior defeated the purpose of using route names. If using Route::resource within a Route::group call that specified a prefix, examine all route helper and UrlGenerator::route calls to verify that this URI prefix is no longer appended to the route name. If this change causes you to have two routes with the same name, you have two options. First, you may use the names option when calling Route::resource to specify a custom name for a given route or add the as option to your route group.
  • If a form request's validation fails, an instance of Illuminate\Validation\ValidationException is now thrown instead of an HttpException, and if manually catching the HttpException thrown by a form request, update your catch blocks to catch the ValidationException instead.
  • If previously using the has method to determine if an Illuminate\Support\MessageBag instance contained any messages, you should use the count method instead because the has method now requires a parameter and only determines if a specific key exists in the message bag.
  • When validating arrays, booleans, integers, numerics, and strings, null is no longer considered valid unless the rule set contains the new nullablerule.

5.3 to 5.4

  • Update laravel/framework to 5.4.\* in composer.json file.
  • Update phpunit/phpunit to ~5.7 in composer.json file.
  • Delete the bootstrap/cache/compiled.php file as it is no longer used by the framework.
  • After upgrading packages, run php artisan view:clear to avoid Blade errors related to the removal of Illuminate\View\Factory::getFirstLoop() and run php artisan route:clear to flush the route cache.
  • Laravel Passport 2.0.0 has been released to provide compatibility with Laravel 5.4 and the Axios JavaScript library; if upgrading from Laravel 5.3 and using the pre-built Passport Vue components make sure the Axios library is globally available to your application as axios.
  • Laravel Scout 3.0.0 has been released to provide compatibility with Laravel 5.4.
  • Laravel Socialite 3.0.0 has been released to provide compatibility with Laravel 5.4.
  • Laravel 5.4 requires Guzzle 6.0 or greater.
  • The getPolicyFor method now returns null if no policy is found for the given class. If calling this method directly check for a null response.
  • Inline Blade content passed to a @section is automatically escaped. Use the long form style to render unescaped content.
  • If overriding the $bootstrappers array in your HTTP or console kernel, rename the DetectEnvironment entry to LoadEnvironmentVariables and remove ConfigureLogging.
  • Previously the \* character was used to define channel name placeholders; change these placeholders to use {foo} style placeholders (like routes).
  • The every method has been moved to the nth method to match the method name defined by Lodash.
  • $collection->random(1) now returns a new collection instance with one item whereas previously this would return a single object. A single object will only be returned if no arguments are supplied.
  • The ability to pass an array as the first parameter of the bind or instance methods when registering an alias has been removed; instead use the alias method.
  • Binding classes into the container with leading slashes is no longer supported, instead register your bindings without a leading slash.
  • The container's make method no longer accepts a second array of parameters; if you must continue to pass an array of parameters, use the makeWith method.
  • The container's resolving and afterResolving method now must be provided a class name or binding key as the first argument to the method.
  • The share method has been removed from the container; use the singleton method instead.
  • If directly referencing Illuminate\Console\AppNamespaceDetectorTrait, instead reference Illuminate\Console\DetectsApplicationNamespace.
  • When passing an array as the first argument to the orWhere method the inner conditions now use OR between each array element.
  • If previously binding a service container binding for a db.connection.{driver} key in order to resolve a custom database connection, you should now use the Illuminate\Database\Connection::resolverFor method in the register method of your AppServiceProvider.
  • No longer able to customize the PDO "fetch mode" from configuration files as PDO::FETCH_OBJ is always used. To customize the fetch mode for your application listen for the new Illuminate\Database\Events\StatementPrepared event.
  • The date cast now converts the column to a Carbon object and calls the startOfDay method on the object. To preserve the timeportion of the date use the datetime cast.
  • If a foreign key is not explicitly specified when defining a relationship, Eloquent will now use the table name and primary key name for the related model to build the foreign key.
  • The belongsToMany setJoin method renamed to performJoin.
  • The belongsToMany getRelatedIds method renamed to allRelatedIds.
  • The createMany method of a hasOne or hasMany relationship now returns a collection object instead of an array.
  • The getPlainForeignKey method of a hasOne or hasMany relationship renamed getForeignKeyName.
  • Related models will now use the same connection as the parent model.
  • Query builder chunk method now requires an orderBy clause, and an exception will be thrown if not supplied. The method will automatically apply an orderBy clause on the model's primary key if not supplied.
  • The Model::create and Model::forceCreate methods moved to the Illuminate\Database\Eloquent\Builder class.
  • If you are currently passing a custom connection name to hydrate method now use the on method.
  • Model::hydrateRaw method has been renamed to fromQuery. If passing a custom connection name to this method use the on method.
  • whereKey($id) method will now add a "where" clause for the given primary key value. Previously this would fall into the dynamic "where" clause builder and add a "where" clause for the "key" column. If you used the whereKey method to dynamically add a condition for the key column you should now use where('key', ...) instead.
  • Calling factory(User::class, 1)->make() or factory(User::class, 1)->create() will now return a collection with one item instead of returning a single model and will only return a single model if the amount is not supplied.
  • Model::newPivot method signature has been updated to add a new $using argument.
  • If manually implementing the Illuminate\Contracts\Events\Dispatcher interface in your application rename the fire method to dispatch.
  • Support for event handler "priorities" has been removed.
  • Wildcard event handlers now receive the event name as their first argument and the array of event data as their second argument and the Event::firing method has been removed.
  • The following events are now object based:
    • kernel.handled using the Illuminate\Foundation\Http\Events\RequestHandled class.
    • locale.changed using the Illuminate\Foundation\Events\LocaleUpdated class.
    • illuminate.log using the Illuminate\Log\Events\MessageLogged class.
  • The Illuminate\Http\Exception\HttpResponseException has been renamed to Illuminate\Http\Exceptions\HttpResponseException. Also the Illuminate\Http\Exception\PostTooLargeException has been renamed to lluminate\Http\Exceptions\PostTooLargeException.
  • Sending mail using Class@method syntax is no longer supported.
  • To provide support for 5.4's new Markdown mail components add the following block of configuration to the bottom of config/mail.php (see here for details.
  • To queue mail you now must use a mailable. Queuing mail using the Mail::queue and Mail::later methods no longer support using closures to configure the mail message.
  • If using the failed_jobs table, add an exception column to the table: $table->longText('exception')->after('payload');
  • If using Redis clusters place your cluster connections inside of a clusters configuration option in the Redis portion of config/database.php:
  • The class Illuminate\Foundation\Http\Middleware\VerifyPostSize has been renamed to Illuminate\Foundation\Http\Middleware\ValidatePostSize.
  • The middleware method of the Illuminate\Routing\Router class has been renamed to aliasMiddleware().
  • getUri method of the Illuminate\Routing\Route class has been removed; use the uri method instead.
  • getMethods method of the Illuminate\Routing\Route class has been removed; use the methods method instead.
  • getParameter method of the Illuminate\Routing\Route class has been removed; use the parameter method instead.
  • getPath method of the Illuminate\Routing\Route class has been removed; use the uri method instead.
  • Session handlers no longer implement Symfony's SessionInterface. A new Illuminate\Contracts\Session\Session interface has been defined and used instead. The following code changes should also be applied: All calls to the ->set() method should be changed to ->put(). All calls to the ->getToken() method should be changed to ->token(). All calls to the $request->setSession() method should be changed to setLaravelSession().
  • The testing layer has been simplified. To continue using the 5.3 testing layer, install the laravel/browser-kit-testing package. You can run the 5.4 testing layer side-by-side with the Laravel 5.3 testing layer. To autoload any new tests you generate using the 5.4 test generators, add the Tests namespace to your composer.json file's autoload-dev block: "psr-4": {"Tests\\": "tests/"}
  • The test class no longer manually forces putenv('APP_ENV=testing'); instead the APP_ENV variable is loaded from the .env file.
  • The Event fake's assertFired method should be updated to assertDispatched, and the assertNotFired method should be updated to assertNotDispatched.
  • The Mail fake has been simplified for the 5.4 release; instead of using the assertSentTo method, you should now simply use the assertSent method and utilize the hasTo, hasCc, etc. helper methods within your callback.
  • If using the {Inf} placeholder for pluralizing translation strings, update translation strings to use the * character instead.
  • The trans helper signature has been updated to remove the unnecessary $domain argument.
  • The forceSchema method of the Illuminate\Routing\UrlGenerator class has been renamed to forceScheme.
  • Date format validation is now more strict and supports the placeholders present within the documentation for the PHP date function.
  • The addError method has been renamed to addFailure and the doReplacements method has been renamed to makeReplacements.

5.4 to 5.5

  • Update laravel/framework to 5.5.* in composer.json file.
  • Laravel Dusk 2.0.0 has been released to provide compatibility with Laravel 5.5 and headless Chrome testing.
  • The Pusher event broadcasting driver now requires version ~3.0 of the Pusher SDK.
  • Laravel 5.5 requires version ~6.0 of Swift Mailer.
  • Artisan can now automatically discover commands so that you do not have to manually register them in the kernel. To enable, add the following line to the commands method of your App\Console\Kernel class:
  • Any fire methods present on your Artisan commands should be renamed to handle.
  • Due to improvements to PHP op-code caching, the optimize Artisan command is no longer needed. Remove any references to this command from your deployment scripts as it will be removed.
  • When passing a multi-word model name to the authorizeResource method, the resulting route segment will now be "snake" case, matching the behavior of resource controllers.
  • Auth::basic and Auth::onceBasic now throw \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException rather than returning a Response when authentication fails. This still results in a 401 response being sent to the client; however if your application checked the return value of Auth::basic in order to return a custom response or implement other behavior on authentication failure, you will now need to handle the UnauthorizedHttpException.
  • The before method of a policy class will not be called if the class doesn't contain a method matching the name of the ability being checked.
  • If using the database cache driver, run php artisan cache:clear after upgrading.
  • New arguments to the belongsToMany method Eloquent models.
  • The getQualifiedRelatedKeyName method has been renamed to getQualifiedRelatedPivotKeyName.
  • The getQualifiedForeignKeyName method has been renamed to getQualifiedForeignPivotKeyName.
  • If overriding the is method of an Eloquent model, remove the Model type-hint from the method allowing the is method to receive null as an argument.
  • The $events property on your models should be renamed to $dispatchesEvents.
  • The protected $parent property on the Illuminate\Database\Eloquent\Relations\Pivot class has been renamed to $pivotParent.
  • The BelongsToMany, HasOneOrMany, and MorphOneOrMany classes' create methods have been modified to provide a default value for the $attributes argument. Mind the new signatures.
  • When deleting a "soft deleted" model, the exists property on the model will remain true.
  • When using an alias, the withCount method will no longer automatically append _count onto the resulting column name.
  • To prevent accessing a model's private properties when using array access, it's no longer possible to have a model method with the same name as an attribute or property, and doing so will cause exceptions to be thrown when accessing the model's attributes via array access ($user['name']) or the data_get helper function.
  • All exceptions now, including validation exceptions, are converted into HTTP responses by the exception handler, and the default format for JSON validation errors has changed.
  • JSON authentication failures return the error messages following a new formatting convention.
  • If previously customizing the response format of an individual form request, now override the failedValidation method of that form request, and throw an HttpResponseException instance containing your custom response.
  • The files method of the Illuminate\Filesystem\Filesystem class has changed its signature to add the $hidden argument and now returns an array of SplFileInfo objects, similar to the allFiles method as opposed to previously returning an array of string path names.
  • The unused $data and $callback arguments were removed from Illuminate\Contracts\Mail\MailQueue queue and later methods.
  • To dispatch a job that runs immediately and returns a value from the handle method, use the dispatch_now or Bus::dispatchNow method.
  • If overriding the all method of the Illuminate\Http\Request class, update your method signature to reflect the new $keys argument.
  • $request->has method will now return true even if the input value is an empty string or null, and a new $request->filled method has been added that provides the previous behavior of the has method.
  • The intersect method has been removed; you may replicate this behavior using array_filter on a call to $request->only.
  • The only method will now only return attributes that are actually present in the request payload, and if you would like to preserve the old behavior use the all method instead.
  • The request helper will no longer retrieve nested keys. If needed, you may use the input method of the request to achieve this behavior: request()->input('filters.date');
  • Renamed authentication assertions:
    • seeIsAuthenticated renamed to assertAuthenticated
    • dontSeeIsAuthenticated renamed to assertGuest
    • seeIsAuthenticatedAs renamed to assertAuthenticatedAs
    • seeCredentials renamed to assertCredentials
    • dontSeeCredentials renamed to assertInvalidCredentials
  • If using the Mail fake to determine if a mailable was queued during a request, you should now use Mail::assertQueued instead of Mail::assertSent. This distinction allows you to specifically assert that the mail was queued for background sending and not sent during the request itself.
  • Tinker now supports omitting namespaces when referring to your application classes, which requires an optimized Composer class-map, so add the optimize-autoloader directive to the config section of your composer.json file.
  • The Illuminate\Translation\LoaderInterface interface has been moved to Illuminate\Contracts\Translation\Loader.
  • All of the validator's validation methods are now public instead of protected.
  • When allowing the dynamic __call method to share variables with a view, these variables will automatically use "camel" case.
  • The @php blade directive no longer accepts inline tags; instead use the full form of the directive.