5.2 to 5.3
Starting from https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0:
- Update
laravel/frameworkto5.3.*incomposer.jsonfile. - Update
symfony/css-selectorandsymfony/dom-crawler3.1.*in require-dev section composer.json. - 5.2 deprecations: https://laravel.com/docs/5.3/upgrade#5.2-deprecations
Illuminate\Contracts\Bus\SelfHandlingcontract; it can be removed from jobs.listsmethod on Collection, query builder, and Eloquent query builder objects renamed topluck.- Implicit controller routes using
Route::controllerdeprecated. get,post, and other route helper functions removed; useRoutefacade instead.databasesession driver from 5.1 has been renamed tolegacy-databaseand will be removed.Str::randomBytesfunction deprecated; userandom_bytesnative PHP function instead.Str::equalsfunction deprecated; usehash_equalsnative PHP function instead.Illuminate\View\Expressiondeprecated in favor ofIlluminate\Support\HtmlString.WincacheStorecache driver removed.
- Remove arguments from the
bootmethod onEventServiceProvider,RouteServiceProvider, andAuthServiceProviderclasses. Convert any calls to the removed arguments to use the equivalent facade instead. For example, instead of calling methods on the$dispatcherargument, you may simply call theEventfacade. Make sure to import any facades used. - The
first,last, andwheremethods on theArrclass, 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:consolecommand renamed tomake: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
sendPasswordResetNotificationmethod of theIlluminate\Auth\Passwords\CanResetPasswordtrait. TheUsermodel must use the newIlluminate\Notifications\Notifiabletrait for password reset emails to be delivered. Don't forget to register theIlluminate\Notifications\NotificationServiceProvider::classin the providers array ofconfig/app.php. AuthorizesResourcestrait has been merged with theAuthorizesRequeststrait; remove theAuthorizesResourcestrait fromapp/Http/Controllers/Controller.php.- Blade custom directive
$expressioncallback 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
BroadcastServiceProviderto yourapp/Providersdirectory; get it here, and then add it to the providers array ofconfig/app.php. Next, add the new broadcasting.php configuration file to the config directory. - When calling the
Cache::extendmethod with a closure,$thiswill be bound to theCacheManagerinstance, enabling the invokation of its methods from within the closure. - Upgrade your
laravel/cashierpackage to the~7.0release, which upgrades a few internal methods for compatibility with Laravel 5.3 and is not a breaking change. - The
first,last, andcontainscollection methods all pass the "value" as the first parameter to their given callback closure, instead of$keybeing passed first. This type of change does more harm than good. - The collection
wheremethod now performs a loose comparison instead of a strict comparison; to perform a strict comparison, use thewhereStrictmethod. 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\Requestclass on your controller method. - Query builder now returns
Illuminate\Support\Collectioninstead of plain arrays, bringing consistency to the returned result types. If you do not want to migrate your query builder results toCollections, instead chain theallmethod to in addition to thegetorpluckmethods to return a plain PHP array and maintaining backwards compatibility. - Eloquent
getRelationmethod no longer throws aBadMethodCallExceptionif the relation can't be loaded, and instead throws anIlluminate\Database\Eloquent\RelationNotFoundExceptionwhich only affects your app if you were manually catching theBadMethodCallException. $morphClassproperty 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$morphClassproperty should migrate toRelation::morphMapin thebootmethod of yourAppServiceProvider.- Eloquent scopes now respect the leading boolean of scope constraints. For example, if are starting with an
orWhereconstraint it will no longer be converted to normal where. If you were leveraging this feature (for example: using multipleorWhereconstraints in a loop) verify that the first condition is a normalwhereto avoid logic issues. If your scopes begin withwhereconstraints no action is required. If unsure, verify your SQL using thetoSqlmethod. JoinClauseclass updated to unify its syntax with query builder and the optional$whereparameter of theonclause has been removed. Add a "where" condition by explicitly using one of thewheremethods offered by the query builder. The operator of theonclause is now validated and can no longer contain invalid values, and the$bindingsproperty was removed. In order to manipulate join bindings directly use theaddBindingmethod.Mcryptremoved in favor of the newer encryption implementation based on OpenSSL. If still using anMcryptbased cipher (defined inconfig/app.php), update the cipher toAES-256-CBCand set your key to a random 32 byte string generated withphp artisan key:generate. If storing encrypted data using theMcryptencrypter, install thelaravel/legacy-encrypterpackage to decrypt your encrypted data and re-encrypt it using the new OpenSSL encrypter.- Base exception handler class requires an
Illuminate\Container\Containerinstance to be passed to its constructor; only affects app if a custom__constructmethod has been defined inapp/Exceptions/Handler.php, in which case pass a container instance into theparent::__constructlike so:parent::__construct(app()); - Add the
unauthenticatedmethod to yourApp\Exceptions\Handlerclass in order to convert authentication exceptions into HTTP responses. Find the newunauthenticatedmethod here: https://github.com/laravel/laravel/blob/5.3/app/Exceptions/Handler.php - Update
canmiddleware in$routeMiddlewareproperty of HTTP kernel to the following class:'can' => \Illuminate\Auth\Middleware\Authorize::class canmiddleware now throws an instance ofIlluminate\Auth\AuthenticationExceptionif 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\SubstituteBindingsto your web middleware group inapp/Http/Kernel.php. - Register a route middleware for binding substitution in the
$routeMiddlewareproperty of your HTTP kernel:'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, and once registered add the'bindings'element to theapimiddleware group array. - For the new Laravel 5.3 driver based notification system register the
Illuminate\Notifications\NotificationServiceProviderin the providers array ofconfig/app.php. Also add'Notification' => Illuminate\Support\Facades\Notification::classto the aliases array ofconfig/app.php. Use theIlluminate\Notifications\Notifiabletrait 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/vendordirectory using thephp artisan vendor:publish --tag=laravel-paginationcommand which will place the views in theresources/views/vendor/paginationdirectory. Thedefault.blade.phpfile is used for the default pagination view; edit this file to modify the pagination HTML. - In your queue configuration rename all
expireconfiguration items toretry_after, and Beanstalk configuration'sttritem should similarly renamed. - Queueing closures no longer supported; instead convert the closure to a class and queue an instance of the class.
Illuminate\Queue\SerializesModelstrait now properly serializes instances ofIlluminate\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
--daemonoption when calling thequeue:workArtisan command; insteadphp artisan queue:workwill run the worker in daemon mode. To process a single job use the--onceoption. - If using the
databasedriver to store queued jobs, drop thejobs_queue_reserved_reserved_at_indexindex then drop thereservedcolumn from thejobstable (it's no longer required when using the database driver). Then add a new compound index on thequeueandreserved_at columns:$table->index(['queue', 'reserved_at']);. - Many job events such as
JobProcessingandJobProcessedno longer contain the$dataproperty; update your application to call$event->job->payload()to get the equivalent data. - Update the signature of the
Queue::failingmethod in yourAppServiceProvider. - If using the
--timeoutoption for queue workers verify that the PHPpcntlextension 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 theIlluminate\Queue\SerializesModelstrait on your job class with the newpushsyntax:Queue::push(new ClassName);. - Previously route parameters registered using
Route::resourcewere 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 usingRoute::resourcewithin aRoute::groupcall that specified aprefix, examine allroutehelper andUrlGenerator::routecalls 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 thenamesoption when callingRoute::resourceto specify a custom name for a given route or add theasoption to your route group. - If a form request's validation fails, an instance of
Illuminate\Validation\ValidationExceptionis now thrown instead of anHttpException, and if manually catching theHttpExceptionthrown by a form request, update your catch blocks to catch theValidationExceptioninstead. - If previously using the
hasmethod to determine if anIlluminate\Support\MessageBaginstance contained any messages, you should use thecountmethod instead because thehasmethod now requires a parameter and only determines if a specific key exists in the message bag. - When validating arrays, booleans, integers, numerics, and strings,
nullis no longer considered valid unless the rule set contains the newnullablerule.
5.3 to 5.4
- Update
laravel/frameworkto5.4.\*incomposer.jsonfile. - Update
phpunit/phpunitto~5.7incomposer.jsonfile. - Delete the
bootstrap/cache/compiled.phpfile as it is no longer used by the framework. - After upgrading packages, run
php artisan view:clearto avoid Blade errors related to the removal ofIlluminate\View\Factory::getFirstLoop()and runphp artisan route:clearto 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
getPolicyFormethod 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
@sectionis automatically escaped. Use the long form style to render unescaped content. - If overriding the
$bootstrappersarray in your HTTP or console kernel, rename theDetectEnvironmententry toLoadEnvironmentVariablesand removeConfigureLogging. - Previously the
\*character was used to define channel name placeholders; change these placeholders to use{foo}style placeholders (like routes). - The
everymethod has been moved to thenthmethod 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
bindorinstancemethods when registering an alias has been removed; instead use thealiasmethod. - Binding classes into the container with leading slashes is no longer supported, instead register your bindings without a leading slash.
- The container's
makemethod no longer accepts a second array of parameters; if you must continue to pass an array of parameters, use themakeWithmethod. - The container's
resolvingandafterResolvingmethod now must be provided a class name or binding key as the first argument to the method. - The
sharemethod has been removed from the container; use thesingletonmethod instead. - If directly referencing
Illuminate\Console\AppNamespaceDetectorTrait, instead referenceIlluminate\Console\DetectsApplicationNamespace. - When passing an array as the first argument to the
orWheremethod the inner conditions now useORbetween 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 theIlluminate\Database\Connection::resolverFormethod in theregistermethod of yourAppServiceProvider. - No longer able to customize the PDO "fetch mode" from configuration files as
PDO::FETCH_OBJis always used. To customize the fetch mode for your application listen for the newIlluminate\Database\Events\StatementPreparedevent. - The
datecast now converts the column to aCarbonobject and calls thestartOfDaymethod on the object. To preserve thetimeportion of the date use thedatetimecast. - 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
belongsToManysetJoinmethod renamed toperformJoin. - The
belongsToManygetRelatedIdsmethod renamed toallRelatedIds. - The
createManymethod of ahasOneorhasManyrelationship now returns a collection object instead of an array. - The
getPlainForeignKeymethod of ahasOneorhasManyrelationship renamedgetForeignKeyName. - Related models will now use the same connection as the parent model.
- Query builder
chunkmethod now requires anorderByclause, and an exception will be thrown if not supplied. The method will automatically apply anorderByclause on the model's primary key if not supplied. - The
Model::createandModel::forceCreatemethods moved to theIlluminate\Database\Eloquent\Builderclass. - If you are currently passing a custom connection name to
hydratemethod now use theonmethod. Model::hydrateRawmethod has been renamed tofromQuery. If passing a custom connection name to this method use theonmethod.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 thewhereKeymethod to dynamically add a condition for the key column you should now usewhere('key', ...)instead.- Calling
factory(User::class, 1)->make()orfactory(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::newPivotmethod signature has been updated to add a new$usingargument.- If manually implementing the
Illuminate\Contracts\Events\Dispatcherinterface in your application rename thefiremethod todispatch. - 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::firingmethod has been removed. - The following events are now object based:
kernel.handledusing theIlluminate\Foundation\Http\Events\RequestHandledclass.locale.changedusing theIlluminate\Foundation\Events\LocaleUpdatedclass.illuminate.logusing the Illuminate\Log\Events\MessageLogged class.
- The
Illuminate\Http\Exception\HttpResponseExceptionhas been renamed toIlluminate\Http\Exceptions\HttpResponseException. Also theIlluminate\Http\Exception\PostTooLargeExceptionhas been renamed tolluminate\Http\Exceptions\PostTooLargeException. - Sending mail using
Class@methodsyntax 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 theMail::queueandMail::latermethods no longer support using closures to configure the mail message. - If using the
failed_jobstable, add anexceptioncolumn to the table:$table->longText('exception')->after('payload'); - If using Redis clusters place your cluster connections inside of a
clustersconfiguration option in the Redis portion ofconfig/database.php: - The class
Illuminate\Foundation\Http\Middleware\VerifyPostSizehas been renamed toIlluminate\Foundation\Http\Middleware\ValidatePostSize. - The middleware method of the
Illuminate\Routing\Routerclass has been renamed toaliasMiddleware(). getUrimethod of theIlluminate\Routing\Routeclass has been removed; use theurimethod instead.getMethodsmethod of theIlluminate\Routing\Routeclass has been removed; use themethodsmethod instead.getParametermethod of theIlluminate\Routing\Routeclass has been removed; use theparametermethod instead.getPathmethod of theIlluminate\Routing\Routeclass has been removed; use theurimethod instead.- Session handlers no longer implement Symfony's
SessionInterface. A newIlluminate\Contracts\Session\Sessioninterface 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 tosetLaravelSession(). - The testing layer has been simplified. To continue using the 5.3 testing layer, install the
laravel/browser-kit-testingpackage. 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 theTestsnamespace to yourcomposer.jsonfile'sautoload-devblock:"psr-4": {"Tests\\": "tests/"} - The test class no longer manually forces
putenv('APP_ENV=testing'); instead theAPP_ENVvariable is loaded from the .env file. - The
Eventfake'sassertFiredmethod should be updated toassertDispatched, and theassertNotFiredmethod should be updated toassertNotDispatched. - The
Mailfake has been simplified for the 5.4 release; instead of using theassertSentTomethod, you should now simply use theassertSentmethod and utilize thehasTo,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
transhelper signature has been updated to remove the unnecessary$domainargument. - The
forceSchemamethod of theIlluminate\Routing\UrlGeneratorclass has been renamed toforceScheme. - Date format validation is now more strict and supports the placeholders present within the documentation for the PHP date function.
- The
addErrormethod has been renamed toaddFailureand thedoReplacementsmethod has been renamed tomakeReplacements.
5.4 to 5.5
- Update
laravel/frameworkto5.5.*incomposer.jsonfile. - 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\Kernelclass: - Any
firemethods present on your Artisan commands should be renamed tohandle. - Due to improvements to PHP op-code caching, the
optimizeArtisan 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
authorizeResourcemethod, the resulting route segment will now be "snake" case, matching the behavior of resource controllers. Auth::basicandAuth::onceBasicnow throw\Symfony\Component\HttpKernel\Exception\UnauthorizedHttpExceptionrather than returning aResponsewhen authentication fails. This still results in a 401 response being sent to the client; however if your application checked the return value ofAuth::basicin order to return a custom response or implement other behavior on authentication failure, you will now need to handle theUnauthorizedHttpException.- The
beforemethod 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
databasecache driver, runphp artisan cache:clearafter upgrading. - New arguments to the
belongsToManymethod Eloquent models. - The
getQualifiedRelatedKeyNamemethod has been renamed togetQualifiedRelatedPivotKeyName. - The
getQualifiedForeignKeyNamemethod has been renamed togetQualifiedForeignPivotKeyName. - If overriding the
ismethod of an Eloquent model, remove theModeltype-hint from the method allowing theismethod to receivenullas an argument. - The
$eventsproperty on your models should be renamed to$dispatchesEvents. - The protected
$parentproperty on theIlluminate\Database\Eloquent\Relations\Pivotclass has been renamed to$pivotParent. - The
BelongsToMany,HasOneOrMany, andMorphOneOrManyclasses'createmethods have been modified to provide a default value for the$attributesargument. Mind the new signatures. - When deleting a "soft deleted" model, the
existsproperty on the model will remaintrue. - When using an alias, the
withCountmethod will no longer automatically append_countonto 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 thedata_gethelper 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
failedValidationmethod of that form request, and throw anHttpResponseExceptioninstance containing your custom response. - The
filesmethod of theIlluminate\Filesystem\Filesystemclass has changed its signature to add the$hiddenargument and now returns an array ofSplFileInfoobjects, similar to theallFilesmethod as opposed to previously returning an array of string path names. - The unused
$dataand$callbackarguments were removed fromIlluminate\Contracts\Mail\MailQueuequeue and later methods. - To dispatch a job that runs immediately and returns a value from the handle method, use the
dispatch_noworBus::dispatchNowmethod. - If overriding the
allmethod of theIlluminate\Http\Requestclass, update your method signature to reflect the new$keysargument. $request->hasmethod will now returntrueeven if the input value is an empty string ornull, and a new$request->filledmethod has been added that provides the previous behavior of thehasmethod.- The
intersectmethod has been removed; you may replicate this behavior usingarray_filteron a call to$request->only. - The
onlymethod will now only return attributes that are actually present in the request payload, and if you would like to preserve the old behavior use theallmethod instead. - The
requesthelper will no longer retrieve nested keys. If needed, you may use theinputmethod of therequestto achieve this behavior:request()->input('filters.date'); - Renamed authentication assertions:
seeIsAuthenticatedrenamed toassertAuthenticateddontSeeIsAuthenticatedrenamed toassertGuestseeIsAuthenticatedAsrenamed toassertAuthenticatedAsseeCredentialsrenamed toassertCredentialsdontSeeCredentialsrenamed toassertInvalidCredentials
- If using the
Mailfake to determine if a mailable was queued during a request, you should now useMail::assertQueuedinstead ofMail::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-autoloaderdirective to theconfigsection of yourcomposer.jsonfile. - The
Illuminate\Translation\LoaderInterfaceinterface has been moved toIlluminate\Contracts\Translation\Loader. - All of the validator's validation methods are now
publicinstead ofprotected. - When allowing the dynamic
__callmethod to share variables with a view, these variables will automatically use "camel" case. - The
@phpblade directive no longer accepts inline tags; instead use the full form of the directive.