Created
November 4, 2024 20:18
-
-
Save StuMason/3203b61bf78a9e6d055c9fd40612d22b to your computer and use it in GitHub Desktop.
LLMs aren't upto date with the latest Laravel features. This is a condensed version of all new features from Laravel 10 to 11, for LLM Context use (Claude Projects, for example)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
LARAVEL 11 - NEW FEATURES AND CHANGES | |
=== artisan === | |
- **Isolatable Commands**: Implement the `Illuminate\Contracts\Console\Isolatable` interface to ensure only one instance of a command runs at a time. An `--isolated` option is added to the command for this purpose. | |
- **Lock ID**: Customize the atomic lock key by defining an `isolatableId` method in the command class. | |
- **Lock Expiration Time**: Adjust the expiration time of isolation locks by defining an `isolationLockExpiresAt` method in the command class. | |
- **Prompts for Missing Input**: Implement the `PromptsForMissingInput` interface to automatically prompt users for required arguments that are missing. | |
- **Custom Prompt Questions**: Use the `promptForMissingArgumentsUsing` method to customize questions for missing arguments. | |
- **After Prompting for Missing Arguments**: Implement the `afterPromptingForMissingArguments` method to handle additional input prompts after missing arguments are gathered. | |
- **Tinker Command Allow List**: Modify the `commands` array in the `tinker.php` configuration file to allow additional Artisan commands in Tinker. | |
- **Classes That Should Not Be Aliased**: List classes in the `dont_alias` array of the `tinker.php` configuration file to prevent them from being automatically aliased in Tinker. | |
=== authentication === | |
- Laravel 11 introduces the ability to define custom authentication guards using the `extend` method on the `Auth` facade within a service provider. | |
- The `Auth::viaRequest` method allows for a simpler implementation of custom HTTP request-based authentication systems using a closure. | |
- Laravel 11 provides the `logoutOtherDevices` method, which invalidates sessions on other devices while keeping the current session authenticated. | |
- The `password_timeout` configuration value can be adjusted in `config/auth.php` to change the duration before a user is prompted to confirm their password again. | |
- Automatic password rehashing can be disabled in Laravel 11 by publishing the `hashing` configuration file and setting `rehash_on_login` to `false`. | |
=== authorization === | |
- **Policy Discovery**: Laravel 11 introduces a custom policy discovery callback using the `Gate::guessPolicyNamesUsing` method, allowing developers to define their own logic for discovering policy names based on model classes. | |
- **Customizing HTTP Response Status**: In Laravel 11, you can customize the HTTP status code returned for a failed authorization check using the `denyWithStatus` method on the `Illuminate\Auth\Access\Response` class, and the `denyAsNotFound` method is provided for convenience. | |
- **Inline Authorization**: The `Gate::allowIf` and `Gate::denyIf` methods for inline authorization checks do not execute any defined "before" or "after" authorization hooks, providing a more straightforward way to check permissions without additional overhead. | |
- **Authorization & Inertia**: Laravel 11 includes a `HandleInertiaRequests` middleware that allows sharing authorization data with Inertia-powered frontends, enabling the frontend to render UI based on user permissions. | |
- **Warning**: The `before` method of a policy class will not be called if the class doesn't contain a method with a name matching the ability being checked. | |
=== billing === | |
- Cashier 15 utilizes Stripe API version `2023-10-16`. The Stripe API version will be updated on minor releases to utilize new Stripe features. | |
- To enable automatic tax calculation, invoke the `calculateTaxes` method in the `boot` method of your application's `App\Providers\AppServiceProvider` class. | |
- The `CASHIER_CURRENCY_LOCALE` environment variable can now be set to specify a locale for formatting money values on invoices. | |
- The `CASHIER_LOGGER` environment variable allows specification of the log channel for logging fatal Stripe errors. | |
- The `updateDefaultPaymentMethodFromStripe` method syncs default payment method information with Stripe. | |
- The `syncStripeCustomerDetails` method can be invoked within an event listener to automatically sync customer information with Stripe upon updates. | |
- The `syncTaxRates` method allows updating tax rates for existing subscriptions based on the new `taxRates` values. | |
- The `anchorBillingCycleOn` method can be used to modify the billing anchor date during subscription creation. | |
- The `CASHIER_PAYMENT_NOTIFICATION` environment variable can be set to enable notifications for off-session payment confirmations. | |
- The `checkoutCharge` method creates a new product and price in Stripe for ad-hoc charges; it is recommended to create products upfront in Stripe. | |
- The `collectTaxIds` method can be invoked to enable collection of a customer's Tax ID during checkout sessions. | |
- The `CASHIER_WEBHOOK_SECRET` environment variable must be defined to enable webhook signature verification. | |
- The `withPaymentConfirmationOptions` method allows providing additional data required for confirming payments with certain payment methods. | |
=== blade === | |
- Blade now includes the `@class` directive for conditionally compiling CSS class strings. | |
- The `@style` directive has been introduced for conditionally adding inline CSS styles to HTML elements. | |
- New directives: `@checked`, `@selected`, `@disabled`, `@readonly`, and `@required` for easily indicating states of form elements. | |
- The `@once` directive can now be used in conjunction with `@pushOnce` and `@prependOnce` for better management of script inclusions. | |
- The `@use` directive allows for importing classes directly within Blade templates. | |
- Anonymous components can now be defined within their respective directories, allowing for a cleaner structure. | |
- The `@aware` directive allows child components to access data from parent components. | |
- The `@props` directive can be used in anonymous components to specify data properties and default values. | |
- The `anonymousComponentPath` method allows for registering additional paths for anonymous components. | |
- The `fragment` and `fragmentIf` methods enable returning specific fragments of views in HTTP responses. | |
- The `@inject` directive now supports a more streamlined way to retrieve services from the service container. | |
- The `Blade::stringable` method allows for registering custom echo handlers for specific object types. | |
- The `Blade::if` method provides a way to define custom conditional directives easily. | |
=== broadcasting === | |
- Laravel 11 introduces the `ShouldDispatchAfterCommit` interface, allowing events to be dispatched after all open database transactions have been committed. | |
- The `broadcastOn` method in model broadcasting now receives an `$event` argument, indicating the type of event that has occurred (e.g., `created`, `updated`, `deleted`). | |
- The `broadcastWith` method can now be defined in model broadcasting to customize the broadcast payload based on the event type. | |
- The `broadcastAs` method can also be defined in model broadcasting to customize the broadcast name based on the event type. | |
- Laravel Echo `reverb` broadcaster requires `laravel-echo` version 1.16.0 or higher. | |
- The `toOthers` method requires the event to use the `Illuminate\Broadcasting\InteractsWithSockets` trait. | |
- The `broadcast` helper can now be used to send anonymous events without creating a dedicated event class. | |
- The `broadcastOn` method in model broadcasting can return Eloquent model instances directly, which Laravel will convert to private channel instances automatically. | |
- The `broadcast` method can now be used with `sendNow` for immediate broadcasting of events. | |
=== cache === | |
- **Stale While Revalidate**: Introduced `Cache::flexible` method to implement the "stale-while-revalidate" pattern, allowing partially stale data to be served while recalculating the cached value in the background. | |
- **Atomic Locks**: | |
- New ability to manage locks across processes using the lock's scoped "owner token" to restore and release locks in different processes. | |
- Introduced `forceRelease` method to release a lock without respecting its current owner. | |
- **Custom Cache Drivers**: | |
- New requirement to register custom cache drivers within a `booting` callback to ensure proper registration timing relative to service providers. | |
- **Cache Events**: | |
- Introduced the ability to disable cache events for performance by setting the `events` configuration option to `false` for a given cache store. | |
=== cashier-paddle === | |
- Cashier Paddle 2.x's integration with Paddle Billing is introduced in Laravel 11. If using Paddle Classic, you must use Cashier Paddle 1.x. | |
- The `PADDLE_RETAIN_KEY` is optional and should only be set if you're using Paddle with Retain. | |
- The `CASHIER_CURRENCY_LOCALE` environment variable can now be set to specify a locale for formatting money values for display on invoices. | |
- The `keepPastDueSubscriptionsActive` method can be called in the `register` method of your `AppServiceProvider` to keep subscriptions active even when they are `past_due`. | |
- The `paddle-button` Blade component is included with Cashier Paddle for easier integration. | |
- You can now provide an array of custom data to the `checkout` method when redirecting customers to Paddle's Checkout Overlay. | |
- The `previewPrices` method allows you to retrieve prices based on the customer's IP address or a specific country. | |
- The `paddleName` and `paddleEmail` methods can be overridden in your billable model to set defaults for customer information during checkout sessions. | |
- The `createAsCustomer` method allows creating a Paddle customer without starting a subscription. | |
- The `subscription()->charge` method allows for single charges on subscriptions, with an option to immediately invoice using `chargeAndInvoice`. | |
- Paddle's webhook handling now includes the ability to listen for additional events dispatched by Cashier. | |
- The `refund` method on a `Cashier\Paddle\Transaction` model allows for partial refunds of specific price IDs. | |
- New methods for managing subscriptions include `pauseNow`, `pauseUntil`, and `pauseNowUntil` for more flexible subscription management. | |
- The `onPausedGracePeriod` method allows checking if a user is on a grace period after pausing a subscription. | |
- The `stopCancelation` method allows stopping the cancellation of a subscription during its grace period. | |
- The `activate` method can be used to immediately activate a subscription after a trial period. | |
- The `extendTrial` method allows extending an existing trial period on a subscription. | |
- The `CASHIER_WEBHOOK` environment variable can be defined to override the default webhook route. | |
- The `PADDLE_WEBHOOK_SECRET` environment variable must be defined for webhook verification. | |
=== collections === | |
- `ensure()` method verifies that all elements of a collection are of a specified type or list of types, throwing an `UnexpectedValueException` if not. | |
- `takeUntilTimeout()` method in `LazyCollection` returns a new lazy collection that enumerates values until a specified time. | |
- `tapEach()` method in `LazyCollection` calls the given callback as items are pulled out one by one, unlike `each` which calls it immediately. | |
- `throttle()` method in `LazyCollection` throttles the lazy collection so that each value is returned after a specified number of seconds, useful for rate-limited API interactions. | |
- `remember()` method in `LazyCollection` remembers values that have already been enumerated, preventing retrieval on subsequent enumerations. | |
=== concurrency === | |
- Laravel's `Concurrency` facade is currently in beta. | |
- If upgrading from Laravel 10.x to 11.x, add `ConcurrencyServiceProvider` to the `providers` array in `config/app.php`. | |
- The `Concurrency` facade supports three drivers: `process`, `fork`, and `sync`. The `fork` driver requires the installation of the `spatie/fork` package. | |
- To change the default concurrency driver, publish the `concurrency` configuration file via `php artisan config:publish concurrency` and update the `default` option in the file. | |
- The `defer` method allows executing closures concurrently after the HTTP response has been sent, without waiting for results. | |
=== configuration === | |
- The `about` Artisan command now provides an overview of your application's configuration, drivers, and environment. | |
- The `config:show` Artisan command allows exploration of specific configuration file values in detail. | |
- New `Config` facade methods for typed configuration retrieval: `Config::string()`, `Config::integer()`, `Config::float()`, `Config::boolean()`, `Config::array()`. | |
- The `config:publish` Artisan command is introduced to publish any configuration files that are not published by default. | |
- The `env:encrypt` command encrypts the `.env` file and creates an `.env.encrypted` file, with the decryption key outputted for secure storage. | |
- The `env:decrypt` command decrypts the `.env.encrypted` file back to `.env`, with options for specifying the encryption key and cipher. | |
- Maintenance mode can now utilize a cache-based method for handling maintenance status across multiple servers. | |
- Pre-rendering of the maintenance mode view is introduced, allowing a specific template to be rendered at the start of the request cycle. | |
- The `--redirect` option for the `down` command allows redirection of all requests to a specific URL during maintenance mode. | |
=== console-tests === | |
- `expectsSearch` assertion introduced to mock user input, search results, and selection for commands using Laravel Prompts. | |
- `WithConsoleEvents` trait added to enable dispatching `CommandStarting` and `CommandFinished` events during tests. | |
=== container === | |
- **Contextual Attributes**: New attributes available for dependency injection include `Storage`, `Auth`, `Cache`, `Config`, `DB`, `Log`, `RouteParameter`, `Tag`, and `CurrentUser`. | |
- **Defining Custom Attributes**: You can create custom contextual attributes by implementing the `Illuminate\Contracts\Container\ContextualAttribute` contract. | |
- **Binding Typed Variadics**: You can now use contextual binding to inject an array of typed objects using variadic constructor arguments. | |
- **Variadic Tag Dependencies**: New method to inject all tagged instances for a variadic dependency using `needs` and `giveTagged`. | |
- **Rebinding Method**: New `rebinding` method allows you to listen for when a service is re-bound to the container. | |
- **PSR-11 Compliance**: Laravel's service container implements the PSR-11 interface, allowing type-hinting of the PSR-11 container interface to obtain an instance of the Laravel container. | |
=== context === | |
- Context now supports the ability to store "hidden" data, which is not appended to logs and is accessed via a different set of methods. | |
- New methods for hidden context: `addHidden`, `getHidden`, `addHiddenIf`, `pushHidden`, `pullHidden`, `onlyHidden`, `allHidden`, `hasHidden`, `forgetHidden`. | |
- The `dehydrating` event allows you to register a closure that modifies data shared with queued jobs. Use this in the `boot` method of `AppServiceProvider`. | |
- The `hydrated` event allows you to register a closure that restores context data when a queued job begins execution. Use this in the `boot` method of `AppServiceProvider`. | |
- Important: Do not use the `Context` facade within the `dehydrating` or `hydrated` callbacks, as it will change the context of the current process. | |
=== controllers === | |
- Implementing the `HasMiddleware` interface in controllers to define middleware directly within the controller class. | |
- New `middleware` method in controllers that allows returning an array of middleware for controller actions. | |
- The `creatable` method for singleton resources allows defining creation and storage routes for singleton resources. | |
- The `apiSingleton` method for registering singleton resources specifically for API usage, omitting unnecessary routes like `create` and `edit`. | |
- The `--requests` option when generating a resource controller to automatically create form request classes for storage and update methods. | |
- The `withTrashed` method for resource routes allows retrieval of soft deleted models. | |
- The `scoped` method for nested resources to enable automatic scoping of nested bindings. | |
- The `resourceVerbs` method for localizing resource URIs, allowing customization of action verbs in different languages. | |
=== database-testing === | |
- Laravel 11 allows you to automatically seed the database before each test that uses the `RefreshDatabase` trait by defining a `$seed` property on your base test class. | |
- You can specify a specific seeder to be executed before each test by defining a `$seeder` property on your test class. | |
- The `expectsDatabaseQueryCount` method is available to specify the expected number of database queries during a test; if the actual count does not match, the test will fail. | |
=== database === | |
- **New Database Support**: Laravel 11 introduces support for additional database versions, ensuring compatibility with the latest releases. | |
- **Sticky Option**: The `sticky` option in read/write connections allows immediate reading of records written during the current request cycle. | |
- **Handling Deadlocks**: The `transaction` method now accepts a second argument to specify the number of retry attempts for deadlocks. | |
- **Database Monitoring**: The `db:monitor` Artisan command can be scheduled to dispatch a `DatabaseBusy` event when the number of open connections exceeds a specified threshold. | |
- **Cumulative Query Time Monitoring**: The `whenQueryingForLongerThan` method allows you to specify a threshold for query time, invoking a closure if exceeded. | |
- **New Query Method**: The `selectResultSets` method retrieves multiple result sets from stored procedures. | |
- **Using Database URLs**: Laravel 11 supports configuring database connections using a single URL string, simplifying connection management for managed database providers. | |
=== deployment === | |
- PHP >= 8.2 is now a requirement for Laravel 11. | |
- The health check route's default URI has changed from `/up` to `/status`. | |
- The health check route now dispatches the `Illuminate\Foundation\Events\DiagnosingHealth` event for additional application-specific health checks. | |
=== dusk === | |
- Dusk now requires PHP 8.2 or higher. | |
- The `dusk:page` Artisan command generates page objects, which are placed in `tests/Browser/Pages`. | |
- The `dusk:component` Artisan command generates components, which are placed in `tests/Browser/Components`. | |
- The `waitForLocation` method allows waiting for the current window location to be a fully qualified URL. | |
- The `waitForEvent` method can now attach an event listener to specific elements, not just the body. | |
- The `assertVue` method allows making assertions on the state of Vue component data. | |
- The `assertVueIsNot`, `assertVueContains`, and `assertVueDoesntContain` methods are available for Vue component assertions. | |
- Continuous integration configurations have been updated for Heroku CI, Travis CI, GitHub Actions, and Chipper CI, including specific commands and environment settings. | |
- Warnings regarding the use of SQLite in-memory databases during Dusk tests remain relevant. | |
=== eloquent-collections === | |
- **New Method**: The `append` method can now accept an array of attributes or a single attribute to append for every model in the collection. | |
- **New Method**: The `modelKeys` method returns the primary keys for all models in the collection. | |
- **Custom Collections**: Laravel 11 introduces the `CollectedBy` attribute to specify a custom collection class for a model. | |
- **Custom Collections**: The `newCollection` method can be defined on a model to return a custom collection instance. | |
- **Warning**: If using a custom collection for every model, define the `newCollection` method on a base model class extended by all models. | |
=== eloquent-factories === | |
- **New Method**: The `recycle` method allows for reusing a single instance of a related model across multiple factory instances, ensuring consistency in relationships. | |
- **New Feature**: The `trashed` state method is automatically available to all factories for soft-deleted models. | |
- **Factory Callbacks**: The `configure` method can be defined on factory classes to register `afterMaking` and `afterCreating` callbacks, enhancing the customization of model creation. | |
- **Sequence Feature**: Sequences can now use closures for dynamic attribute assignment, allowing for more complex scenarios when creating multiple models. | |
- **Magic Methods**: New magic methods for defining relationships (e.g., `hasPosts`, `forUser`, `hasRoles`) simplify the creation of related models without needing to explicitly define the relationship name. | |
- **Polymorphic Relationships**: The ability to create polymorphic relationships using factories has been enhanced, although magic methods cannot be used for `morphTo` relationships. | |
- **Caveat**: Mass assignment protection is automatically disabled when creating models using factories, which requires careful handling of attributes to avoid security issues. | |
=== eloquent-mutators === | |
- All accessor methods must declare a return type-hint of `Illuminate\Database\Eloquent\Casts\Attribute`. | |
- Accessor caching: Changes made to value objects returned from accessors will automatically sync back to the model before saving. | |
- You can enable caching for primitive values using the `shouldCache` method in accessors. | |
- You can disable object caching behavior of attributes using the `withoutObjectCaching` method in accessors. | |
- Custom casts can now be created using the `make:cast` Artisan command, which places the new class in the `app/Casts` directory. | |
- Inbound-only custom casts can be created using the `make:cast --inbound` Artisan command. | |
- The `AsArrayObject` and `AsCollection` casts allow casting JSON attributes to `ArrayObject` and Laravel `Collection` instances, respectively. | |
- The `AsEnumCollection` cast allows storing an array of enum values within a single column. | |
- The `encrypted` cast and its variants encrypt attribute values when stored in the database, with a warning that the database column must be of `TEXT` type or larger. | |
- Key rotation for encryption requires manual re-encryption of attributes with the new key. | |
- The `withCasts` method allows applying casts to attributes during query execution. | |
- Custom cast classes can implement the `SerializesCastableAttributes` interface for custom serialization logic. | |
- Anonymous cast classes can be defined within value objects, allowing encapsulation of casting logic. | |
=== eloquent-relationships === | |
- Automatically Hydrating Parent Models on Children: Introduced `chaperone` method to `hasMany` and `morphMany` relationships for automatic hydration of parent models on child models. | |
- Default Models: The `withDefault` method can be used with `belongsTo`, `hasOne`, `hasOneThrough`, and `morphOne` relationships to define a default model returned when the relationship is `null`. | |
- Has One of Many: New `latestOfMany`, `oldestOfMany`, and `ofMany` methods for retrieving the latest, oldest, or a specific related model based on custom sorting criteria. | |
- Custom Pivot Models: Introduced `using` method to define custom pivot models for many-to-many relationships, allowing for additional behavior on the pivot model. | |
- Morph To Relationships: Added `whereHasMorph` and `whereDoesntHaveMorph` methods for querying polymorphic relationships. | |
- Eager Loading: Introduced `withWhereHas` method to eager load relationships based on existence conditions. | |
- Preventing Lazy Loading: Added `preventLazyLoading` method to disable lazy loading of relationships, throwing exceptions on attempts to lazy load. | |
- Dynamic Relationships: Introduced `resolveRelationUsing` method for defining relationships at runtime. | |
- Touching Parent Timestamps: Added `touches` property to child models to automatically update parent timestamps when the child is updated. | |
- Warning: PostgreSQL does not support executing the `MAX` function against UUID columns, affecting one-of-many relationships with UUIDs. | |
=== eloquent-resources === | |
- **Customizing the Pagination Information**: You can define a `paginationInformation` method on the resource to customize the information included in the `links` or `meta` keys of the pagination response. | |
- **Conditional Relationship Counts**: The `whenCounted` method allows you to conditionally include a relationship's count in your resource response. Other aggregate methods like `avg`, `sum`, `min`, and `max` can also be conditionally loaded using the `whenAggregated` method. | |
- **Conditional Pivot Information**: The `whenPivotLoaded` method allows you to conditionally include data from the intermediate tables of many-to-many relationships. You can also use `whenPivotLoadedAs` for custom intermediate table models. | |
- **Top Level Meta Data**: You can add a `with` method to your resource class to include meta data only when the resource is the outermost resource being returned. | |
- **Adding Meta Data When Constructing Resources**: The `additional` method can be used when constructing resource instances to add top-level data to the resource response. | |
- **Resource Responses Customization**: You can chain the `response` method onto the resource to customize the outgoing HTTP response or define a `withResponse` method within the resource to customize the response when the resource is the outermost resource. | |
- **Warning**: The `mergeWhen` method should not be used within arrays that mix string and numeric keys, and should not be used within arrays with numeric keys that are not ordered sequentially. | |
=== eloquent-serialization === | |
- NO_NEW_CONTENT | |
=== eloquent === | |
- **New Features in Laravel 11:** | |
- The `make:scope` Artisan command now places generated scopes in the `app/Models/Scopes` directory. | |
- Global scopes can now be assigned using the `ScopedBy` attribute on the model. | |
- The `dispatchesEvents` property can be used to map model lifecycle events to custom event classes. | |
- Observers can be registered using the `ObservedBy` attribute on the model. | |
- **Changes from Laravel 10:** | |
- The `preventLazyLoading` method can now be conditionally applied based on the environment (e.g., only in non-production environments). | |
- The `preventSilentlyDiscardingAttributes` method can be invoked in the `boot` method of the `AppServiceProvider` to throw exceptions for unfillable attributes during local development. | |
- The `prunable` method can now be implemented to specify which models to delete periodically, with the option to define a `pruning` method for additional cleanup. | |
- The `lazyById` method can now filter results based on descending order of the `id`. | |
- **Important Warnings or Caveats:** | |
- When issuing a mass update or delete query, the `saved`, `updated`, `deleting`, and `deleted` model events will not be dispatched. | |
- The `upsert` method requires that all databases except SQL Server have a "primary" or "unique" index on the columns specified in the second argument. | |
- Soft deleting models will be permanently deleted if they match the prunable query when using the `Prunable` or `MassPrunable` traits. | |
=== encryption === | |
- Laravel 11 introduces the `APP_PREVIOUS_KEYS` environment variable to allow graceful decryption when changing encryption keys, enabling decryption attempts with previous keys if the current key fails. | |
- The `encryptString` and `decryptString` methods remain unchanged, but the handling of previous keys enhances the functionality of the encryption service in Laravel 11. | |
=== envoy === | |
- Laravel 11 introduces support for sending notifications to Microsoft Teams using the `@microsoftTeams` directive, which accepts a Teams Webhook, message, theme color, and an array of options. | |
- The `@slack`, `@discord`, and `@telegram` directives have been updated to include additional customization options for messages. | |
- The `confirm` directive can now be used in task declarations to prompt for confirmation before executing potentially destructive operations. | |
=== errors === | |
- The `report` method in the `withExceptions` closure can now be used to register a closure that executes when an exception of a given type needs to be reported, allowing for more granular control over exception reporting. | |
- The `dontReportDuplicates` method can be invoked to ensure that a single instance of an exception is only reported once, preventing duplicate entries in logs. | |
- The `level` method allows configuration of the log level for specific exceptions when logging messages. | |
- The `dontReport` method can be used to specify types of exceptions that should never be reported, enhancing control over exception handling. | |
- The `stopIgnoring` method allows Laravel to stop ignoring specific types of exceptions that it previously handled internally. | |
- The `shouldRenderJsonWhen` method enables customization of how Laravel determines whether to render HTML or JSON exception responses. | |
- The `respond` method allows for complete customization of the HTTP response rendered by Laravel's exception handler. | |
- The `throttle` method can be used to randomly sample exceptions or conditionally sample based on exception type, providing control over how many exceptions are logged or sent to external services. | |
- The `by` method on the `Limit` instance allows customization of the rate limit key for throttling exceptions. | |
=== events === | |
- **Queueable Anonymous Event Listeners**: New in Laravel 11, you can wrap closure-based event listeners with the `Illuminate\Events\queueable` function to execute them using the queue system. You can customize execution with `onConnection`, `onQueue`, and `delay` methods. | |
- **Handling Failed Jobs**: In Laravel 11, you can define a `failed` method in your queued listener to handle failures, receiving the event instance and the `Throwable` that caused the failure. | |
- **Specifying Queued Listener Maximum Attempts**: Laravel 11 allows you to define a `$tries` property on your listener class to specify how many times the listener may be attempted before it is considered failed. | |
- **Dispatching Events After Database Transactions**: Implementing the `ShouldDispatchAfterCommit` interface on an event class in Laravel 11 allows you to dispatch the event only after the current database transaction is committed. | |
- **Scoped Event Fakes**: Laravel 11 introduces the `fakeFor` method, allowing you to fake event listeners for a specific portion of your test. | |
- **Faking a Subset of Events**: You can now pass a specific set of events to the `fake` or `fakeFor` method to only fake event listeners for those events. | |
- **Important Warning**: After calling `Event::fake()`, no event listeners will be executed. If your tests use model factories that rely on events, call `Event::fake()` **after** using your factories. | |
=== facades === | |
- Real-time facades introduced: You can treat any class in your application as if it was a facade by prefixing the namespace with `Facades`. | |
- The method signature for real-time facades does not require the explicit passing of dependencies, allowing for easier testing while maintaining testability. | |
- Facade testing methods can now be used with real-time facades, allowing for mocking and assertions similar to traditional facades. | |
=== filesystem === | |
- Scoped disks can now be created using the `scoped` driver, which automatically prefixes all paths with a specified path prefix. Requires `league/flysystem-path-prefixing` package. | |
- Read-only disks can be defined using the `read-only` configuration option, which prevents write operations. Requires `league/flysystem-read-only` package. | |
- The `temporaryUploadUrl` method has been introduced for generating temporary URLs for file uploads, specifically supported by the `s3` driver. | |
- The `serve` option must be added to the `local` disk's configuration to enable local temporary URLs if the application was developed before this feature was introduced. | |
- The `throw` option can be defined in filesystem disk configurations to throw exceptions on failed write operations. | |
- The `permissions` configuration for the `local` driver can be customized to modify the permissions mappings for public and private visibility. | |
- The `fake` method in the `Storage` facade now has a "persistentFake" option to keep files in the temporary directory instead of deleting them. | |
- The `image` method used in testing requires the GD extension. | |
=== folio === | |
- Laravel 11 introduces the **Folio** package for page-based routing, simplifying route creation by using Blade templates in the `resources/views/pages` directory. | |
- New **Folio installation command**: `php artisan folio:install` to register the service provider. | |
- **Customizable page paths**: Use `Folio::path` and `Folio::uri` methods to specify multiple directories for routing. | |
- **Subdomain routing**: Use `Folio::domain` to route based on subdomains and capture parts of the domain as parameters. | |
- **Route creation**: Place Blade templates in Folio mounted directories to create routes automatically. | |
- **Nested routes**: Create nested routes by organizing Blade templates in directories. | |
- **Index routes**: Use `index.blade.php` for directory root routing. | |
- **Route parameters**: Capture URL segments in page filenames using square brackets, with support for multiple segments. | |
- **Route model binding**: Automatically inject Eloquent model instances into pages based on filename segments. | |
- **Customizing model resolution**: Specify a column other than `id` for model binding in filenames. | |
- **Soft deleted models**: Use `withTrashed()` to include soft deleted models in route model binding. | |
- **Render hooks**: Customize responses by using the `render` function in templates, allowing additional data to be passed to the view. | |
- **Named routes**: Assign names to routes using the `name` function and generate URLs with the `route` function. | |
- **Middleware application**: Apply middleware directly in templates or to groups of pages using the `middleware` function. | |
- **Route caching**: Folio supports Laravel's route caching capabilities for improved performance. | |
=== hashing === | |
- Laravel 11 introduces the ability to disable hash algorithm verification by setting the `HASH_VERIFY` environment variable to `false`, allowing support for multiple hashing algorithms during migrations. | |
=== helpers === | |
- **Deferred Functions**: | |
- Introduced in Laravel 11, allows deferring the execution of a closure until after the HTTP response has been sent. | |
- Deferred functions will only execute if the response completes successfully; use `always` method to ensure execution regardless of response status. | |
- To cancel a deferred function, use the `forget` method with the function's name. | |
- If upgrading from Laravel 10, add `InvokeDeferredCallbacks` middleware to the `$middleware` property in `app/Http/Kernel.php`. | |
- **Testing Deferred Functions**: | |
- Use `withoutDefer` in tests to execute deferred functions immediately. | |
- **Lottery**: | |
- New methods for testing lottery invocations: `alwaysWin`, `alwaysLose`, `fix`, and `determineResultsNormally`. | |
- **Sleep Class**: | |
- Introduced a `Sleep` class for better testability and a developer-friendly API for time manipulation. | |
- Allows faking sleep in tests with `Sleep::fake()` and provides assertions like `assertSequence`, `assertSleptTimes`, and `assertNeverSlept`. | |
- **Important Warnings**: | |
- Deferred functions are currently in beta; feedback is being gathered. | |
- Ensure to handle `env` function calls correctly when using `config:cache`, as it will return `null` if called outside configuration files. | |
=== homestead === | |
- PHP 8.3 is now included as a supported version in Homestead. | |
- If using Apple Silicon, the Parallels provider is now required. | |
- The `backup` option in `Homestead.yaml` enables automatic database backups when the virtual machine is destroyed, requiring Vagrant 2.1.0 or greater. | |
- The `schedule` option can now be set to `true` in the `Homestead.yaml` file to automatically create a cron job for the site. | |
- The `minio` feature can now be configured in `Homestead.yaml` to enable Minio, with default access keys and region specified. | |
- The `webdriver` feature must be enabled in `Homestead.yaml` to run Laravel Dusk tests. | |
- The `networks` property in `Homestead.yaml` allows configuration of multiple network interfaces, including private and public networks. | |
- The `natdnshostresolver` setting can be overridden in `Homestead.yaml` for VirtualBox users. | |
=== horizon === | |
- Horizon now allows defining a wildcard environment (`*`) in the `environments` configuration, which is used when no other matching environment is found. | |
- The `autoScalingStrategy` configuration value can now be set to either `time` or `size` to determine how Horizon allocates more worker processes to queues. | |
- The `balanceMaxShift` and `balanceCooldown` configuration options have been introduced to control the scaling behavior of worker processes. | |
- The `silenced` configuration option allows specific jobs to be silenced by adding their class names, or by implementing the `Laravel\Horizon\Contracts\Silenced` interface. | |
- The `tags` method can now be defined in job classes to manually assign tags to jobs. | |
- The `tags` method in event listener classes can now utilize the event instance to add event-specific data to the tags. | |
- The `waits` configuration option allows setting specific long wait time thresholds for different connection/queue combinations. | |
- The `horizon:snapshot` Artisan command should be scheduled to run every five minutes to populate the metrics dashboard. | |
=== http-client === | |
- **URI Templates**: Introduced `withUrlParameters` method to construct request URLs using URI template specification. | |
- **Dumping Requests**: Added `dd` method to dump the outgoing request instance before it is sent. | |
- **Global Middleware**: Introduced `globalRequestMiddleware` and `globalResponseMiddleware` methods to register middleware that applies to every outgoing request and incoming response. | |
- **Global Options**: Added `globalOptions` method to configure default options for every outgoing request. | |
- **Customizing Concurrent Requests**: Clarified that `pool` method cannot be chained with other HTTP client methods like `withHeaders` or `middleware`. | |
- **Faking Response Sequences**: Introduced `Http::sequence` method to specify a series of fake responses in a specific order. | |
- **Preventing Stray Requests**: Added `preventStrayRequests` method to ensure all requests have been faked during tests. | |
- **Recording Requests/Responses**: Introduced `recorded` method to gather all requests and their corresponding responses. | |
- **Events**: Introduced three events: `RequestSending`, `ResponseReceived`, and `ConnectionFailed`, with properties to inspect request and response instances. | |
=== http-tests === | |
- **Fluent JSON Testing**: Laravel 11 introduces a fluent way to test JSON responses using the `assertJson` method with closures, allowing for more expressive assertions on JSON attributes. | |
- **`etc` Method**: The `etc` method can be used in fluent JSON assertions to indicate that additional attributes may be present without causing the test to fail, enhancing control over JSON response validation. | |
- **`assertJsonPath` Method**: This method can now accept a closure to dynamically determine if the assertion should pass, providing more flexibility in testing JSON structures. | |
- **`withoutDeprecationHandling` Method**: This new method allows tests to fail if deprecated features are used, ensuring that applications do not rely on deprecated functionality. | |
- **`assertThrows` Method**: This method is introduced to assert that a specific exception is thrown within a closure, enhancing exception handling in tests. | |
- **`assertJsonValidationErrors` and `assertJsonValidationErrorFor`**: These methods are updated to provide more robust validation error assertions for JSON responses. | |
- **`assertSessionHasInput` Method**: This method now supports a closure to validate decrypted session input values, enhancing security in tests. | |
- **`assertViewHas` Method**: This method allows for closures to be passed in to validate view data, improving the flexibility of view assertions. | |
- **`assertJsonMissingValidationErrors`**: This method is introduced to assert that the response has no JSON validation errors for specified keys, enhancing validation testing capabilities. | |
=== localization === | |
- Pluralizer now supports additional languages: `french`, `norwegian-bokmal`, `portuguese`, `spanish`, and `turkish`. | |
- Warning: If customizing the pluralizer's language, explicitly define Eloquent model's table names. | |
- Warning: For languages that differ by territory, name language directories according to ISO 15897 (e.g., "en_GB" for British English). | |
- New method: `Lang::stringable` allows registering a custom formatting handler for objects in translation placeholders. | |
- Pluralization can now specify translation strings for multiple ranges of values using the syntax: `{0} ... |[1,19] ... |[20,*] ...`. | |
=== logging === | |
- Laravel Pail is introduced for real-time log tailing, requiring PHP 8.2+ and the PCNTL extension. | |
- To install Pail, use `composer require laravel/pail`. | |
- The `pail` command can be executed with options for verbosity (`-v` for increased verbosity, `-vv` for maximum verbosity). | |
- The `--filter` option allows filtering logs by type, file, message, and stack trace content. | |
- The `--message` option filters logs by their message. | |
- The `--level` option filters logs by their log level. | |
- The `--user` option displays logs written while a specific user was authenticated. | |
=== mail === | |
- **Failover Configuration**: New `failover` transport allows defining backup mail delivery configurations for when the primary service is down. | |
- **Round Robin Configuration**: New `roundrobin` transport distributes mailing workload across multiple mailers. | |
- **Markdown Mailables**: New `--markdown` option in `make:mail` command to generate Markdown mailables. | |
- **Customizing the Symfony Message**: New ability to register custom callbacks to modify the Symfony Message instance before sending. | |
- **User Preferred Locales**: New `HasLocalePreference` contract allows automatic use of a user's preferred locale when sending mail. | |
- **Queued Mailables and Database Transactions**: New `afterCommit` method ensures queued mailables are dispatched after database transactions are committed. | |
- **Custom Transports**: New ability to create and register custom mail transports extending `Symfony\Component\Mailer\Transport\AbstractTransport`. | |
- **Additional Symfony Transports**: New support for additional Symfony maintained mail transports, such as Brevo (formerly Sendinblue), by requiring the necessary Symfony mailer and registering it with Laravel. | |
=== middleware === | |
- Middleware groups can now be managed using the `appendToGroup` and `prependToGroup` methods in the `bootstrap/app.php` file. | |
- You can append or prepend middleware to the default `web` and `api` middleware groups using the `web` and `api` methods in the `bootstrap/app.php` file. | |
- Middleware aliases can be defined in the `bootstrap/app.php` file, allowing for shorter names when assigning middleware to routes. | |
- The `priority` method can be used to specify the execution order of middleware in the `bootstrap/app.php` file. | |
- Middleware can now receive additional parameters, allowing for more dynamic middleware behavior. | |
- The `terminate` method can be defined in middleware to perform actions after the HTTP response has been sent, and it will be called automatically if using FastCGI. | |
=== migrations === | |
- Migration squashing is introduced, allowing migrations to be consolidated into a single SQL file using the `schema:dump` command. | |
- The `--prune` option for the `schema:dump` command removes existing migrations after the dump. | |
- The `isolated` option for the `migrate` command is introduced to acquire an atomic lock before running migrations, preventing concurrent execution on multiple servers. | |
- The `--force` flag for the `migrate` command allows destructive migration operations to run without confirmation prompts. | |
- The `nullableMorphs`, `nullableUlidMorphs`, and `nullableUuidMorphs` methods are introduced for creating nullable polymorphic relationship columns. | |
- The `vector` method is introduced for creating a `vector` equivalent column. | |
- The `ulidMorphs` method is introduced for creating polymorphic relationship columns using ULID identifiers. | |
- The `uuidMorphs` method is introduced for creating polymorphic relationship columns using UUID identifiers. | |
- Support for default expressions in column definitions is introduced, allowing the use of database-specific functions as default values. | |
- New event classes related to migrations are introduced, such as `MigrationsStarted`, `MigrationsEnded`, `MigrationStarted`, `MigrationEnded`, `NoPendingMigrations`, `SchemaDumped`, and `SchemaLoaded`. | |
=== mix === | |
- Vite has replaced Laravel Mix in new Laravel installations. | |
- For existing applications using Laravel Mix, refer to the official Laravel Mix website for documentation. | |
- A migration guide is available for switching from Laravel Mix to Vite. | |
=== mocking === | |
- The `mock` method is now available in Laravel's base test case class for convenience when mocking objects. | |
- The `partialMock` method allows mocking of only specific methods of an object, with unmocked methods executing normally. | |
- The `spy` method is introduced as a convenient wrapper around `Mockery::spy` for spying on objects. | |
- Facade spying can now be performed by calling the `spy` method directly on the corresponding facade. | |
- New time manipulation methods include `freezeTime` and `freezeSecond`, which allow freezing time during a closure execution. | |
- The ability to provide a closure to time travel methods is introduced, allowing tests to run with frozen time for specific scenarios. | |
=== notifications === | |
- Localization of notifications can now be set using the `locale` method on the `Notification` class, allowing notifications to be sent in a different locale than the current HTTP request's locale. | |
- The `HasLocalePreference` contract can be implemented on notifiable models to automatically use stored user preferences for locale when sending notifications. | |
- New `afterCommit` method allows queued notifications to be dispatched after database transactions are committed, preventing issues with uncommitted data. | |
- The `shouldSend` method can be defined on notifications to determine if a queued notification should be sent after being processed by a queue worker. | |
- Notifications can now be sent using the `Notification::routes` method to provide ad-hoc routing information for multiple channels at once. | |
- The `viaConnections` method can be defined on notifications to specify different queue connections for each notification channel. | |
- The `viaQueues` method allows specifying different queue names for each notification channel. | |
- Queued notifications can now define middleware using the `middleware` method, similar to queued jobs. | |
- The `broadcastType` method can be defined on notifications to customize the notification type sent during broadcasting. | |
- Slack notifications can utilize the `usingBlockKitTemplate` method to send raw JSON payloads generated by Slack's Block Kit Builder. | |
- New features for Slack notifications include handling user interactions with buttons and confirmation modals, enhancing the interactivity of notifications. | |
- The `dd` method can be called on `SlackMessage` instances to quickly inspect the generated blocks in Slack's Block Kit Builder. | |
=== octane === | |
- Laravel Octane requires PHP 8.1+. | |
- Octane will automatically download and install the FrankenPHP binary when selected as the server. | |
- Octane will offer to download and install the RoadRunner binary the first time it is started. | |
- Swoole and Open Swoole must be installed via PECL for use with Octane. | |
- The `OCTANE_HTTPS` environment variable can be set to `true` to prefix all generated links with `https://`. | |
- The `--watch` flag can be used with `octane:start` to automatically restart the server on file changes, requiring Node and Chokidar. | |
- Octane gracefully restarts any worker after handling 500 requests by default, adjustable via the `--max-requests` option. | |
- The `octane:reload` command can be used to gracefully restart the Octane server's application workers. | |
- Octane supports executing operations concurrently via the `concurrently` method when using Swoole, with a limit of 1024 tasks. | |
- The `tick` method allows registering operations to be executed at specified intervals when using Swoole. | |
- The Octane cache driver provides extreme read/write speeds and is powered by Swoole tables, with data flushed on server restart. | |
- Interval-based caches can be registered to refresh automatically at specified intervals. | |
- Swoole tables can be defined in the `tables` configuration array, allowing for high-performance data access across workers. | |
=== packages === | |
- Laravel 11 introduces the `optimizes` method for registering package-specific Artisan commands that should be invoked during the `optimize` and `optimize:clear` commands. | |
- The `AboutCommand` class can now be used to push additional information from packages to Laravel's built-in `about` Artisan command. | |
- The `publishesMigrations` method has been added to inform Laravel that a directory contains migrations, automatically updating the timestamp in their filenames upon publishing. | |
- The `loadJsonTranslationsFrom` method has been introduced for registering JSON translation files for packages. | |
- The `componentNamespace` method allows for autoloading component classes by convention, supporting subdirectories using "dot" notation. | |
- Laravel 11 requires that anonymous components be placed within a `components` directory of the package's views directory. | |
=== pagination === | |
- **Cursor Pagination Enhancements**: In Laravel 11, cursor pagination now requires an "order by" clause in the query. The columns used for ordering must belong to the table being paginated. | |
- **Paginator Customization**: You can now set default pagination views using the `defaultView` and `defaultSimpleView` methods in the `boot` method of your `App\Providers\AppServiceProvider` class. | |
- **Bootstrap Support**: Laravel 11 introduces methods to use Bootstrap pagination views (`useBootstrapFour` and `useBootstrapFive`) in the `boot` method of your `App\Providers\AppServiceProvider`. | |
- **New Methods in Cursor Paginator**: The cursor paginator now includes additional methods such as `getCursorName()` and `setCursorName()` for managing the query string variable used to store the cursor. | |
- **Performance Improvements**: Cursor pagination is highlighted as providing better performance for large datasets, especially when the "order by" columns are indexed. | |
- **Warning on Cursor Pagination**: It is emphasized that cursor pagination can only display "Next" and "Previous" links and does not support generating links with page numbers. | |
=== passport === | |
- The `install:api` Artisan command now allows for the installation of Laravel Passport and publishes necessary database migrations and encryption keys. | |
- The `passport:keys` command is required to generate encryption keys for access tokens when deploying Passport. | |
- The `Passport::hashClientSecrets` method can be called to hash client secrets when stored in the database. | |
- The default token lifetime is now configurable using `tokensExpireIn`, `refreshTokensExpireIn`, and `personalAccessTokensExpireIn` methods. | |
- The `enablePasswordGrant` method is now required to enable password grant tokens. | |
- The `passport:client` command now supports a `--public` option for creating PKCE-enabled clients. | |
- The `passport:client` command also supports a `--password` option for creating password grant clients. | |
- The `passport:client` command includes a `--provider` option to specify the user provider when creating a password grant client. | |
- The `CreateFreshApiToken` middleware must be appended to the `web` middleware group for JavaScript applications to consume the API without explicitly passing an access token. | |
- The `Passport::cookie` method allows customization of the `laravel_token` cookie's name. | |
- The `actingAs` and `actingAsClient` methods in Passport are used for testing to specify the currently authenticated user or client along with their scopes. | |
=== passwords === | |
- **Deleting Expired Tokens**: Introduced the `auth:clear-resets` Artisan command to delete expired password reset tokens from the database. | |
- **Reset Link Customization**: New `createUrlUsing` method in the `ResetPassword` notification class allows customization of the password reset link URL. | |
- **Reset Email Customization**: Override the `sendPasswordResetNotification` method in the `App\Models\User` model to use a custom notification class for sending password reset links. | |
=== pennant === | |
- **Class Based Features**: New in Laravel 11, you can define class-based features without needing to register them in a service provider. Use the `pennant:feature` Artisan command to create a feature class. | |
- **Customizing the Stored Feature Name**: You can specify a `$name` property in class-based features to decouple the stored feature name from the class name. | |
- **In-Memory Cache**: When checking a feature, Pennant creates an in-memory cache of the result. If using the `database` driver, re-checking the same feature within a single request will not trigger additional database queries. Use `Feature::flushCache()` to manually flush the in-memory cache. | |
- **Nullable Scope**: If the provided scope is `null` and the feature's definition does not support `null`, Pennant will return `false`. Ensure your feature definitions handle potential `null` scope values. | |
- **Identifying Scope**: Implement the `FeatureScopeable` contract on objects used as Pennant scopes to customize how scope values are stored for third-party drivers. | |
- **Rich Feature Values**: Features can now return rich values (e.g., strings) instead of just binary states. A feature is considered "active" if it has any value other than `false`. | |
- **Eager Loading**: Use `Feature::for($users)->load(['feature-name'])` to eager load feature values for a collection of users, reducing potential database queries. | |
- **Bulk Updates**: New methods `activateForEveryone` and `deactivateForEveryone` allow bulk updates of feature values for all users. | |
- **Purging Features**: You can purge individual features or all features from storage using the `purge` method. The `pennant:purge` Artisan command supports purging with options to exclude specific features. | |
- **Testing**: Redefining features in tests allows for controlling the returned value easily. You can redefine both closure-based and class-based features. | |
- **Events**: New events such as `FeatureRetrieved`, `FeatureResolved`, and `UnexpectedNullScopeEncountered` allow for tracking feature flag usage and handling specific scenarios during feature checks. | |
=== pint === | |
- Laravel Pint is automatically included with all new Laravel applications. | |
- Laravel Pint can be run using the `pint` binary located in the `vendor/bin` directory. | |
- New options in Laravel 11 for running Pint: | |
- `--dirty`: Only modifies files with uncommitted changes. | |
- `--repair`: Fixes files with code style errors and exits with a non-zero exit code if any errors were fixed. | |
- Configuration can be done using a `pint.json` file in the project's root directory. | |
- Supported presets in Laravel 11 include: `laravel`, `per`, `psr12`, `symfony`, and `empty`. | |
- New configuration options for excluding files/folders: | |
- `exclude`: To exclude specific folders. | |
- `notName`: To exclude files by name pattern. | |
- `notPath`: To exclude files by exact path. | |
- Continuous Integration setup for GitHub Actions includes a specific PHP version matrix option (`php: [8.3]`). | |
=== precognition === | |
- Laravel 11 introduces the **Precognition** feature, allowing anticipation of future HTTP request outcomes without executing the route's controller method. | |
- To enable Precognition for a route, the `HandlePrecognitiveRequests` middleware must be added to the route definition. | |
- New frontend helper packages for Vue, React, and Alpine have been introduced: | |
- `laravel-precognition-vue` | |
- `laravel-precognition-react` | |
- `laravel-precognition-alpine` | |
- The `submit` method in the Inertia-compatible form helper has been streamlined, removing the need to specify the HTTP method or URL. | |
- The `setValidationTimeout` function can be called to configure the debounce timeout for validation requests. | |
- Precognition validation libraries utilize Axios for requests, and the Axios instance can be customized for outgoing requests. | |
- The `isPrecognitive` method can be used in form requests to customize validation rules based on whether the request is precognitive. | |
- By default, file uploads are not validated during precognitive requests to prevent unnecessary uploads; this behavior can be modified using `validateFiles`. | |
- The `withPrecognition` helper is available for making precognitive requests in tests, and the `assertSuccessfulPrecognition` method can be used to assert successful validation. | |
=== processes === | |
- **New Features in Laravel 11:** | |
- Introduced `Process::pipe` method for piping the output of one process into another, allowing for easier chaining of commands. | |
- Added `Process::concurrently` method to start an asynchronous process pool and immediately wait on its results, enhancing syntax expressiveness. | |
- **Changes from Laravel 10:** | |
- The `tty` method can now be used to enable TTY mode for processes, allowing interactive command-line applications to run. | |
- The `waitUntil` method has been introduced for asynchronous processes, allowing the waiting to stop based on the output of the process. | |
- The `signal` method can now be used on a process pool to send a signal to every process within the pool. | |
- **Important Warnings or Caveats:** | |
- Ensure that all invoked processes have been faked when using `Process::preventStrayProcesses`, as any processes without a corresponding fake result will throw an exception. | |
=== prompts === | |
- Laravel Prompts is included with the latest release of Laravel 11. | |
- New `transform` argument added to prompt functions to allow input transformation before validation. | |
- The `form` function now allows users to return to previous prompts using `CTRL + U`. | |
- The `spin` function requires the `pcntl` PHP extension; a static spinner will appear if this extension is not available. | |
- Fallback conditions can be customized using the `fallbackWhen` method on the `Prompt` class. | |
- Fallback behavior can be customized using the `fallbackUsing` method on each prompt class. | |
=== providers === | |
- Implementing the `\Illuminate\Contracts\Support\DeferrableProvider` interface is now required for deferred providers. | |
- The `provides` method must be defined in deferred providers to specify the service container bindings registered by the provider. | |
- Laravel 11 introduces automatic registration of service providers when generated via the `make:provider` command, which adds them to the `bootstrap/providers.php` file. | |
- The `$app` property is accessible within any service provider methods, providing access to the service container. | |
=== pulse === | |
- Pulse's first-party storage implementation requires a MySQL, MariaDB, or PostgreSQL database. A separate database is needed for Pulse data if using a different engine. | |
- The `ignore-after` prop for the `<livewire:pulse.servers />` card allows specifying a duration after which inactive servers should be removed from the dashboard. | |
- The `PULSE_DB_CONNECTION` environment variable can be set to use a dedicated database connection for Pulse. | |
- Redis Ingest requires Redis 6.2 or greater and `phpredis` or `predis` as the configured Redis client driver. | |
- The `PULSE_INGEST_DRIVER` environment variable can be set to `redis` to enable Redis ingest. | |
- The `PULSE_SERVER_NAME` environment variable allows customization of the server name reported by Pulse. | |
- The `handleExceptionsUsing` method can be used to customize how exceptions in Pulse are handled. | |
- The `Pulse::filter` method allows filtering out records based on factors such as the authenticated user. | |
- The `Pulse::record` method allows capturing "entries" with aggregation methods like `sum`, `count`, etc. | |
- The `aggregate` method retrieves aggregated data for the period viewed in the dashboard. | |
- The `aggregateTotal` method retrieves the total value for a given type instead of grouping by user. | |
- The `Pulse::resolveUsers` method resolves user IDs to user records for displaying aggregates. | |
=== queries === | |
- **New Methods:** | |
- `whereAny`, `whereAll`, `whereNone` methods for applying query constraints to multiple columns. | |
- `whereLike`, `orWhereLike`, `whereNotLike`, `orWhereNotLike` methods for pattern matching with LIKE clauses. | |
- `whereBetweenColumns`, `whereNotBetweenColumns`, `orWhereBetweenColumns`, `orWhereNotBetweenColumns` methods for comparing column values against other columns. | |
- **Changes:** | |
- The `whereLike` method now supports a `caseSensitive` argument, allowing case-sensitive searches (not supported on SQL Server). | |
- **Warnings:** | |
- MySQL and MariaDB typecast strings to integers in comparisons, which can lead to unexpected results. Ensure values are typecast appropriately before queries. | |
- When using `insertGetId` with PostgreSQL, the auto-incrementing column must be named `id`, or a different sequence name must be specified. | |
- All databases except SQL Server require the columns in the second argument of the `upsert` method to have a "primary" or "unique" index. MariaDB and MySQL ignore the second argument and always use the primary and unique indexes for detecting existing records. | |
=== queues === | |
- The `ShouldBeUnique` interface now allows you to define a specific "key" that makes the job unique or specify a timeout beyond which the job no longer stays unique using `uniqueId` and `uniqueFor` properties or methods. | |
- The `ShouldBeUniqueUntilProcessing` contract allows jobs to unlock immediately before processing, rather than after completion. | |
- The `ShouldBeEncrypted` interface can be added to job classes to ensure the privacy and integrity of a job's data via encryption. | |
- Job middleware can be defined in any location within the application, allowing for custom logic around queued jobs. | |
- The `Skip` middleware allows jobs to be deleted based on specified conditions without modifying job logic. | |
- The `ThrottlesExceptions` middleware allows you to throttle exceptions, delaying further attempts to execute the job after a specified number of exceptions. | |
- The `WithoutOverlapping` middleware prevents job overlaps based on an arbitrary key and can be shared across job classes using the `shared` method. | |
- The `SkipIfBatchCancelled` middleware can be used to skip processing a job if its corresponding batch has been cancelled. | |
- The `queue:prune-batches` command can now prune unfinished batch records and cancelled batch records using specific options. | |
- Laravel now supports storing batch meta information in DynamoDB, requiring a specific table structure and configuration. | |
- The `deleteWhenMissingModels` property on jobs allows automatic deletion of jobs with missing models without raising exceptions. | |
- The `queue:monitor` command can be scheduled to alert when the queue job count exceeds a specified threshold. | |
- The `Bus::fake()` method can be used to prevent queued jobs from being pushed to the queue during testing, with assertions available for job counts and specific job types. | |
- The `retryUntil` method can be defined on job classes to specify a time at which the job should no longer be attempted. | |
- The `failOnTimeout` property can be set on job classes to indicate that a job should be marked as failed on timeout. | |
- The `queue:flush` command allows for deleting all failed jobs from the `failed_jobs` table. | |
=== rate-limiting === | |
- The rate limiter now allows specifying a `limiter` key in the cache configuration to define which cache driver to use for rate limiting. | |
- The `attempt` method can now accept a fourth argument for the "decay rate," allowing for more flexible rate limiting configurations. | |
- The `increment` method can now accept an `amount` parameter to increment the attempts by a specified number, rather than just one. | |
=== redirects === | |
- Laravel 11 introduces the global `to_route` function for convenience in redirecting to named routes. | |
- The `getRouteKey` method on Eloquent models can now be overridden to customize the value placed in route parameters when redirecting. | |
=== redis === | |
- **PhpRedis Serialization and Compression**: Laravel 11 introduces support for additional serializers and compression algorithms in the PhpRedis extension, configurable via the `options` array in the Redis configuration. Supported serializers: `Redis::SERIALIZER_NONE`, `Redis::SERIALIZER_PHP`, `Redis::SERIALIZER_JSON`, `Redis::SERIALIZER_IGBINARY`, `Redis::SERIALIZER_MSGPACK`. Supported compression algorithms: `Redis::COMPRESSION_NONE`, `Redis::COMPRESSION_LZF`, `Redis::COMPRESSION_ZSTD`, `Redis::COMPRESSION_LZ4`. | |
- **Warning on Redis Transactions**: In Laravel 11, when defining a Redis transaction using the `transaction` method, you cannot retrieve any values from the Redis connection during the execution of the closure, as the transaction is executed as a single atomic operation. | |
- **Warning on Lua Scripts**: The `eval` method allows executing multiple Redis commands atomically and can interact with Redis key values. Users are advised to consult the Redis documentation for more information on scripting. | |
- **Wildcard Subscriptions**: Laravel 11 adds the ability to subscribe to wildcard channels using the `psubscribe` method, allowing for catching all messages on all channels or specific patterns. | |
=== releases === | |
- Laravel 11 requires a minimum PHP version of 8.2. | |
- Streamlined application structure for new Laravel applications, with a revitalized `bootstrap/app.php` file for application configuration. | |
- Only a single `AppServiceProvider` is included by default; previous service providers' functionalities are now integrated into the `bootstrap/app.php`. | |
- `api.php` and `channels.php` route files are no longer included by default; they can be created using Artisan commands. | |
- Middleware has been moved into the framework, allowing customization via `bootstrap/app.php`, eliminating the need for a separate HTTP "kernel" class. | |
- Scheduled tasks can now be defined directly in `routes/console.php` using a new `Schedule` facade. | |
- Exception handling can now be customized from `bootstrap/app.php`, reducing the number of files in new applications. | |
- The base controller no longer extends Laravel's internal `Controller` class, simplifying its structure. | |
- New applications use SQLite for database storage by default, along with the `database` driver for session, cache, and queue. | |
- Laravel Reverb introduced for scalable WebSocket communication. | |
- Per-second rate limiting is now supported for all rate limiters. | |
- Health routing directive added for a health-check endpoint at `/up`. | |
- Graceful encryption key rotation allows defining previous encryption keys via `APP_PREVIOUS_KEYS`. | |
- Automatic password rehashing on user authentication when the bcrypt work factor is increased. | |
- Prompt validation now supports full Laravel validation for command-line inputs. | |
- Queue interaction testing simplified with `withFakeQueueInteractions` method. | |
- New Artisan commands for creating classes, enums, interfaces, and traits. | |
- Model casts can now be defined using a method instead of a property. | |
- The `once` helper function caches the result of a callback for the duration of the request. | |
- Improved performance when testing with in-memory databases, reducing total test run time. | |
- Improved support for MariaDB with a dedicated driver. | |
- Additional database schema operation and inspection methods introduced. | |
=== requests === | |
- **New Methods in Request Class**: | |
- `string` method: Retrieves input data as an instance of `Illuminate\Support\Stringable`. | |
- `integer` method: Casts input value to an integer. | |
- `boolean` method: Retrieves truthy values as booleans. | |
- `date` method: Retrieves date input values as Carbon instances. | |
- `enum` method: Retrieves input values corresponding to PHP enums. | |
- **Input Normalization Changes**: | |
- Middleware for input normalization can now be conditionally applied using `trimStrings` and `convertEmptyStringsToNull` methods. | |
- **Trusted Proxies Configuration**: | |
- New ability to trust all proxies using `trustProxies(at: '*')`. | |
- **Trusted Hosts Configuration**: | |
- `trustHosts` middleware can now be configured to accept hostnames dynamically via a closure. | |
- **Warnings**: | |
- The `date` method may throw an `InvalidArgumentException` if the input format is invalid; validation is recommended before use. | |
=== responses === | |
- Streamed JSON Responses: New `streamJson` method for incrementally streaming JSON data, useful for large datasets. | |
- Streamed Downloads: New `streamDownload` method to create downloadable responses from string outputs without writing to disk. | |
- Cache Control Middleware: New `cache.headers` middleware for setting `Cache-Control` headers with automatic ETag generation if specified. | |
=== reverb === | |
- Reverb can now be installed using the `install:broadcasting` Artisan command, which internally runs `reverb:install`. | |
- The `REVERB_HOST` environment variable must be set to your site's hostname for secure connections when using Laravel Herd or Valet. | |
- Reverb now supports automatic switching to an `ext-uv` powered event loop if available, which allows handling more than 1,024 open files. | |
- To enable monitoring, Reverb can integrate with Laravel Pulse, requiring the addition of Reverb's recorders in the `config/pulse.php` configuration file. | |
- The `REVERB_SCALING_ENABLED` environment variable can be set to `true` to enable horizontal scaling of the Reverb server using Redis. | |
=== routing === | |
- API Routes: The `install:api` Artisan command now creates the `routes/api.php` file and installs Laravel Sanctum for API token authentication. | |
- Routing Customization: You can now define additional routes using a `then` closure in the `withRouting` method. | |
- Implicit Enum Binding: Laravel 11 supports type-hinting backed Enums in route definitions, automatically returning a 404 if the route segment does not correspond to a valid Enum value. | |
- Rate Limiting: The `response` method can now be used to define custom responses for rate limit exceedances. | |
- Throttling With Redis: You can now map the `throttle` middleware to use Redis for rate limiting by using the `throttleWithRedis` method in `bootstrap/app.php`. | |
- Route Caching: The `route:cache` command is emphasized for production deployment, with a reminder to regenerate the cache after adding new routes. | |
=== sail === | |
- If you are using Docker Desktop for Linux, use the `default` Docker context by executing `docker context use default`. | |
- To add an additional service to your existing Sail installation, run the `sail:add` Artisan command. | |
- Use the `--devcontainer` option with the `sail:install` command to publish a default `.devcontainer/devcontainer.json` file. | |
- Sail now supports PHP 8.3 as the default version. | |
- Sail installs Node 20 by default. | |
- The `share` command allows you to share your site publicly, and you must configure your application's trusted proxies using the `trustProxies` middleware method. | |
- To enable Xdebug, set `SAIL_XDEBUG_MODE=develop,debug,coverage` in your `.env` file. | |
- For Linux users with Docker versions older than 20.10, you must manually define the host IP for Xdebug. | |
- The `sail debug` command can be used to start a debugging session with Xdebug when running an Artisan command. | |
- Laravel Sail relies on `artisan serve` to serve your application, which only accepts `XDEBUG_CONFIG` and `XDEBUG_MODE` variables as of Laravel version 8.53.0. | |
=== sanctum === | |
- **New Installation Command**: You can install Laravel Sanctum via the `install:api` Artisan command: `php artisan install:api`. | |
- **Token Expiration Configuration**: You can configure an expiration time for API tokens via the `expiration` configuration option in the `sanctum` configuration file. The default is set to 525600 minutes (1 year). | |
- **Pruning Expired Tokens**: Sanctum includes a `sanctum:prune-expired` Artisan command to delete expired token records. You can schedule this command in your application. | |
- **First-Party UI Initiated Requests**: The `tokenCan` method will return `true` for requests from your first-party SPA using Sanctum's built-in SPA authentication. | |
- **CORS Configuration**: If accessing via a URL with a port, include the port number in the domain configuration. | |
- **Sanctum Middleware**: You can use the `statefulApi` middleware method to allow requests from your SPA to authenticate using session cookies while still allowing API token authentication for third-party requests. | |
- **CSRF Protection Initialization**: For SPAs, make a request to `/sanctum/csrf-cookie` to initialize CSRF protection. | |
- **Custom Pusher Authorizer**: When using Pusher for broadcasting, provide a custom authorizer to configure it to use the properly set up axios instance for cross-domain requests. | |
- **Mobile Application Token Issuing**: Create a route to exchange user credentials for a new Sanctum token, which can be used for mobile application requests. | |
- **Testing with Sanctum**: Use the `Sanctum::actingAs` method to authenticate a user with specific abilities during testing. | |
=== scheduling === | |
- **Sub-Minute Scheduled Tasks**: Laravel 11 allows scheduling tasks to run as frequently as once per second. | |
- **Interrupting Sub-Minute Tasks**: Introduced `schedule:interrupt` command to interrupt in-progress `schedule:run` invocations during deployment. | |
- **Background Tasks**: The `runInBackground` method can only be used with `command` and `exec` methods. | |
- **Task Output Methods**: New methods for task output handling include `sendOutputTo`, `appendOutputTo`, `emailOutputTo`, and `emailOutputOnFailure`, which are exclusive to `command` and `exec` methods. | |
- **Task Hooks**: New methods `before`, `after`, `onSuccess`, and `onFailure` for executing code before and after tasks, and based on task success or failure. | |
- **Pinging URLs**: New methods `pingBefore`, `thenPing`, `pingBeforeIf`, `thenPingIf`, `pingOnSuccess`, and `pingOnFailure` for notifying external services about task execution status. | |
- **Events**: New events dispatched during the scheduling process include `ScheduledTaskStarting`, `ScheduledTaskFinished`, `ScheduledBackgroundTaskFinished`, `ScheduledTaskSkipped`, and `ScheduledTaskFailed`. | |
- **Warning on Timezones**: Caution against using timezone scheduling due to potential issues with daylight saving time changes. | |
=== scout === | |
- **New Features in Laravel 11:** | |
- Introduced attributes for customizing database searching strategies using `#[SearchUsingPrefix]` and `#[SearchUsingFullText]` annotations in the `toSearchableArray` method. | |
- New `makeAllSearchableUsing` method for modifying the import query during batch imports. | |
- New `makeSearchableUsing` method for modifying the collection of models being made searchable. | |
- Added `shouldBeSearchable` method for conditionally making models searchable. | |
- **Changes from Laravel 10:** | |
- The `soft_delete` option in `config/scout.php` now allows soft deleted models to be indexed with a hidden `__soft_deleted` attribute. | |
- The `queue` configuration option can now be set as an array to specify connection and queue details. | |
- The `searchableUsing` method allows specifying a search engine per model, enhancing flexibility. | |
- The `unsearchable` method can now be used on Eloquent query instances to remove records from the search index. | |
- **Important Warnings/Caveats:** | |
- When upgrading Scout with Meilisearch, always review any additional breaking changes to the Meilisearch service itself. | |
- The `makeAllSearchableUsing` method may not be applicable when using a queue to batch import models. | |
- The `shouldBeSearchable` method is not applicable when using Scout's "database" engine, as all searchable data is always stored in the database. | |
- If using Meilisearch, you must configure your application's filterable attributes before utilizing Scout's "where" clauses. | |
- Global scopes should not be utilized in applications that utilize Scout pagination, or they should be recreated when searching via Scout. | |
=== seeding === | |
- **New Feature**: Laravel 11 introduces the ability to type-hint dependencies directly in the `run` method's signature of seeders, allowing automatic resolution via the service container. | |
- **Caveat**: In production environments, running seeding commands will prompt for confirmation to prevent accidental data loss. Use the `--force` flag to bypass this prompt. | |
=== session === | |
- **Session Blocking**: | |
- New `block` method allows limiting concurrent requests for a given session. | |
- Accepts two optional arguments: `lockSeconds` (max time to hold the lock) and `waitSeconds` (max time to wait for the lock). | |
- Throws `Illuminate\Contracts\Cache\LockTimeoutException` if unable to obtain a session lock within the specified time. | |
- Requires a cache driver that supports atomic locks; `cookie` session driver cannot be used. | |
- **Adding Custom Session Drivers**: | |
- Custom session drivers must implement PHP's `SessionHandlerInterface`. | |
- Use the `extend` method from the `Session` facade to register custom drivers in a service provider. | |
=== socialite === | |
- **Slack Bot Scopes**: Introduced `asBotUser` method to generate a bot token for Slack authentication. Must be called before redirecting and when retrieving user details after authentication. | |
- **Optional Parameters**: Warning added about not passing reserved keywords (e.g., `state`, `response_type`) when using the `with` method for optional parameters in the redirect request. | |
- **Stateless Authentication**: New `stateless` method to disable session state verification, useful for stateless APIs. | |
=== strings === | |
- `Str::apa()` method introduced to convert strings to title case following APA guidelines. | |
- `Str::inlineMarkdown()` method added to convert GitHub flavored Markdown into inline HTML without wrapping in block-level elements. | |
- `Str::ulid()` method introduced to generate a ULID (Universally Unique Lexicographically Sortable Identifier). | |
- `Str::orderedUuid()` method introduced to generate a "timestamp first" UUID for efficient storage in indexed database columns. | |
- `Str::createUlidsUsing()` and `Str::createUlidsNormally()` methods added for testing purposes to fake ULID generation. | |
- `Str::createRandomStringsUsing()` and `Str::createRandomStringsNormally()` methods added for testing purposes to fake random string generation. | |
- `Str::mask()` method enhanced to allow negative numbers for masking from the end of the string. | |
- `Str::whenContains()`, `Str::whenContainsAll()`, `Str::whenEmpty()`, `Str::whenNotEmpty()`, `Str::whenStartsWith()`, `Str::whenEndsWith()`, `Str::whenExactly()`, `Str::whenNotExactly()`, `Str::whenIs()`, `Str::whenIsAscii()`, `Str::whenIsUlid()`, `Str::whenIsUuid()`, and `Str::whenTest()` methods added for conditional execution of closures based on string properties. | |
- `Str::scan()` method added for parsing input from a string into a collection according to a format supported by `sscanf`. | |
- `Str::exactly()` method introduced to check for exact string matches. | |
- `Str::pipe()` method added to transform the string by passing its current value to a callable. | |
- `Str::replace()` method now accepts a `caseSensitive` argument for case sensitivity control during replacements. | |
=== telescope === | |
- **Local Only Installation**: In Laravel 11, after running `telescope:install`, you must remove the `TelescopeServiceProvider` registration from `bootstrap/providers.php` and manually register it in `App\Providers\AppServiceProvider` to ensure it only loads in the local environment. | |
- **Dashboard Authorization Warning**: Ensure you change your `APP_ENV` environment variable to `production` in your production environment to prevent unauthorized access to the Telescope dashboard. | |
- **Filtering Enhancements**: The `filterBatch` method is introduced to register a closure that filters all data for a given request or console command, enhancing the filtering capabilities of Telescope. | |
- **Tagging Customization**: You can now attach custom tags to entries using the `Telescope::tag` method, which allows for more granular tracking of requests based on specific criteria. | |
- **Watcher Customization**: The configuration for watchers has been enhanced to allow for more granular control over which commands, abilities, and events are recorded, including the ability to specify `ignore` options for various watchers. | |
- **Avatar Customization**: The method for customizing user avatars in the Telescope dashboard has been updated to allow for a callback that returns a user's avatar image URL based on their ID and email. | |
=== testing === | |
- **Parallel Testing Hooks**: Introduced `ParallelTesting` facade to specify code for `setUp` and `tearDown` of processes or test cases. | |
- **Accessing the Parallel Testing Token**: New method `ParallelTesting::token()` to access the unique token for each parallel test process. | |
- **Enforcing a Minimum Coverage Threshold**: New `--min` option for the `php artisan test --coverage` command to set a minimum test coverage threshold. | |
- **Warnings**: | |
- When running tests in parallel, some Pest/PHPUnit options (e.g., `--do-not-cache-result`) may not be available. | |
- Coverage reporting requires Xdebug or PCOV. | |
=== upgrade === | |
- PHP 8.2.0 and curl 7.34.0 are now required. | |
- New default application structure with fewer service providers, middleware, and configuration files. | |
- Password rehashing is now automatic during authentication if the hashing algorithm's work factor has changed. Specify a custom password field using `$authPasswordName` if needed. | |
- `UserProvider` contract includes a new `rehashPasswordIfRequired` method. | |
- `Authenticatable` contract includes a new `getAuthPasswordName` method. | |
- `AuthenticationException` class's `redirectTo` method now requires an `Illuminate\Http\Request` instance as its first argument. | |
- `SendEmailVerificationNotification` listener is automatically registered for the `Registered` event unless explicitly configured not to. | |
- Cache key prefixes for DynamoDB, Memcached, or Redis no longer receive a `:` suffix. | |
- `dump` method of `Enumerable` contract now accepts a variadic `...$args` argument. | |
- SQLite database now requires version 3.26.0 or greater. | |
- When modifying columns, all modifiers must be explicitly included to retain existing attributes. | |
- `double` and `float` migration column types have been rewritten for consistency across databases. | |
- A dedicated MariaDB driver is introduced, which behaves like MySQL but creates native UUID columns. | |
- Spatial column types have been standardized; use `geometry` or `geography` methods instead of specific spatial types. | |
- Doctrine DBAL has been removed; related classes and methods are no longer available. | |
- New native schema methods (`Schema::getTables()`, `Schema::getViews()`, etc.) replace deprecated Doctrine methods. | |
- Carbon 3 is now supported; `diffIn*` methods return floating-point numbers and may return negative values. | |
- `Mailer` contract includes a new `sendNow` method. | |
- New `BatchRepository` interface method `rollBack`. | |
- Synchronous jobs in database transactions now respect the "after commit" configuration. | |
- Per-second rate limiting is now supported; constructors and properties have been updated to accept seconds. | |
- Cashier Stripe, Spark Stripe, Passport, and Sanctum no longer automatically load migrations; publish migrations manually. | |
- Laravel 11 provides its own `once` function, removing the need for the `spatie/once` package. | |
=== urls === | |
- **URL Defaults and Middleware Priority**: Setting URL default values can interfere with Laravel's handling of implicit model bindings. Prioritize middleware that sets URL defaults to be executed before Laravel's `SubstituteBindings` middleware using the `priority` middleware method in `bootstrap/app.php`. | |
=== valet === | |
- Valet now supports the `isolate` command to specify per-site PHP versions, allowing different sites to use different PHP versions without modifying the global PHP version. | |
- The `share-tool` command allows users to specify either `ngrok` or `expose` for sharing sites, with automatic prompts for installation if the tool is not present. | |
- The `secure` command can now serve sites over encrypted TLS using HTTP/2. | |
- The `default` option in the `~/.config/valet/config.json` file allows users to configure a default site to serve instead of a `404` for unknown `test` domains. | |
- The `proxy` command allows users to proxy traffic from a Valet domain to another service running locally, with support for both HTTP and secure HTTP/2. | |
- The `unproxy` command is introduced to remove a proxy configuration. | |
- The `isolated` command lists all isolated sites and their PHP versions. | |
- The `unisolate` command reverts a site back to using Valet's globally installed PHP version. | |
- The `.valet-env.php` file allows configuration of site-specific environment variables, which will be added to the global `$_SERVER` array for each site. | |
- Custom drivers can now be defined in a `LocalValetDriver.php` file within the application's root directory, allowing for application-specific configurations. | |
=== validation === | |
- **New Validation Rules**: Laravel 11 introduces several new validation rules, including `prohibited`, `prohibited_if`, `prohibited_unless`, and `prohibits`, which allow for more nuanced validation scenarios regarding the presence and emptiness of fields. | |
- **Password Validation Enhancements**: The `Password` rule object now includes methods for specifying password complexity requirements, such as `mixedCase()`, `numbers()`, `symbols()`, and `uncompromised()`, which checks against known data breaches. | |
- **Custom Validation Rules**: The process for creating custom validation rules has been streamlined with the introduction of `DataAwareRule` and `ValidatorAwareRule` interfaces, allowing custom rules to access the data being validated and the validator instance, respectively. | |
- **Implicit Rules**: Custom rules can now be defined as "implicit," meaning they will run even when the attribute is not present or is empty, provided the rule itself implies that the attribute is required. | |
- **File Validation**: The `File` rule now supports specifying file sizes using string suffixes (e.g., `1kb`, `10mb`), making it easier to define size constraints. | |
- **Warning on Language Files**: The default Laravel application skeleton does not include the `lang` directory. To customize language files, you must publish them using the `lang:publish` Artisan command. | |
- **Validation Error Response Format**: When validation fails, Laravel 11 will return a JSON response with a 422 HTTP status code, containing a structured format for error messages, including nested error keys flattened into dot notation. | |
- **Caveat on Unique Rule**: When using the `unique` rule, ensure that the ID passed to the `ignore` method is a system-generated unique ID to avoid SQL injection vulnerabilities. | |
=== verification === | |
- Laravel 11 introduces the `EmailVerificationRequest` form request type, which automatically validates the request's `id` and `hash` parameters when handling email verification. | |
- The `toMailUsing` method for customizing the verification email can now be called from the `boot` method of the `AppServiceProvider` class, allowing for more flexible email message construction. | |
- Important: When manually implementing email verification, you must define the contents of the verification notice view yourself. | |
- Important: Ensure that the route for the email verification notice is named `verification.notice`, as the `verified` middleware redirects to this route for unverified users. | |
=== views === | |
- NO_NEW_CONTENT | |
=== vite === | |
- Vite has replaced Laravel Mix in new Laravel installations. | |
- The Laravel Vite plugin requires specifying entry points for JavaScript or CSS files, including preprocessed languages like TypeScript, JSX, TSX, and Sass. | |
- When building an SPA, import CSS via JavaScript instead of specifying it as an entry point. | |
- The `detectTls` option can be specified in `vite.config.js` for HTTPS development servers. | |
- New configuration options for the Vite development server in Sail on WSL2 include setting `hmr.host` to 'localhost'. | |
- The `refresh` option in the Laravel Vite plugin can be set to automatically refresh the browser on changes to specific directories. | |
- The `Vite::prefetch` method can be used to eagerly prefetch JavaScript and CSS assets on initial page load. | |
- The `ASSET_URL` environment variable must be set if Vite compiled assets are deployed to a different domain. | |
- Environment variables can be injected into JavaScript by prefixing them with `VITE_`. | |
- The `withoutVite` method can be used to mock Vite during tests. | |
- The SSR entry point must be specified in `vite.config.js` for server-side rendering. | |
- The `useCspNonce` method can be used to add a nonce attribute to script and style tags for Content Security Policy. | |
- The `vite-plugin-manifest-sri` plugin can be installed to enable Subresource Integrity (SRI) for assets. | |
- The `useScriptTagAttributes` and `useStyleTagAttributes` methods can be used to add arbitrary attributes to script and style tags. | |
- The `transformOnServe` option can be used to correct URLs generated by plugins that expect certain behaviors in the Vite dev server. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment