Upgrading Laravel
Code written for Laravel 5.8 calls str_slug() and array_get(), which are
Str::slug() and Arr::get() today. The package dresscode/upgrade-laravel holds 179 such
changes to the framework, from version 6 to the current one, from the helpers through Request::get() to the
migration columns that version 11 removed. DressCode fixes over a hundred of them right away, and for the rest it says what to
write instead. And it offers to write models, commands and jobs with attributes, the way Laravel 13 does.
Installation
To upgrade an application that still runs on PHP older than 8.4, install DressCode globally, because DressCode itself needs PHP 8.4 (see Where DressCode Runs):
composer global require dresscode/dresscode dresscode/upgrade-laravel phpstan/phpstan
dresscode upgrade today
upgrade today finds the data and the rewrites of the package on its own, needs no configuration, and leaves the
style of the code as it is. It applies the data only when the project uses laravel/framework, and only for the
versions the project has reached. Upgrading Code describes how to go one major version at a time and what to do with
what is left. A project that already runs on PHP 8.4 to 8.6 can also add the package as a development dependency,
composer require --dev dresscode/upgrade-laravel phpstan/phpstan, and then run
vendor/bin/dresscode upgrade today.
Larastan in the project does no harm, quite the opposite: whether you have it in phpstan.neon or
phpstan/extension-installer registered it, DressCode boots the application the same way PHPStan does and reads the
facade call Request::get() as a method of the class behind it. If bootstrap/app.php fails during that,
Larastan itself prints the message “Application bootstrap failed” together with the exception that stopped the application
from starting, and ends the whole run. Watch out in CI: the run ends with a non-zero exit code, and when it runs in a single
process, that code is 1, the same as when DressCode finds something in the code. No static analysis can resolve an alias from
config/app.php written without a namespace, such as \Request::get(), so such a call goes unnoticed.
What Gets Fixed
Here are a middleware, a provider and a controller written for Laravel 10, in a project on Laravel 13:
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; // Class `Illuminate\Foundation\Http\Middleware\VerifyCsrfToken` is replaced by `Illuminate\Foundation\Http\Middleware\PreventRequestForgery`.
class VerifyCsrfToken extends Middleware // Class `Illuminate\Foundation\Http\Middleware\VerifyCsrfToken` is replaced by `Illuminate\Foundation\Http\Middleware\PreventRequestForgery`.
{
protected $except = ['stripe/*'];
}
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
Schema::useNativeSchemaOperationsIfPossible(); // Static method `Illuminate\Support\Facades\Schema::useNativeSchemaOperationsIfPossible()` is forbidden: there is no replacement; the schema is always changed natively; drop the call.
URL::forceRootUrl(config('app.url')); // Static method `Illuminate\Support\Facades\URL::forceRootUrl()` is replaced by `URL::useOrigin()`.
}
}
class ReportController
{
public function show(Request $request): array
{
$limit = Limit::perMinute(60);
$limit->decayMinutes = 5; // Property `Illuminate\Cache\RateLimiting\Limit::$decayMinutes` is replaced by `$this->decaySeconds = $value * 60`.
return [$request->get('day'), Schema::getAllTables()]; // Method `Illuminate\Http\Request::get()` is replaced by `Request::input()`.
// Static method `Illuminate\Support\Facades\Schema::getAllTables()` is forbidden: call `getTables()`, which returns arrays with the name and schema of each table, not rows of the database.
}
}
After dresscode upgrade today:
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery as Middleware;
class VerifyCsrfToken extends Middleware
{
protected $except = ['stripe/*'];
}
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
Schema::useNativeSchemaOperationsIfPossible();
URL::useOrigin(config('app.url'));
}
}
class ReportController
{
public function show(Request $request): array
{
$limit = Limit::perMinute(60);
$limit->decaySeconds = 5 * 60;
return [$request->input('day'), Schema::getAllTables()];
}
}
The minutes were converted to the seconds Laravel 11 stores in the property. Schema::getAllTables() was left
alone: getTables() returns arrays with the name and schema of each table, not rows of the database, and you have to
decide what your code does with them.
Examples of what the package fixes, by the kind of change:
- Laravel 5.8 helpers:
str_slug(),str_limit(),array_get(),studly_case()and 35 others to the methods ofStrandArrwith the same arguments, import included, - renamed classes:
VerifyCsrfTokenandValidateCsrfTokentoPreventRequestForgery, the traitHasVersion7UuidstoHasUuids, the facadeInputtoRequest,ResourcetoJsonResource, the testingTestResponseandAssertto the namespaceIlluminate\Testing; the import,extends,::classandwithoutMiddleware()are all rewritten, - renamed members:
Request::get()toinput(), also through the facade, a job'sdispatchNow()todispatchSync(),forceRootUrl()touseOrigin(), collection methods such ascontainsOneItem()tohasSole(), the propertyQueueBusy::$connectionto$connectionName, and more, - calls of a different shape:
$limit->decayMinutesto seconds,$event->exceptionOccurredto$event->exception !== null, the tests'assertDeleted()toassertModelMissing(), the migration columnsdouble('x', 8, 2)andunsignedDecimal()the way Laravel 11 writes them, and more.
The full list is in the data of the package, in the file upgrading/framework.neon.
DressCode rewrites a helper called without a leading backslash inside a namespace, as is usual in an application, only with
--fix-risky: the namespace could declare a function of the same name. The data leaves str_contains(),
array_first() and array_last() alone, because they are PHP functions now.
Request::get() and input() are not quite the same: get() reads the route
attributes first, then the query, and finally the body of the request; input() does not read the attributes, puts the
body before the query, and takes a key with a dot as a path into an array. Laravel itself recommends input() in place
of the deprecated get(), and DressCode writes it too; read a value that a middleware sets as a route attribute with
$request->attributes->get().
Changes in signatures need no data: a method a contract added, or a return type a child class must declare, DressCode reports and writes from the declarations of the installed version. Adding a return type is a risky fix, because the body of the method may return something else.
What Is Left to You
Where there is no replacement, where the replacement returns something else, or where it depends on the database, DressCode reports the place and says what to write. This covers, for example, Doctrine DBAL, which Laravel 11 dropped, or the spatial columns of migrations:
Method `Illuminate\Database\Connection::getDoctrineSchemaManager()` is forbidden: read the schema by the schema builder, such as `Schema::getTables()`, `getColumns()` or `getIndexes()`.
Method `Illuminate\Database\Schema\Blueprint::point()` is forbidden: call `geometry()` or `geography()` with the subtype, such as `geography($column, 'point')`; the column type it creates depends on the database.
Other places are reported in the same way, for example these:
- mail: the move from Swift Mailer to Symfony Mailer (
getSwiftMessage(),withSwiftMessage(),TransportManager), and the Mandrill and SparkPost drivers the framework no longer has, - tests: model factories written before Laravel 8, including the helper
factory(), and the traitMocksApplicationServices, - queue: a job's
retryAfter(),$retryAfterand$timeoutAt, instead of which the queue readsbackoff(),$backoffand$retryUntil, - database: the constructors of grammars and of
Blueprint, which in Laravel 12 require a connection,withTablePrefix(), the columnfloat()with the parameters$totaland$places, and the traitDetectsDeadlocks, - other: the helper
elixir(), password validation inPasswordBroker, the Rackspace filesystem driver and the traitDetectsApplicationNamespace.
Again, the full list, together with what to write instead, is in the data of the package.
What the framework only marks as deprecated, with a note on the replacement, is often not in the data. With the types, DressCode reports it anyway, and where the annotation names the replacement, it rewrites the code. The data does not capture changes in behavior and configuration at all; you will find those in the Laravel upgrade guide.
Keeping the Old API from Coming Back
To keep the old API from coming back into the code, for example in continuous integration, put the types, the set
deprecations, and the name of the package into the configuration; the name enables its rewrites in the section
laravel (see Upgrading
Code):
typeAnalysis: phpstan
use:
- perCs # your standard
- deprecations
- upgrade-laravel
Models Written the New Way
Laravel 11 reads the casts of a model from the method casts(), Laravel 12.4 recognizes a local scope by the
attribute #[Scope] instead of the prefix scope, and Laravel 13 reads from class attributes what it used
to read from properties, for example #[Table('posts')] instead of protected $table = 'posts'. The old
way keeps working, so this is an offer, not a fix. You get it together with the rest of the package data, with the configuration
of the previous section:
typeAnalysis: phpstan
use:
- perCs # your standard
- deprecations
- upgrade-laravel
class Post extends Model
{
protected $table = 'blog_posts'; // Property `Illuminate\Database\Eloquent\Model::$table` is replaced by the attribute `#[Illuminate\Database\Eloquent\Attributes\Table]`.
public $timestamps = false; // Property `Illuminate\Database\Eloquent\Model::$timestamps` is replaced by the attribute `#[Illuminate\Database\Eloquent\Attributes\WithoutTimestamps]`.
protected $fillable = ['title', 'body']; // Property `Illuminate\Database\Eloquent\Model::$fillable` is replaced by the attribute `#[Illuminate\Database\Eloquent\Attributes\Fillable]`.
protected $casts = ['published_at' => 'datetime']; // Property `Illuminate\Database\Eloquent\Model::$casts` is replaced by the method `casts()`.
public function scopePublished(Builder $query): void // Method `scopePublished()` is replaced by the method `published()` with the attribute `#[Illuminate\Database\Eloquent\Attributes\Scope]`.
{
$query->whereNotNull('published_at');
}
}
After dresscode fix --fix-risky:
#[WithoutTimestamps]
#[Table(name: 'blog_posts')]
#[Fillable(['title', 'body'])]
class Post extends Model
{
protected function casts(): array
{
return ['published_at' => 'datetime'];
}
#[Scope]
protected function published(Builder $query): void
{
$query->whereNotNull('published_at');
}
}
Properties that map to the same attribute class, $table, $primaryKey and $keyType, are
merged into a single #[Table]; the page Upgrading to Laravel 13 lists which
attributes the data knows for models, commands, jobs and other classes. Rewriting the scope is a risky fix, so it needs
--fix-risky: DressCode cannot see a call to scopePublished() by its old name in another file. It makes
the method published() protected, because otherwise the static call Post::published() would not
reach it.
The decision laravel.castsMethod from laravel/framework 11 writes the method
casts(), and laravel.scopeAttribute from 12.4 writes a scope with an attribute. The data itself turns
them on, and the plugin that the name of the package in use enables checks them; if you do not want one of them, turn
it off in the section laravel with the value keep.
What the Package Covers
| what | versions |
|---|---|
helpers str_* and array_* |
6 |
| deprecated and removed API of the framework | 6 to 13 |
| attributes instead of properties | 13 |
casts() instead of $casts |
11 |
#[Scope] instead of the prefix scope |
12.4 |
The package starts with Laravel 6, so it upgrades code written for Laravel 5.8; from there, go one major version at a time, as described in Upgrading Code. It has no data for versions older than 5.8, and the move to 5.8 is yours to do by hand.