1. Примечания к релизу
1.1. Схема версионирования
Laravel и его официальные пакеты придерживаются семантического версионирования. Основные релизы фреймворка выходят ежегодно (примерно в первом квартале), а минорные и патч-релизы могут выпускаться вплоть до еженедельного цикла. Минорные и патч-релизы никогда не должны содержать изменений, нарушающих обратную совместимость.
При указании зависимости на фреймворк Laravel или его компоненты из вашего приложения или пакета всегда
используйте ограничение версии, например, ^11.0
, так как основные релизы Laravel включают изменения,
нарушающие обратную совместимость. Однако мы стремимся к тому, чтобы обновление до нового основного релиза
занимало не более одного дня.
1.1. Именованные аргументы
Именованные аргументы не подпадают под правила обратной совместимости Laravel. Мы можем изменить имена аргументов функций, если это необходимо для улучшения кода Laravel. Поэтому при использовании именованных аргументов для вызова методов Laravel следует соблюдать осторожность и понимать, что имена параметров могут измениться в будущем.
1.2. Политика поддержки
Для всех релизов Laravel исправления ошибок предоставляются в течение 18 месяцев, а обновления безопасности — в течение 2 лет. Для всех дополнительных библиотек, включая Lumen, исправления ошибок предоставляются только для последней основной версии. Кроме того, рекомендуем ознакомиться с версиями баз данных, поддерживаемыми Laravel.
Version | PHP (*) | Release | Bug Fixes Until | Security Fixes Until |
---|---|---|---|---|
9 | 8.0 - 8.2 | February 8th, 2022 | August 8th, 2023 | February 6th, 2024 |
10 | 8.1 - 8.3 | February 14th, 2023 | August 6th, 2024 | February 4th, 2025 |
11 | 8.2 - 8.3 | March 12th, 2024 | September 3rd, 2025 | March 12th, 2026 |
12 | 8.2 - 8.3 | Q1 2025 | Q3 2026 | Q1 2027 |
(*) Supported PHP versions
1.3. Laravel 11
Laravel 11 продолжает улучшения, начатые в Laravel 10.x, внедряя упрощенную структуру приложения, ограничение скорости запросов в расчете на секунду, маршрутизацию для проверки состояния, плавную ротацию ключей шифрования, улучшенное тестирование очередей, транспорт для почты Resend, интеграцию валидатора Prompt, новые команды Artisan и многое другое. Кроме того, представлен Laravel Reverb — официальный масштабируемый сервер WebSocket, который добавляет вашим приложениям мощные возможности для работы в режиме реального времени.
1.3.1. PHP 8.2
Для Laravel 11.x требуется минимальная версия PHP 8.2.
1.3.2. Оптимизированная структура приложения
Оптимизированная структура приложения Laravel была разработана Тейлором Отвеллом и Нуно Мадуро.
Laravel 11 представляет оптимизированную структуру для новых приложений Laravel, не требующую изменений в существующих приложениях. Новая структура предназначена для того, чтобы сделать работу более легкой и современной, сохраняя при этом многие концепции, уже знакомые разработчикам Laravel. Ниже мы обсудим основные особенности новой структуры приложения Laravel.
Файл начальной загрузки приложения
Файл bootstrap/app.php
был обновлен и теперь используется как файл конфигурации приложения с
приоритетом кода. В этом файле вы можете настраивать маршрутизацию, промежуточное ПО, поставщиков сервисов,
обработку исключений и многое другое. Этот файл объединяет различные параметры поведения приложения высокого
уровня, которые ранее были разбросаны по структуре файлов приложения:
return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { // }) ->withExceptions(function (Exceptions $exceptions) { // })->create();
Сервис-провайдеры
Вместо пяти сервис-провайдеров, которые содержались в стандартной структуре приложения Laravel, в Laravel 11
остался только один — AppServiceProvider
. Функциональность прежних сервис-провайдеров была перенесена
в bootstrap/app.php
, обрабатывается автоматически фреймворком или может быть размещена в
AppServiceProvider
вашего приложения.
Например, обнаружение событий теперь включено по умолчанию, что в значительной степени устраняет необходимость в
ручной регистрации событий и их слушателей. Однако, если вам нужно зарегистрировать события вручную, вы можете
сделать это в AppServiceProvider
. Аналогично, привязки моделей к маршрутам или политики авторизации,
которые ранее регистрировались в AuthServiceProvider
, теперь также можно регистрировать в
AppServiceProvider
.
Opt-in API and Broadcast Routing
The api.php
and channels.php
route files are no longer present by default, as
many applications do not require these files. Instead, they may be created using simple Artisan commands:
php artisan install:api php artisan install:broadcasting
Middleware
Previously, new Laravel applications included nine middleware. These middleware performed a variety of tasks such as authenticating requests, trimming input strings, and validating CSRF tokens.
In Laravel 11, these middleware have been moved into the framework itself, so that they do not add bulk
to your application's structure. New methods for customizing the behavior of these middleware have been
added to the framework and may be invoked from your application's bootstrap/app.php
file:
->withMiddleware(function (Middleware $middleware) { $middleware->validateCsrfTokens( except: ['stripe/*'] ); $middleware->web(append: [ EnsureUserIsSubscribed::class, ])})
Since all middleware can be easily customized via your application's bootstrap/app.php
, the
need for a separate HTTP "kernel" class has been eliminated.
Scheduling
Using a new Schedule
facade, scheduled tasks may now be defined directly in your
application's routes/console.php
file, eliminating the need for a separate console "kernel"
class:
use Illuminate\Support\Facades\Schedule; Schedule::command('emails:send')->daily();
Exception Handling
Like routing and middleware, exception handling can now be customized from your application's
bootstrap/app.php
file instead of a separate exception handler class, reducing the overall
number of files included in a new Laravel application:
->withExceptions(function (Exceptions $exceptions) { $exceptions->dontReport(MissedFlightException::class); $exceptions->report(function (InvalidOrderException $e) { // ... });})
Base Controller
Class
The base controller included in new Laravel applications has been simplified. It no longer extends
Laravel's internal Controller
class, and the AuthorizesRequests
and
ValidatesRequests
traits have been removed, as they may be included in your application's
individual controllers if desired:
<?php namespace App\Http\Controllers; abstract class Controller{ //}
Application Defaults
By default, new Laravel applications use SQLite for database storage, as well as the
database
driver for Laravel's session, cache, and queue. This allows you to begin building
your application immediately after creating a new Laravel application, without being required to install
additional software or create additional database migrations.
In addition, over time, the database
drivers for these Laravel services have become robust
enough for production usage in many application contexts; therefore, they provide a sensible, unified
choice for both local and production applications.
Laravel Reverb
Laravel Reverb was developed by Joe Dixon.
Laravel Reverb brings blazing-fast and scalable real-time WebSocket communication directly to your Laravel application, and provides seamless integration with Laravel’s existing suite of event broadcasting tools, such as Laravel Echo.
php artisan reverb:start
In addition, Reverb supports horizontal scaling via Redis's publish / subscribe capabilities, allowing you to distribute your WebSocket traffic across multiple backend Reverb servers all supporting a single, high-demand application.
For more information on Laravel Reverb, please consult the complete Reverb documentation.
Per-Second Rate Limiting
Per-second rate limiting was contributed by Tim MacDonald.
Laravel now supports "per-second" rate limiting for all rate limiters, including those for HTTP requests and queued jobs. Previously, Laravel's rate limiters were limited to "per-minute" granularity:
RateLimiter::for('invoices', function (Request $request) { return Limit::perSecond(1);});
For more information on rate limiting in Laravel, check out the rate limiting documentation.
Health Routing
Health routing was contributed by Taylor Otwell.
New Laravel 11 applications include a health
routing directive, which instructs Laravel to
define a simple health-check endpoint that may be invoked by third-party application health monitoring
services or orchestration systems like Kubernetes. By default, this route is served at /up
:
->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up',)
When HTTP requests are made to this route, Laravel will also dispatch a DiagnosingHealth
event, allowing you to perform additional health checks that are relevant to your application.
Graceful Encryption Key Rotation
Graceful encryption key rotation was contributed by Taylor Otwell.
Since Laravel encrypts all cookies, including your application's session cookie, essentially every request to a Laravel application relies on encryption. However, because of this, rotating your application's encryption key would log all users out of your application. In addition, decrypting data that was encrypted by the previous encryption key becomes impossible.
Laravel 11 allows you to define your application's previous encryption keys as a comma-delimited list via
the APP_PREVIOUS_KEYS
environment variable.
When encrypting values, Laravel will always use the "current" encryption key, which is within the
APP_KEY
environment variable. When decrypting values, Laravel will first try the current key.
If decryption fails using the current key, Laravel will try all previous keys until one of the keys is
able to decrypt the value.
This approach to graceful decryption allows users to keep using your application uninterrupted even if your encryption key is rotated.
For more information on encryption in Laravel, check out the encryption documentation.
Automatic Password Rehashing
Automatic password rehashing was contributed by Stephen Rees-Carter.
Laravel's default password hashing algorithm is bcrypt. The "work factor" for bcrypt hashes can be
adjusted via the config/hashing.php
configuration file or the BCRYPT_ROUNDS
environment variable.
Typically, the bcrypt work factor should be increased over time as CPU / GPU processing power increases. If you increase the bcrypt work factor for your application, Laravel will now gracefully and automatically rehash user passwords as users authenticate with your application.
Prompt Validation
Prompt validator integration was contributed by Andrea Marco Sartori.
Laravel Prompts is a PHP package for adding beautiful and user-friendly forms to your command-line applications, with browser-like features including placeholder text and validation.
Laravel Prompts supports input validation via closures:
$name = text( label: 'What is your name?', validate: fn (string $value) => match (true) { strlen($value) < 3 => 'The name must be at least 3 characters.', strlen($value) > 255 => 'The name must not exceed 255 characters.', default => null });
However, this can become cumbersome when dealing with many inputs or complicated validation scenarios. Therefore, in Laravel 11, you may utilize the full power of Laravel's validator when validating prompt inputs:
$name = text('What is your name?', validate: [ 'name' => 'required|min:3|max:255',]);
Queue Interaction Testing
Queue interaction testing was contributed by Taylor Otwell.
Previously, attempting to test that a queued job was released, deleted, or manually failed was cumbersome
and required the definition of custom queue fakes and stubs. However, in Laravel 11, you may easily test
for these queue interactions using the withFakeQueueInteractions
method:
use App\Jobs\ProcessPodcast; $job = (new ProcessPodcast)->withFakeQueueInteractions(); $job->handle(); $job->assertReleased(delay: 30);
For more information on testing queued jobs, check out the queue documentation.
New Artisan Commands
Class creation Artisan commands were contributed by Taylor Otwell.
New Artisan commands have been added to allow the quick creation of classes, enums, interfaces, and traits:
php artisan make:classphp artisan make:enumphp artisan make:interfacephp artisan make:trait
Model Casts Improvements
Model casts improvements were contributed by Nuno Maduro.
Laravel 11 supports defining your model's casts using a method instead of a property. This allows for streamlined, fluent cast definitions, especially when using casts with arguments:
/** * Get the attributes that should be cast. * * @return array<string, string> */protected function casts(): array{ return [ 'options' => AsCollection::using(OptionCollection::class), // AsEncryptedCollection::using(OptionCollection::class), // AsEnumArrayObject::using(OptionEnum::class), // AsEnumCollection::using(OptionEnum::class), ];}
For more information on attribute casting, review the Eloquent documentation.
The once
Function
The once
helper was contributed by Taylor
Otwell and Nuno Maduro.
The once
helper function executes the given callback and caches the result in memory for the
duration of the request. Any subsequent calls to the once
function with the same callback
will return the previously cached result:
function random(): int{ return once(function () { return random_int(1, 1000); });} random(); // 123random(); // 123 (cached result)random(); // 123 (cached result)
For more information on the once
helper, check out the helpers documentation.
Improved Performance When Testing With In-Memory Databases
Improved in-memory database testing performance was contributed by Anders Jenbo
Laravel 11 offers a significant speed boost when using the :memory:
SQLite database during
testing. To accomplish this, Laravel now maintains a reference to PHP's PDO object and reuses it across
connections, often cutting total test run time in half.
Improved Support for MariaDB
Improved support for MariaDB was contributed by Jonas Staudenmeir and Julius Kiekbusch
Laravel 11 includes improved support for MariaDB. In previous Laravel releases, you could use MariaDB via Laravel's MySQL driver. However, Laravel 11 now includes a dedicated MariaDB driver which provides better defaults for this database system.
For more information on Laravel's database drivers, check out the database documentation.
Проверка баз данных и улучшенные операции со схемами
Improved schema operations and database inspection was contributed by Hafez Divandari
Laravel 11 provides additional database schema operation and inspection methods, including the native modifying, renaming, and dropping of columns. Furthermore, advanced spatial types, non-default schema names, and native schema methods for manipulating tables, views, columns, indexes, and foreign keys are provided:
use Illuminate\Support\Facades\Schema; $tables = Schema::getTables();$views = Schema::getViews();$columns = Schema::getColumns('users');$indexes = Schema::getIndexes('users');$foreignKeys = Schema::getForeignKeys('users');