5.2 to 5.3
Starting from https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0:
- Update
laravel/framework
to5.3.*
incomposer.json
file. - Update
symfony/css-selector
andsymfony/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 topluck
.- Implicit controller routes using
Route::controller
deprecated. get
,post
, and other route helper functions removed; useRoute
facade instead.database
session driver from 5.1 has been renamed tolegacy-database
and will be removed.Str::randomBytes
function deprecated; userandom_bytes
native PHP function instead.Str::equals
function deprecated; usehash_equals
native PHP function instead.Illuminate\View\Expression
deprecated in favor ofIlluminate\Support\HtmlString
.WincacheStore
cache driver removed.
- Remove arguments from the
boot
method onEventServiceProvider
,RouteServiceProvider
, andAuthServiceProvider
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 theEvent
facade. Make sure to import any facades used. - The
first
,last
, andwhere
methods on theArr
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 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
sendPasswordResetNotification
method of theIlluminate\Auth\Passwords\CanResetPassword
trait. TheUser
model must use the newIlluminate\Notifications\Notifiable
trait for password reset emails to be delivered. Don't forget to register theIlluminate\Notifications\NotificationServiceProvider::class
in the providers array ofconfig/app.php
. AuthorizesResources
trait has been merged with theAuthorizesRequests
trait; remove theAuthorizesResources
trait fromapp/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 yourapp/Providers
directory; 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::extend
method with a closure,$this
will be bound to theCacheManager
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
, andcontains
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 thewhereStrict
method. The 'whereLoosemethod has been removed from the collection class. The
wheremethod also no longer accepts a third parameter to indicate "strictness"; instead use
whereor
whereStrict`. - 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 toCollections
, instead chain theall
method to in addition to theget
orpluck
methods to return a plain PHP array and maintaining backwards compatibility. - Eloquent
getRelation
method no longer throws aBadMethodCallException
if the relation can't be loaded, and instead throws anIlluminate\Database\Eloquent\RelationNotFoundException
which only affects your app if you were manually catching theBadMethodCallException
. $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 toRelation::morphMap
in theboot
method of yourAppServiceProvider
.- 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 multipleorWhere
constraints in a loop) verify that the first condition is a normalwhere
to avoid logic issues. If your scopes begin withwhere
constraints no action is required. If unsure, verify your SQL using thetoSql
method. JoinClause
class updated to unify its syntax with query builder and the optional$where
parameter of theon
clause has been removed. Add a "where" condition by explicitly using one of thewhere
methods offered by the query builder. The operator of theon
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 theaddBinding
method.Mcrypt
removed in favor of the newer encryption implementation based on OpenSSL. If still using anMcrypt
based cipher (defined inconfig/app.php
), update the cipher toAES-256-CBC
and set your key to a random 32 byte string generated withphp artisan key:generate
. If storing encrypted data using theMcrypt
encrypter, install thelaravel/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 inapp/Exceptions/Handler.php
, in which case pass a container instance into theparent::__construct
like so:parent::__construct(app());
- Add the
unauthenticated
method to yourApp\Exceptions\Handler
class in order to convert authentication exceptions into HTTP responses. Find the newunauthenticated
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 ofIlluminate\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 inapp/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 theapi
middleware group array. - For the new Laravel 5.3 driver based notification system register the
Illuminate\Notifications\NotificationServiceProvider
in the providers array ofconfig/app.php
. Also add'Notification' => Illuminate\Support\Facades\Notification::class
to the aliases array ofconfig/app.php
. Use theIlluminate\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 thephp artisan vendor:publish --tag=laravel-pagination
command which will place the views in theresources/views/vendor/pagination
directory. Thedefault.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 toretry_after
, and Beanstalk configuration'sttr
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 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
--daemon
option when calling thequeue:work
Artisan command; insteadphp 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 thejobs_queue_reserved_reserved_at_index
index then drop thereserved
column from thejobs
table (it's no longer required when using the database driver). Then add a new compound index on thequeue
andreserved_at columns
:$table->index(['queue', 'reserved_at']);
. - Many job events such as
JobProcessing
andJobProcessed
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 yourAppServiceProvider
. - If using the
--timeout
option for queue workers verify that the PHPpcntl
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 theIlluminate\Queue\SerializesModels
trait on your job class with the newpush
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 usingRoute::resource
within aRoute::group
call that specified aprefix
, examine allroute
helper andUrlGenerator::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 thenames
option when callingRoute::resource
to specify a custom name for a given route or add theas
option to your route group. - If a form request's validation fails, an instance of
Illuminate\Validation\ValidationException
is now thrown instead of anHttpException
, and if manually catching theHttpException
thrown by a form request, update your catch blocks to catch theValidationException
instead. - If previously using the
has
method to determine if anIlluminate\Support\MessageBag
instance contained any messages, you should use thecount
method instead because thehas
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 newnullable
rule.
5.3 to 5.4
- Update
laravel/framework
to5.4.\*
incomposer.json
file. - Update
phpunit/phpunit
to~5.7
incomposer.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 ofIlluminate\View\Factory::getFirstLoop()
and runphp 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 theDetectEnvironment
entry toLoadEnvironmentVariables
and removeConfigureLogging
. - 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 thenth
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
orinstance
methods when registering an alias has been removed; instead use thealias
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 themakeWith
method. - The container's
resolving
andafterResolving
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 thesingleton
method instead. - If directly referencing
Illuminate\Console\AppNamespaceDetectorTrait
, instead referenceIlluminate\Console\DetectsApplicationNamespace
. - When passing an array as the first argument to the
orWhere
method the inner conditions now useOR
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 theIlluminate\Database\Connection::resolverFor
method in theregister
method of yourAppServiceProvider
. - 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 newIlluminate\Database\Events\StatementPrepared
event. - The
date
cast now converts the column to aCarbon
object and calls thestartOfDay
method on the object. To preserve thetime
portion of the date use thedatetime
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 toperformJoin
. - The
belongsToMany
getRelatedIds
method renamed toallRelatedIds
. - The
createMany
method of ahasOne
orhasMany
relationship now returns a collection object instead of an array. - The
getPlainForeignKey
method of ahasOne
orhasMany
relationship renamedgetForeignKeyName
. - Related models will now use the same connection as the parent model.
- Query builder
chunk
method now requires anorderBy
clause, and an exception will be thrown if not supplied. The method will automatically apply anorderBy
clause on the model's primary key if not supplied. - The
Model::create
andModel::forceCreate
methods moved to theIlluminate\Database\Eloquent\Builder
class. - If you are currently passing a custom connection name to
hydrate
method now use theon
method. Model::hydrateRaw
method has been renamed tofromQuery
. If passing a custom connection name to this method use theon
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 thewhereKey
method 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::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 thefire
method 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::firing
method has been removed. - The following events are now object based:
kernel.handled
using theIlluminate\Foundation\Http\Events\RequestHandled
class.locale.changed
using theIlluminate\Foundation\Events\LocaleUpdated
class.illuminate.log
using the Illuminate\Log\Events\MessageLogged class.
- The
Illuminate\Http\Exception\HttpResponseException
has been renamed toIlluminate\Http\Exceptions\HttpResponseException
. Also theIlluminate\Http\Exception\PostTooLargeException
has been renamed tolluminate\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 theMail::queue
andMail::later
methods no longer support using closures to configure the mail message. - If using the
failed_jobs
table, add anexception
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 ofconfig/database.php
: - The class
Illuminate\Foundation\Http\Middleware\VerifyPostSize
has been renamed toIlluminate\Foundation\Http\Middleware\ValidatePostSize
. - The middleware method of the
Illuminate\Routing\Router
class has been renamed toaliasMiddleware()
. getUri
method of theIlluminate\Routing\Route
class has been removed; use theuri
method instead.getMethods
method of theIlluminate\Routing\Route
class has been removed; use themethods
method instead.getParameter
method of theIlluminate\Routing\Route
class has been removed; use theparameter
method instead.getPath
method of theIlluminate\Routing\Route
class has been removed; use theuri
method instead.- Session handlers no longer implement Symfony's
SessionInterface
. A newIlluminate\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 tosetLaravelSession()
. - 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 theTests
namespace to yourcomposer.json
file'sautoload-dev
block:"psr-4": {"Tests\\": "tests/"}
- The test class no longer manually forces
putenv('APP_ENV=testing')
; instead theAPP_ENV
variable is loaded from the .env file. - The
Event
fake'sassertFired
method should be updated toassertDispatched
, and theassertNotFired
method should be updated toassertNotDispatched
. - The
Mail
fake has been simplified for the 5.4 release; instead of using theassertSentTo
method, you should now simply use theassertSent
method 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
trans
helper signature has been updated to remove the unnecessary$domain
argument. - The
forceSchema
method of theIlluminate\Routing\UrlGenerator
class 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
addError
method has been renamed toaddFailure
and thedoReplacements
method has been renamed tomakeReplacements
.
5.4 to 5.5
- Update
laravel/framework
to5.5.*
incomposer.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 tohandle
. - 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
andAuth::onceBasic
now throw\Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
rather than returning aResponse
when authentication fails. This still results in a 401 response being sent to the client; however if your application checked the return value ofAuth::basic
in order to return a custom response or implement other behavior on authentication failure, you will now need to handle theUnauthorizedHttpException
.- 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, runphp artisan cache:clear
after upgrading. - New arguments to the
belongsToMany
method Eloquent models. - The
getQualifiedRelatedKeyName
method has been renamed togetQualifiedRelatedPivotKeyName
. - The
getQualifiedForeignKeyName
method has been renamed togetQualifiedForeignPivotKeyName
. - If overriding the
is
method of an Eloquent model, remove theModel
type-hint from the method allowing theis
method to receivenull
as an argument. - The
$events
property on your models should be renamed to$dispatchesEvents
. - The protected
$parent
property on theIlluminate\Database\Eloquent\Relations\Pivot
class has been renamed to$pivotParent
. - The
BelongsToMany
,HasOneOrMany
, andMorphOneOrMany
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 remaintrue
. - 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 thedata_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 anHttpResponseException
instance containing your custom response. - The
files
method of theIlluminate\Filesystem\Filesystem
class has changed its signature to add the$hidden
argument and now returns an array ofSplFileInfo
objects, similar to theallFiles
method as opposed to previously returning an array of string path names. - The unused
$data
and$callback
arguments were removed fromIlluminate\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
orBus::dispatchNow
method. - If overriding the
all
method of theIlluminate\Http\Request
class, update your method signature to reflect the new$keys
argument. $request->has
method will now returntrue
even if the input value is an empty string ornull
, and a new$request->filled
method has been added that provides the previous behavior of thehas
method.- The
intersect
method has been removed; you may replicate this behavior usingarray_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 theall
method instead. - The
request
helper will no longer retrieve nested keys. If needed, you may use theinput
method of therequest
to achieve this behavior:request()->input('filters.date');
- Renamed authentication assertions:
seeIsAuthenticated
renamed toassertAuthenticated
dontSeeIsAuthenticated
renamed toassertGuest
seeIsAuthenticatedAs
renamed toassertAuthenticatedAs
seeCredentials
renamed toassertCredentials
dontSeeCredentials
renamed toassertInvalidCredentials
- If using the
Mail
fake to determine if a mailable was queued during a request, you should now useMail::assertQueued
instead 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-autoloader
directive to theconfig
section of yourcomposer.json
file. - The
Illuminate\Translation\LoaderInterface
interface has been moved toIlluminate\Contracts\Translation\Loader
. - All of the validator's validation methods are now
public
instead ofprotected
. - 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.