diff --git a/artisan.md b/artisan.md index 2dcb9afac22..572698d11d6 100644 --- a/artisan.md +++ b/artisan.md @@ -6,14 +6,16 @@ - [Generating Commands](#generating-commands) - [Command Structure](#command-structure) - [Closure Commands](#closure-commands) + - [Isolatable Commands](#isolatable-commands) - [Defining Input Expectations](#defining-input-expectations) - [Arguments](#arguments) - [Options](#options) - [Input Arrays](#input-arrays) - [Input Descriptions](#input-descriptions) + - [Prompting for Missing Input](#prompting-for-missing-input) - [Command I/O](#command-io) - [Retrieving Input](#retrieving-input) - - [Prompting For Input](#prompting-for-input) + - [Prompting for Input](#prompting-for-input) - [Writing Output](#writing-output) - [Registering Commands](#registering-commands) - [Programmatically Executing Commands](#programmatically-executing-commands) @@ -43,13 +45,13 @@ php artisan help migrate If you are using [Laravel Sail](/docs/{{version}}/sail) as your local development environment, remember to use the `sail` command line to invoke Artisan commands. Sail will execute your Artisan commands within your application's Docker containers: ```shell -./sail artisan list +./vendor/bin/sail artisan list ``` ### Tinker (REPL) -Laravel Tinker is a powerful REPL for the Laravel framework, powered by the [PsySH](https://github.com/bobthecow/psysh) package. +[Laravel Tinker](https://github.com/laravel/tinker) is a powerful REPL for the Laravel framework, powered by the [PsySH](https://github.com/bobthecow/psysh) package. #### Installation @@ -60,7 +62,8 @@ All Laravel applications include Tinker by default. However, you may install Tin composer require laravel/tinker ``` -> {tip} Looking for a graphical UI for interacting with your Laravel application? Check out [Tinkerwell](https://tinkerwell.app)! +> [!NOTE] +> Looking for hot reloading, multiline code editing, and autocompletion when interacting with your Laravel application? Check out [Tinkerwell](https://tinkerwell.app)! #### Usage @@ -77,30 +80,35 @@ You can publish Tinker's configuration file using the `vendor:publish` command: php artisan vendor:publish --provider="Laravel\Tinker\TinkerServiceProvider" ``` -> {note} The `dispatch` helper function and `dispatch` method on the `Dispatchable` class depends on garbage collection to place the job on the queue. Therefore, when using tinker, you should use `Bus::dispatch` or `Queue::push` to dispatch jobs. +> [!WARNING] +> The `dispatch` helper function and `dispatch` method on the `Dispatchable` class depends on garbage collection to place the job on the queue. Therefore, when using tinker, you should use `Bus::dispatch` or `Queue::push` to dispatch jobs. #### Command Allow List -Tinker utilizes an "allow" list to determine which Artisan commands are allowed to be run within its shell. By default, you may run the `clear-compiled`, `down`, `env`, `inspire`, `migrate`, `optimize`, and `up` commands. If you would like to allow more commands you may add them to the `commands` array in your `tinker.php` configuration file: +Tinker utilizes an "allow" list to determine which Artisan commands are allowed to be run within its shell. By default, you may run the `clear-compiled`, `down`, `env`, `inspire`, `migrate`, `migrate:install`, `up`, and `optimize` commands. If you would like to allow more commands you may add them to the `commands` array in your `tinker.php` configuration file: - 'commands' => [ - // App\Console\Commands\ExampleCommand::class, - ], +```php +'commands' => [ + // App\Console\Commands\ExampleCommand::class, +], +``` #### Classes That Should Not Be Aliased Typically, Tinker automatically aliases classes as you interact with them in Tinker. However, you may wish to never alias some classes. You may accomplish this by listing the classes in the `dont_alias` array of your `tinker.php` configuration file: - 'dont_alias' => [ - App\Models\User::class, - ], +```php +'dont_alias' => [ + App\Models\User::class, +], +``` ## Writing Commands -In addition to the commands provided with Artisan, you may build your own custom commands. Commands are typically stored in the `app/Console/Commands` directory; however, you are free to choose your own storage location as long as your commands can be loaded by Composer. +In addition to the commands provided with Artisan, you may build your own custom commands. Commands are typically stored in the `app/Console/Commands` directory; however, you are free to choose your own storage location as long as you instruct Laravel to [scan other directories for Artisan commands](#registering-commands). ### Generating Commands @@ -118,74 +126,73 @@ After generating your command, you should define appropriate values for the `sig Let's take a look at an example command. Note that we are able to request any dependencies we need via the command's `handle` method. The Laravel [service container](/docs/{{version}}/container) will automatically inject all dependencies that are type-hinted in this method's signature: - send(User::find($this->argument('user'))); - } + $drip->send(User::find($this->argument('user'))); } +} +``` + +> [!NOTE] +> For greater code reuse, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks. In the example above, note that we inject a service class to do the "heavy lifting" of sending the e-mails. -> {tip} For greater code reuse, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks. In the example above, note that we inject a service class to do the "heavy lifting" of sending the e-mails. + +#### Exit Codes + +If nothing is returned from the `handle` method and the command executes successfully, the command will exit with a `0` exit code, indicating success. However, the `handle` method may optionally return an integer to manually specify command's exit code: + +```php +$this->error('Something went wrong.'); + +return 1; +``` + +If you would like to "fail" the command from any method within the command, you may utilize the `fail` method. The `fail` method will immediately terminate execution of the command and return an exit code of `1`: + +```php +$this->fail('Something went wrong.'); +``` ### Closure Commands -Closure based commands provide an alternative to defining console commands as classes. In the same way that route closures are an alternative to controllers, think of command closures as an alternative to command classes. Within the `commands` method of your `app/Console/Kernel.php` file, Laravel loads the `routes/console.php` file: +Closure-based commands provide an alternative to defining console commands as classes. In the same way that route closures are an alternative to controllers, think of command closures as an alternative to command classes. - /** - * Register the closure based commands for the application. - * - * @return void - */ - protected function commands() - { - require base_path('routes/console.php'); - } +Even though the `routes/console.php` file does not define HTTP routes, it defines console based entry points (routes) into your application. Within this file, you may define all of your closure-based console commands using the `Artisan::command` method. The `command` method accepts two arguments: the [command signature](#defining-input-expectations) and a closure which receives the command's arguments and options: -Even though this file does not define HTTP routes, it defines console based entry points (routes) into your application. Within this file, you may define all of your closure based console commands using the `Artisan::command` method. The `command` method accepts two arguments: the [command signature](#defining-input-expectations) and a closure which receives the command's arguments and options: - - Artisan::command('mail:send {user}', function ($user) { - $this->info("Sending email to: {$user}!"); - }); +```php +Artisan::command('mail:send {user}', function (string $user) { + $this->info("Sending email to: {$user}!"); +}); +``` The closure is bound to the underlying command instance, so you have full access to all of the helper methods you would typically be able to access on a full command class. @@ -194,21 +201,93 @@ The closure is bound to the underlying command instance, so you have full access In addition to receiving your command's arguments and options, command closures may also type-hint additional dependencies that you would like resolved out of the [service container](/docs/{{version}}/container): - use App\Models\User; - use App\Support\DripEmailer; +```php +use App\Models\User; +use App\Support\DripEmailer; +use Illuminate\Support\Facades\Artisan; - Artisan::command('mail:send {user}', function (DripEmailer $drip, $user) { - $drip->send(User::find($user)); - }); +Artisan::command('mail:send {user}', function (DripEmailer $drip, string $user) { + $drip->send(User::find($user)); +}); +``` #### Closure Command Descriptions -When defining a closure based command, you may use the `purpose` method to add a description to the command. This description will be displayed when you run the `php artisan list` or `php artisan help` commands: +When defining a closure-based command, you may use the `purpose` method to add a description to the command. This description will be displayed when you run the `php artisan list` or `php artisan help` commands: - Artisan::command('mail:send {user}', function ($user) { - // ... - })->purpose('Send a marketing email to a user'); +```php +Artisan::command('mail:send {user}', function (string $user) { + // ... +})->purpose('Send a marketing email to a user'); +``` + + +### Isolatable Commands + +> [!WARNING] +> To utilize this feature, your application must be using the `memcached`, `redis`, `dynamodb`, `database`, `file`, or `array` cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server. + +Sometimes you may wish to ensure that only one instance of a command can run at a time. To accomplish this, you may implement the `Illuminate\Contracts\Console\Isolatable` interface on your command class: + +```php + +#### Lock ID + +By default, Laravel will use the command's name to generate the string key that is used to acquire the atomic lock in your application's cache. However, you may customize this key by defining an `isolatableId` method on your Artisan command class, allowing you to integrate the command's arguments or options into the key: + +```php +/** + * Get the isolatable ID for the command. + */ +public function isolatableId(): string +{ + return $this->argument('user'); +} +``` + + +#### Lock Expiration Time + +By default, isolation locks expire after the command is finished. Or, if the command is interrupted and unable to finish, the lock will expire after one hour. However, you may adjust the lock expiration time by defining a `isolationLockExpiresAt` method on your command: + +```php +use DateTimeInterface; +use DateInterval; + +/** + * Determine when an isolation lock expires for the command. + */ +public function isolationLockExpiresAt(): DateTimeInterface|DateInterval +{ + return now()->addMinutes(5); +} +``` ## Defining Input Expectations @@ -220,32 +299,38 @@ When writing console commands, it is common to gather input from the user throug All user supplied arguments and options are wrapped in curly braces. In the following example, the command defines one required argument: `user`: - /** - * The name and signature of the console command. - * - * @var string - */ - protected $signature = 'mail:send {user}'; +```php +/** + * The name and signature of the console command. + * + * @var string + */ +protected $signature = 'mail:send {user}'; +``` You may also make arguments optional or define default values for arguments: - // Optional argument... - 'mail:send {user?}' +```php +// Optional argument... +'mail:send {user?}' - // Optional argument with default value... - 'mail:send {user=foo}' +// Optional argument with default value... +'mail:send {user=foo}' +``` ### Options Options, like arguments, are another form of user input. Options are prefixed by two hyphens (`--`) when they are provided via the command line. There are two types of options: those that receive a value and those that don't. Options that don't receive a value serve as a boolean "switch". Let's take a look at an example of this type of option: - /** - * The name and signature of the console command. - * - * @var string - */ - protected $signature = 'mail:send {user} {--queue}'; +```php +/** + * The name and signature of the console command. + * + * @var string + */ +protected $signature = 'mail:send {user} {--queue}'; +``` In this example, the `--queue` switch may be specified when calling the Artisan command. If the `--queue` switch is passed, the value of the option will be `true`. Otherwise, the value will be `false`: @@ -258,12 +343,14 @@ php artisan mail:send 1 --queue Next, let's take a look at an option that expects a value. If the user must specify a value for an option, you should suffix the option name with a `=` sign: - /** - * The name and signature of the console command. - * - * @var string - */ - protected $signature = 'mail:send {user} {--queue=}'; +```php +/** + * The name and signature of the console command. + * + * @var string + */ +protected $signature = 'mail:send {user} {--queue=}'; +``` In this example, the user may pass a value for the option like so. If the option is not specified when invoking the command, its value will be `null`: @@ -273,19 +360,23 @@ php artisan mail:send 1 --queue=default You may assign default values to options by specifying the default value after the option name. If no option value is passed by the user, the default value will be used: - 'mail:send {user} {--queue=default}' +```php +'mail:send {user} {--queue=default}' +``` #### Option Shortcuts To assign a shortcut when defining an option, you may specify it before the option name and use the `|` character as a delimiter to separate the shortcut from the full option name: - 'mail:send {user} {--Q|queue}' +```php +'mail:send {user} {--Q|queue}' +``` -When invoking the command on your terminal, option shortcuts should be prefixed with a single hyphen: +When invoking the command on your terminal, option shortcuts should be prefixed with a single hyphen and no `=` character should be included when specifying a value for the option: ```shell -php artisan mail:send 1 -Q +php artisan mail:send 1 -Qdefault ``` @@ -293,24 +384,30 @@ php artisan mail:send 1 -Q If you would like to define arguments or options to expect multiple input values, you may use the `*` character. First, let's take a look at an example that specifies such an argument: - 'mail:send {user*}' +```php +'mail:send {user*}' +``` -When calling this method, the `user` arguments may be passed in order to the command line. For example, the following command will set the value of `user` to an array with `foo` and `bar` as its values: +When running this command, the `user` arguments may be passed in order to the command line. For example, the following command will set the value of `user` to an array with `1` and `2` as its values: ```shell -php artisan mail:send foo bar +php artisan mail:send 1 2 ``` This `*` character can be combined with an optional argument definition to allow zero or more instances of an argument: - 'mail:send {user?*}' +```php +'mail:send {user?*}' +``` #### Option Arrays When defining an option that expects multiple input values, each option value passed to the command should be prefixed with the option name: - 'mail:send {user} {--id=*}' +```php +'mail:send {--id=*}' +``` Such a command may be invoked by passing multiple `--id` arguments: @@ -323,14 +420,109 @@ php artisan mail:send --id=1 --id=2 You may assign descriptions to input arguments and options by separating the argument name from the description using a colon. If you need a little extra room to define your command, feel free to spread the definition across multiple lines: +```php +/** + * The name and signature of the console command. + * + * @var string + */ +protected $signature = 'mail:send + {user : The ID of the user} + {--queue : Whether the job should be queued}'; +``` + + +### Prompting for Missing Input + +If your command contains required arguments, the user will receive an error message when they are not provided. Alternatively, you may configure your command to automatically prompt the user when required arguments are missing by implementing the `PromptsForMissingInput` interface: + +```php + + */ +protected function promptForMissingArgumentsUsing(): array +{ + return [ + 'user' => 'Which user ID should receive the mail?', + ]; +} +``` + +You may also provide placeholder text by using a tuple containing the question and placeholder: + +```php +return [ + 'user' => ['Which user ID should receive the mail?', 'E.g. 123'], +]; +``` + +If you would like complete control over the prompt, you may provide a closure that should prompt the user and return their answer: + +```php +use App\Models\User; +use function Laravel\Prompts\search; + +// ... + +return [ + 'user' => fn () => search( + label: 'Search for a user:', + placeholder: 'E.g. Taylor Otwell', + options: fn ($value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [] + ), +]; +``` + +> [!NOTE] +The comprehensive [Laravel Prompts](/docs/{{version}}/prompts) documentation includes additional information on the available prompts and their usage. + +If you wish to prompt the user to select or enter [options](#options), you may include prompts in your command's `handle` method. However, if you only wish to prompt the user when they have also been automatically prompted for missing arguments, then you may implement the `afterPromptingForMissingArguments` method: + +```php +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use function Laravel\Prompts\confirm; + +// ... + +/** + * Perform actions after the user was prompted for missing arguments. + */ +protected function afterPromptingForMissingArguments(InputInterface $input, OutputInterface $output): void +{ + $input->setOption('queue', confirm( + label: 'Would you like to queue the mail?', + default: $this->option('queue') + )); +} +``` ## Command I/O @@ -340,328 +532,372 @@ You may assign descriptions to input arguments and options by separating the arg While your command is executing, you will likely need to access the values for the arguments and options accepted by your command. To do so, you may use the `argument` and `option` methods. If an argument or option does not exist, `null` will be returned: - /** - * Execute the console command. - * - * @return int - */ - public function handle() - { - $userId = $this->argument('user'); - - // - } +```php +/** + * Execute the console command. + */ +public function handle(): void +{ + $userId = $this->argument('user'); +} +``` If you need to retrieve all of the arguments as an `array`, call the `arguments` method: - $arguments = $this->arguments(); +```php +$arguments = $this->arguments(); +``` Options may be retrieved just as easily as arguments using the `option` method. To retrieve all of the options as an array, call the `options` method: - // Retrieve a specific option... - $queueName = $this->option('queue'); +```php +// Retrieve a specific option... +$queueName = $this->option('queue'); - // Retrieve all options as an array... - $options = $this->options(); +// Retrieve all options as an array... +$options = $this->options(); +``` -### Prompting For Input +### Prompting for Input + +> [!NOTE] +> [Laravel Prompts](/docs/{{version}}/prompts) is a PHP package for adding beautiful and user-friendly forms to your command-line applications, with browser-like features including placeholder text and validation. In addition to displaying output, you may also ask the user to provide input during the execution of your command. The `ask` method will prompt the user with the given question, accept their input, and then return the user's input back to your command: - /** - * Execute the console command. - * - * @return mixed - */ - public function handle() - { - $name = $this->ask('What is your name?'); - } +```php +/** + * Execute the console command. + */ +public function handle(): void +{ + $name = $this->ask('What is your name?'); + + // ... +} +``` + +The `ask` method also accepts an optional second argument which specifies the default value that should be returned if no user input is provided: + +```php +$name = $this->ask('What is your name?', 'Taylor'); +``` The `secret` method is similar to `ask`, but the user's input will not be visible to them as they type in the console. This method is useful when asking for sensitive information such as passwords: - $password = $this->secret('What is the password?'); +```php +$password = $this->secret('What is the password?'); +``` -#### Asking For Confirmation +#### Asking for Confirmation If you need to ask the user for a simple "yes or no" confirmation, you may use the `confirm` method. By default, this method will return `false`. However, if the user enters `y` or `yes` in response to the prompt, the method will return `true`. - if ($this->confirm('Do you wish to continue?')) { - // - } +```php +if ($this->confirm('Do you wish to continue?')) { + // ... +} +``` If necessary, you may specify that the confirmation prompt should return `true` by default by passing `true` as the second argument to the `confirm` method: - if ($this->confirm('Do you wish to continue?', true)) { - // - } +```php +if ($this->confirm('Do you wish to continue?', true)) { + // ... +} +``` #### Auto-Completion The `anticipate` method can be used to provide auto-completion for possible choices. The user can still provide any answer, regardless of the auto-completion hints: - $name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']); +```php +$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']); +``` Alternatively, you may pass a closure as the second argument to the `anticipate` method. The closure will be called each time the user types an input character. The closure should accept a string parameter containing the user's input so far, and return an array of options for auto-completion: - $name = $this->anticipate('What is your address?', function ($input) { - // Return auto-completion options... - }); +```php +use App\Models\Address; + +$name = $this->anticipate('What is your address?', function (string $input) { + return Address::whereLike('name', "{$input}%") + ->limit(5) + ->pluck('name') + ->all(); +}); +``` #### Multiple Choice Questions If you need to give the user a predefined set of choices when asking a question, you may use the `choice` method. You may set the array index of the default value to be returned if no option is chosen by passing the index as the third argument to the method: - $name = $this->choice( - 'What is your name?', - ['Taylor', 'Dayle'], - $defaultIndex - ); +```php +$name = $this->choice( + 'What is your name?', + ['Taylor', 'Dayle'], + $defaultIndex +); +``` In addition, the `choice` method accepts optional fourth and fifth arguments for determining the maximum number of attempts to select a valid response and whether multiple selections are permitted: - $name = $this->choice( - 'What is your name?', - ['Taylor', 'Dayle'], - $defaultIndex, - $maxAttempts = null, - $allowMultipleSelections = false - ); +```php +$name = $this->choice( + 'What is your name?', + ['Taylor', 'Dayle'], + $defaultIndex, + $maxAttempts = null, + $allowMultipleSelections = false +); +``` ### Writing Output -To send output to the console, you may use the `line`, `info`, `comment`, `question`, `warn`, and `error` methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let's display some general information to the user. Typically, the `info` method will display in the console as green colored text: +To send output to the console, you may use the `line`, `newLine`, `info`, `comment`, `question`, `warn`, `alert`, and `error` methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let's display some general information to the user. Typically, the `info` method will display in the console as green colored text: - /** - * Execute the console command. - * - * @return mixed - */ - public function handle() - { - // ... +```php +/** + * Execute the console command. + */ +public function handle(): void +{ + // ... - $this->info('The command was successful!'); - } + $this->info('The command was successful!'); +} +``` To display an error message, use the `error` method. Error message text is typically displayed in red: - $this->error('Something went wrong!'); +```php +$this->error('Something went wrong!'); +``` You may use the `line` method to display plain, uncolored text: - $this->line('Display this on the screen'); +```php +$this->line('Display this on the screen'); +``` You may use the `newLine` method to display a blank line: - // Write a single blank line... - $this->newLine(); +```php +// Write a single blank line... +$this->newLine(); - // Write three blank lines... - $this->newLine(3); +// Write three blank lines... +$this->newLine(3); +``` #### Tables -The `table` method makes it easy to correctly format multiple rows / columns of data. All you need to do is provide the column names and the data for the table and Laravel will -automatically calculate the appropriate width and height of the table for you: +The `table` method makes it easy to correctly format multiple rows / columns of data. All you need to do is provide the column names and the data for the table and Laravel will automatically calculate the appropriate width and height of the table for you: - use App\Models\User; +```php +use App\Models\User; - $this->table( - ['Name', 'Email'], - User::all(['name', 'email'])->toArray() - ); +$this->table( + ['Name', 'Email'], + User::all(['name', 'email'])->toArray() +); +``` #### Progress Bars For long running tasks, it can be helpful to show a progress bar that informs users how complete the task is. Using the `withProgressBar` method, Laravel will display a progress bar and advance its progress for each iteration over a given iterable value: - use App\Models\User; +```php +use App\Models\User; - $users = $this->withProgressBar(User::all(), function ($user) { - $this->performTask($user); - }); +$users = $this->withProgressBar(User::all(), function (User $user) { + $this->performTask($user); +}); +``` Sometimes, you may need more manual control over how a progress bar is advanced. First, define the total number of steps the process will iterate through. Then, advance the progress bar after processing each item: - $users = App\Models\User::all(); +```php +$users = App\Models\User::all(); - $bar = $this->output->createProgressBar(count($users)); +$bar = $this->output->createProgressBar(count($users)); - $bar->start(); +$bar->start(); - foreach ($users as $user) { - $this->performTask($user); +foreach ($users as $user) { + $this->performTask($user); - $bar->advance(); - } + $bar->advance(); +} - $bar->finish(); +$bar->finish(); +``` -> {tip} For more advanced options, check out the [Symfony Progress Bar component documentation](https://symfony.com/doc/current/components/console/helpers/progressbar.html). +> [!NOTE] +> For more advanced options, check out the [Symfony Progress Bar component documentation](https://symfony.com/doc/current/components/console/helpers/progressbar.html). ## Registering Commands -All of your console commands are registered within your application's `App\Console\Kernel` class, which is your application's "console kernel". Within the `commands` method of this class, you will see a call to the kernel's `load` method. The `load` method will scan the `app/Console/Commands` directory and automatically register each command it contains with Artisan. You are even free to make additional calls to the `load` method to scan other directories for Artisan commands: +By default, Laravel automatically registers all commands within the `app/Console/Commands` directory. However, you can instruct Laravel to scan other directories for Artisan commands using the `withCommands` method in your application's `bootstrap/app.php` file: - /** - * Register the commands for the application. - * - * @return void - */ - protected function commands() - { - $this->load(__DIR__.'/Commands'); - $this->load(__DIR__.'/../Domain/Orders/Commands'); +```php +->withCommands([ + __DIR__.'/../app/Domain/Orders/Commands', +]) +``` - // ... - } +If necessary, you may also manually register commands by providing the command's class name to the `withCommands` method: -If necessary, you may manually register commands by adding the command's class name to a `$commands` property within your `App\Console\Kernel` class. If this property is not already defined on your kernel, you should define it manually. When Artisan boots, all the commands listed in this property will be resolved by the [service container](/docs/{{version}}/container) and registered with Artisan: +```php +use App\Domain\Orders\Commands\SendEmails; - protected $commands = [ - Commands\SendEmails::class - ]; +->withCommands([ + SendEmails::class, +]) +``` + +When Artisan boots, all the commands in your application will be resolved by the [service container](/docs/{{version}}/container) and registered with Artisan. ## Programmatically Executing Commands Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to execute an Artisan command from a route or controller. You may use the `call` method on the `Artisan` facade to accomplish this. The `call` method accepts either the command's signature name or class name as its first argument, and an array of command parameters as the second argument. The exit code will be returned: - use Illuminate\Support\Facades\Artisan; +```php +use Illuminate\Support\Facades\Artisan; +use Illuminate\Support\Facades\Route; - Route::post('/user/{user}/mail', function ($user) { - $exitCode = Artisan::call('mail:send', [ - 'user' => $user, '--queue' => 'default' - ]); +Route::post('/user/{user}/mail', function (string $user) { + $exitCode = Artisan::call('mail:send', [ + 'user' => $user, '--queue' => 'default' + ]); - // - }); + // ... +}); +``` Alternatively, you may pass the entire Artisan command to the `call` method as a string: - Artisan::call('mail:send 1 --queue=default'); +```php +Artisan::call('mail:send 1 --queue=default'); +``` #### Passing Array Values If your command defines an option that accepts an array, you may pass an array of values to that option: - use Illuminate\Support\Facades\Artisan; +```php +use Illuminate\Support\Facades\Artisan; +use Illuminate\Support\Facades\Route; - Route::post('/mail', function () { - $exitCode = Artisan::call('mail:send', [ - '--id' => [5, 13] - ]); - }); +Route::post('/mail', function () { + $exitCode = Artisan::call('mail:send', [ + '--id' => [5, 13] + ]); +}); +``` #### Passing Boolean Values If you need to specify the value of an option that does not accept string values, such as the `--force` flag on the `migrate:refresh` command, you should pass `true` or `false` as the value of the option: - $exitCode = Artisan::call('migrate:refresh', [ - '--force' => true, - ]); +```php +$exitCode = Artisan::call('migrate:refresh', [ + '--force' => true, +]); +``` #### Queueing Artisan Commands Using the `queue` method on the `Artisan` facade, you may even queue Artisan commands so they are processed in the background by your [queue workers](/docs/{{version}}/queues). Before using this method, make sure you have configured your queue and are running a queue listener: - use Illuminate\Support\Facades\Artisan; +```php +use Illuminate\Support\Facades\Artisan; +use Illuminate\Support\Facades\Route; - Route::post('/user/{user}/mail', function ($user) { - Artisan::queue('mail:send', [ - 'user' => $user, '--queue' => 'default' - ]); +Route::post('/user/{user}/mail', function (string $user) { + Artisan::queue('mail:send', [ + 'user' => $user, '--queue' => 'default' + ]); - // - }); + // ... +}); +``` Using the `onConnection` and `onQueue` methods, you may specify the connection or queue the Artisan command should be dispatched to: - Artisan::queue('mail:send', [ - 'user' => 1, '--queue' => 'default' - ])->onConnection('redis')->onQueue('commands'); +```php +Artisan::queue('mail:send', [ + 'user' => 1, '--queue' => 'default' +])->onConnection('redis')->onQueue('commands'); +``` ### Calling Commands From Other Commands Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the `call` method. This `call` method accepts the command name and an array of command arguments / options: - /** - * Execute the console command. - * - * @return mixed - */ - public function handle() - { - $this->call('mail:send', [ - 'user' => 1, '--queue' => 'default' - ]); +```php +/** + * Execute the console command. + */ +public function handle(): void +{ + $this->call('mail:send', [ + 'user' => 1, '--queue' => 'default' + ]); - // - } + // ... +} +``` If you would like to call another console command and suppress all of its output, you may use the `callSilently` method. The `callSilently` method has the same signature as the `call` method: - $this->callSilently('mail:send', [ - 'user' => 1, '--queue' => 'default' - ]); +```php +$this->callSilently('mail:send', [ + 'user' => 1, '--queue' => 'default' +]); +``` ## Signal Handling -The Symfony Console component, which powers the Artisan console, allows you to indicate which process signals (if any) your command handles. For example, you may indicate that your command handles the `SIGINT` and `SIGTERM` signals. - -To get started, you should implement the `Symfony\Component\Console\Command\SignalableCommandInterface` interface on your Artisan command class. This interface requires you to define two methods: `getSubscribedSignals` and `handleSignal`: +As you may know, operating systems allow signals to be sent to running processes. For example, the `SIGTERM` signal is how operating systems ask a program to terminate. If you wish to listen for signals in your Artisan console commands and execute code when they occur, you may use the `trap` method: ```php -trap(SIGTERM, fn () => $this->shouldKeepRunning = false); - /** - * Handle an incoming signal. - * - * @param int $signal - * @return void - */ - public function handleSignal(int $signal): void - { - if ($signal === SIGINT) { - $this->stopServer(); - - return; - } + while ($this->shouldKeepRunning) { + // ... } } ``` -As you might expect, the `getSubscribedSignals` method should return an array of the signals that your command can handle, while the `handleSignal` method receives the signal and can respond accordingly. +To listen for multiple signals at once, you may provide an array of signals to the `trap` method: + +```php +$this->trap([SIGTERM, SIGQUIT], function (int $signal) { + $this->shouldKeepRunning = false; + + dump($signal); // SIGTERM / SIGQUIT +}); +``` ## Stub Customization diff --git a/authentication.md b/authentication.md index bc107f6f329..fead07de08a 100644 --- a/authentication.md +++ b/authentication.md @@ -5,8 +5,8 @@ - [Database Considerations](#introduction-database-considerations) - [Ecosystem Overview](#ecosystem-overview) - [Authentication Quickstart](#authentication-quickstart) - - [Install A Starter Kit](#install-a-starter-kit) - - [Retrieving The Authenticated User](#retrieving-the-authenticated-user) + - [Install a Starter Kit](#install-a-starter-kit) + - [Retrieving the Authenticated User](#retrieving-the-authenticated-user) - [Protecting Routes](#protecting-routes) - [Login Throttling](#login-throttling) - [Manually Authenticating Users](#authenticating-users) @@ -15,7 +15,7 @@ - [HTTP Basic Authentication](#http-basic-authentication) - [Stateless HTTP Basic Authentication](#stateless-http-basic-authentication) - [Logging Out](#logging-out) - - [Invalidating Sessions On Other Devices](#invalidating-sessions-on-other-devices) + - [Invalidating Sessions on Other Devices](#invalidating-sessions-on-other-devices) - [Password Confirmation](#password-confirmation) - [Configuration](#password-confirmation-configuration) - [Routing](#password-confirmation-routing) @@ -25,6 +25,7 @@ - [Adding Custom User Providers](#adding-custom-user-providers) - [The User Provider Contract](#the-user-provider-contract) - [The Authenticatable Contract](#the-authenticatable-contract) +- [Automatic Password Rehashing](#automatic-password-rehashing) - [Social Authentication](/docs/{{version}}/socialite) - [Events](#events) @@ -39,19 +40,22 @@ Providers define how users are retrieved from your persistent storage. Laravel s Your application's authentication configuration file is located at `config/auth.php`. This file contains several well-documented options for tweaking the behavior of Laravel's authentication services. -> {tip} Guards and providers should not be confused with "roles" and "permissions". To learn more about authorizing user actions via permissions, please refer to the [authorization](/docs/{{version}}/authorization) documentation. +> [!NOTE] +> Guards and providers should not be confused with "roles" and "permissions". To learn more about authorizing user actions via permissions, please refer to the [authorization](/docs/{{version}}/authorization) documentation. ### Starter Kits Want to get started fast? Install a [Laravel application starter kit](/docs/{{version}}/starter-kits) in a fresh Laravel application. After migrating your database, navigate your browser to `/register` or any other URL that is assigned to your application. The starter kits will take care of scaffolding your entire authentication system! -**Even if you choose not to use a starter kit in your final Laravel application, installing the [Laravel Breeze](/docs/{{version}}/starter-kits#laravel-breeze) starter kit can be a wonderful opportunity to learn how to implement all of Laravel's authentication functionality in an actual Laravel project.** Since Laravel Breeze creates authentication controllers, routes, and views for you, you can examine the code within these files to learn how Laravel's authentication features may be implemented. +**Even if you choose not to use a starter kit in your final Laravel application, installing a [starter kit](/docs/{{version}}/starter-kits) can be a wonderful opportunity to learn how to implement all of Laravel's authentication functionality in an actual Laravel project.** Since the Laravel starter kits contain authentication controllers, routes, and views for you, you can examine the code within these files to learn how Laravel's authentication features may be implemented. ### Database Considerations -By default, Laravel includes an `App\Models\User` [Eloquent model](/docs/{{version}}/eloquent) in your `app/Models` directory. This model may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the `database` authentication provider which uses the Laravel query builder. +By default, Laravel includes an `App\Models\User` [Eloquent model](/docs/{{version}}/eloquent) in your `app/Models` directory. This model may be used with the default Eloquent authentication driver. + +If your application is not using Eloquent, you may use the `database` authentication provider which uses the Laravel query builder. If your application is using MongoDB, check out MongoDB's official [Laravel user authentication documentation](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/user-authentication/). When building the database schema for the `App\Models\User` model, make sure the password column is at least 60 characters in length. Of course, the `users` table migration that is included in new Laravel applications already creates a column that exceeds this length. @@ -73,13 +77,7 @@ Laravel includes built-in authentication and session services which are typicall **Application Starter Kits** -As discussed in this documentation, you can interact with these authentication services manually to build your application's own authentication layer. However, to help you get started more quickly, we have released [free packages](/docs/{{version}}/starter-kits) that provide robust, modern scaffolding of the entire authentication layer. These packages are [Laravel Breeze](/docs/{{version}}/starter-kits#laravel-breeze), [Laravel Jetstream](/docs/{{version}}/starter-kits#laravel-jetstream), and [Laravel Fortify](/docs/{{version}}/fortify). - -_Laravel Breeze_ is a simple, minimal implementation of all of Laravel's authentication features, including login, registration, password reset, email verification, and password confirmation. Laravel Breeze's view layer is comprised of simple [Blade templates](/docs/{{version}}/blade) styled with [Tailwind CSS](https://tailwindcss.com). To get started, check out the documentation on Laravel's [application starter kits](/docs/{{version}}/starter-kits). - -_Laravel Fortify_ is a headless authentication backend for Laravel that implements many of the features found in this documentation, including cookie-based authentication as well as other features such as two-factor authentication and email verification. Fortify provides the authentication backend for Laravel Jetstream or may be used independently in combination with [Laravel Sanctum](/docs/{{version}}/sanctum) to provide authentication for an SPA that needs to authenticate with Laravel. - -_[Laravel Jetstream](https://jetstream.laravel.com)_ is a robust application starter kit that consumes and exposes Laravel Fortify's authentication services with a beautiful, modern UI powered by [Tailwind CSS](https://tailwindcss.com), [Livewire](https://laravel-livewire.com), and / or [Inertia.js](https://inertiajs.com). Laravel Jetstream includes optional support for two-factor authentication, team support, browser session management, profile management, and built-in integration with [Laravel Sanctum](/docs/{{version}}/sanctum) to offer API token authentication. Laravel's API authentication offerings are discussed below. +As discussed in this documentation, you can interact with these authentication services manually to build your application's own authentication layer. However, to help you get started more quickly, we have released [free starter kits](/docs/{{version}}/starter-kits) that provide robust, modern scaffolding of the entire authentication layer. #### Laravel's API Authentication Services @@ -96,10 +94,8 @@ In response to the complexity of OAuth2 and developer confusion, we set out to b Laravel Sanctum is a hybrid web / API authentication package that can manage your application's entire authentication process. This is possible because when Sanctum based applications receive a request, Sanctum will first determine if the request includes a session cookie that references an authenticated session. Sanctum accomplishes this by calling Laravel's built-in authentication services which we discussed earlier. If the request is not being authenticated via a session cookie, Sanctum will inspect the request for an API token. If an API token is present, Sanctum will authenticate the request using that token. To learn more about this process, please consult Sanctum's ["how it works"](/docs/{{version}}/sanctum#how-it-works) documentation. -Laravel Sanctum is the API package we have chosen to include with the [Laravel Jetstream](https://jetstream.laravel.com) application starter kit because we believe it is the best fit for the majority of web application's authentication needs. - -#### Summary & Choosing Your Stack +#### Summary and Choosing Your Stack In summary, if your application will be accessed using a browser and you are building a monolithic Laravel application, your application will use Laravel's built-in authentication services. @@ -109,110 +105,137 @@ If you are building a single-page application (SPA) that will be powered by a La Passport may be chosen when your application absolutely needs all of the features provided by the OAuth2 specification. -And, if you would like to get started quickly, we are pleased to recommend [Laravel Jetstream](https://jetstream.laravel.com) as a quick way to start a new Laravel application that already uses our preferred authentication stack of Laravel's built-in authentication services and Laravel Sanctum. +And, if you would like to get started quickly, we are pleased to recommend [our application starter kits](/docs/{{version}}/starter-kits) as a quick way to start a new Laravel application that already uses our preferred authentication stack of Laravel's built-in authentication services. ## Authentication Quickstart -> {note} This portion of the documentation discusses authenticating users via the [Laravel application starter kits](/docs/{{version}}/starter-kits), which includes UI scaffolding to help you get started quickly. If you would like to integrate with Laravel's authentication systems directly, check out the documentation on [manually authenticating users](#authenticating-users). +> [!WARNING] +> This portion of the documentation discusses authenticating users via the [Laravel application starter kits](/docs/{{version}}/starter-kits), which includes UI scaffolding to help you get started quickly. If you would like to integrate with Laravel's authentication systems directly, check out the documentation on [manually authenticating users](#authenticating-users). -### Install A Starter Kit +### Install a Starter Kit -First, you should [install a Laravel application starter kit](/docs/{{version}}/starter-kits). Our current starter kits, Laravel Breeze and Laravel Jetstream, offer beautifully designed starting points for incorporating authentication into your fresh Laravel application. - -Laravel Breeze is a minimal, simple implementation of all of Laravel's authentication features, including login, registration, password reset, email verification, and password confirmation. Laravel Breeze's view layer is made up of simple [Blade templates](/docs/{{version}}/blade) styled with [Tailwind CSS](https://tailwindcss.com). Breeze also offers an [Inertia](https://inertiajs.com) based scaffolding option using Vue or React. - -[Laravel Jetstream](https://jetstream.laravel.com) is a more robust application starter kit that includes support for scaffolding your application with [Livewire](https://laravel-livewire.com) or [Inertia.js and Vue](https://inertiajs.com). In addition, Jetstream features optional support for two-factor authentication, teams, profile management, browser session management, API support via [Laravel Sanctum](/docs/{{version}}/sanctum), account deletion, and more. +First, you should [install a Laravel application starter kit](/docs/{{version}}/starter-kits). Our starter kits offer beautifully designed starting points for incorporating authentication into your fresh Laravel application. -### Retrieving The Authenticated User +### Retrieving the Authenticated User -After installing an authentication starter kit and allowing users to register and authenticate with your application, you will often need to interact with the currently authenticated user. While handling an incoming request, you may access the authenticated user via the `Auth` facade's `user` method: +After creating an application from a starter kit and allowing users to register and authenticate with your application, you will often need to interact with the currently authenticated user. While handling an incoming request, you may access the authenticated user via the `Auth` facade's `user` method: - use Illuminate\Support\Facades\Auth; +```php +use Illuminate\Support\Facades\Auth; - // Retrieve the currently authenticated user... - $user = Auth::user(); +// Retrieve the currently authenticated user... +$user = Auth::user(); - // Retrieve the currently authenticated user's ID... - $id = Auth::id(); +// Retrieve the currently authenticated user's ID... +$id = Auth::id(); +``` Alternatively, once a user is authenticated, you may access the authenticated user via an `Illuminate\Http\Request` instance. Remember, type-hinted classes will automatically be injected into your controller methods. By type-hinting the `Illuminate\Http\Request` object, you may gain convenient access to the authenticated user from any controller method in your application via the request's `user` method: - user() - } + $user = $request->user(); + + // ... + + return redirect('/flights'); } +} +``` -#### Determining If The Current User Is Authenticated +#### Determining if the Current User is Authenticated To determine if the user making the incoming HTTP request is authenticated, you may use the `check` method on the `Auth` facade. This method will return `true` if the user is authenticated: - use Illuminate\Support\Facades\Auth; +```php +use Illuminate\Support\Facades\Auth; - if (Auth::check()) { - // The user is logged in... - } +if (Auth::check()) { + // The user is logged in... +} +``` -> {tip} Even though it is possible to determine if a user is authenticated using the `check` method, you will typically use a middleware to verify that the user is authenticated before allowing the user access to certain routes / controllers. To learn more about this, check out the documentation on [protecting routes](/docs/{{version}}/authentication#protecting-routes). +> [!NOTE] +> Even though it is possible to determine if a user is authenticated using the `check` method, you will typically use a middleware to verify that the user is authenticated before allowing the user access to certain routes / controllers. To learn more about this, check out the documentation on [protecting routes](/docs/{{version}}/authentication#protecting-routes). ### Protecting Routes -[Route middleware](/docs/{{version}}/middleware) can be used to only allow authenticated users to access a given route. Laravel ships with an `auth` middleware, which references the `Illuminate\Auth\Middleware\Authenticate` class. Since this middleware is already registered in your application's HTTP kernel, all you need to do is attach the middleware to a route definition: +[Route middleware](/docs/{{version}}/middleware) can be used to only allow authenticated users to access a given route. Laravel ships with an `auth` middleware, which is a [middleware alias](/docs/{{version}}/middleware#middleware-aliases) for the `Illuminate\Auth\Middleware\Authenticate` class. Since this middleware is already aliased internally by Laravel, all you need to do is attach the middleware to a route definition: - Route::get('/flights', function () { - // Only authenticated users may access this route... - })->middleware('auth'); +```php +Route::get('/flights', function () { + // Only authenticated users may access this route... +})->middleware('auth'); +``` #### Redirecting Unauthenticated Users -When the `auth` middleware detects an unauthenticated user, it will redirect the user to the `login` [named route](/docs/{{version}}/routing#named-routes). You may modify this behavior by updating the `redirectTo` function in your application's `app/Http/Middleware/Authenticate.php` file: +When the `auth` middleware detects an unauthenticated user, it will redirect the user to the `login` [named route](/docs/{{version}}/routing#named-routes). You may modify this behavior using the `redirectGuestsTo` method within your application's `bootstrap/app.php` file: - /** - * Get the path the user should be redirected to. - * - * @param \Illuminate\Http\Request $request - * @return string - */ - protected function redirectTo($request) - { - return route('login'); - } +```php +use Illuminate\Http\Request; + +->withMiddleware(function (Middleware $middleware): void { + $middleware->redirectGuestsTo('/login'); + + // Using a closure... + $middleware->redirectGuestsTo(fn (Request $request) => route('login')); +}) +``` + + +#### Redirecting Authenticated Users + +When the `guest` middleware detects an authenticated user, it will redirect the user to the `dashboard` or `home` named route. You may modify this behavior using the `redirectUsersTo` method within your application's `bootstrap/app.php` file: + +```php +use Illuminate\Http\Request; + +->withMiddleware(function (Middleware $middleware): void { + $middleware->redirectUsersTo('/panel'); + + // Using a closure... + $middleware->redirectUsersTo(fn (Request $request) => route('panel')); +}) +``` -#### Specifying A Guard +#### Specifying a Guard When attaching the `auth` middleware to a route, you may also specify which "guard" should be used to authenticate the user. The guard specified should correspond to one of the keys in the `guards` array of your `auth.php` configuration file: - Route::get('/flights', function () { - // Only authenticated users may access this route... - })->middleware('auth:admin'); +```php +Route::get('/flights', function () { + // Only authenticated users may access this route... +})->middleware('auth:admin'); +``` ### Login Throttling -If you are using the Laravel Breeze or Laravel Jetstream [starter kits](/docs/{{version}}/starter-kits), rate limiting will automatically be applied to login attempts. By default, the user will not be able to login for one minute if they fail to provide the correct credentials after several attempts. The throttling is unique to the user's username / email address and their IP address. +If you are using one of our [application starter kits](/docs/{{version}}/starter-kits), rate limiting will automatically be applied to login attempts. By default, the user will not be able to login for one minute if they fail to provide the correct credentials after several attempts. The throttling is unique to the user's username / email address and their IP address. -> {tip} If you would like to rate limit other routes in your application, check out the [rate limiting documentation](/docs/{{version}}/routing#rate-limiting). +> [!NOTE] +> If you would like to rate limit other routes in your application, check out the [rate limiting documentation](/docs/{{version}}/routing#rate-limiting). ## Manually Authenticating Users @@ -221,39 +244,39 @@ You are not required to use the authentication scaffolding included with Laravel We will access Laravel's authentication services via the `Auth` [facade](/docs/{{version}}/facades), so we'll need to make sure to import the `Auth` facade at the top of the class. Next, let's check out the `attempt` method. The `attempt` method is normally used to handle authentication attempts from your application's "login" form. If authentication is successful, you should regenerate the user's [session](/docs/{{version}}/session) to prevent [session fixation](https://en.wikipedia.org/wiki/Session_fixation): - validate([ - 'email' => ['required', 'email'], - 'password' => ['required'], - ]); - - if (Auth::attempt($credentials)) { - $request->session()->regenerate(); - - return redirect()->intended('dashboard'); - } - - return back()->withErrors([ - 'email' => 'The provided credentials do not match our records.', - ]); + $credentials = $request->validate([ + 'email' => ['required', 'email'], + 'password' => ['required'], + ]); + + if (Auth::attempt($credentials)) { + $request->session()->regenerate(); + + return redirect()->intended('dashboard'); } + + return back()->withErrors([ + 'email' => 'The provided credentials do not match our records.', + ])->onlyInput('email'); } +} +``` The `attempt` method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the `email` column. If the user is found, the hashed password stored in the database will be compared with the `password` value passed to the method via the array. You should not hash the incoming request's `password` value, since the framework will automatically hash the value before comparing it to the hashed password in the database. An authenticated session will be started for the user if the two hashed passwords match. @@ -268,11 +291,41 @@ The `intended` method provided by Laravel's redirector will redirect the user to If you wish, you may also add extra query conditions to the authentication query in addition to the user's email and password. To accomplish this, we may simply add the query conditions to the array passed to the `attempt` method. For example, we may verify that the user is marked as "active": - if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) { - // Authentication was successful... - } +```php +if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) { + // Authentication was successful... +} +``` + +For complex query conditions, you may provide a closure in your array of credentials. This closure will be invoked with the query instance, allowing you to customize the query based on your application's needs: + +```php +use Illuminate\Database\Eloquent\Builder; + +if (Auth::attempt([ + 'email' => $email, + 'password' => $password, + fn (Builder $query) => $query->has('activeSubscription'), +])) { + // Authentication was successful... +} +``` -> {note} In these examples, `email` is not a required option, it is merely used as an example. You should use whatever column name corresponds to a "username" in your database table. +> [!WARNING] +> In these examples, `email` is not a required option, it is merely used as an example. You should use whatever column name corresponds to a "username" in your database table. + +The `attemptWhen` method, which receives a closure as its second argument, may be used to perform more extensive inspection of the potential user before actually authenticating the user. The closure receives the potential user and should return `true` or `false` to indicate if the user may be authenticated: + +```php +if (Auth::attemptWhen([ + 'email' => $email, + 'password' => $password, +], function (User $user) { + return $user->isNotBanned(); +})) { + // Authentication was successful... +} +``` #### Accessing Specific Guard Instances @@ -281,9 +334,11 @@ Via the `Auth` facade's `guard` method, you may specify which guard instance you The guard name passed to the `guard` method should correspond to one of the guards configured in your `auth.php` configuration file: - if (Auth::guard('admin')->attempt($credentials)) { - // ... - } +```php +if (Auth::guard('admin')->attempt($credentials)) { + // ... +} +``` ### Remembering Users @@ -292,67 +347,93 @@ Many web applications provide a "remember me" checkbox on their login form. If y When this value is `true`, Laravel will keep the user authenticated indefinitely or until they manually logout. Your `users` table must include the string `remember_token` column, which will be used to store the "remember me" token. The `users` table migration included with new Laravel applications already includes this column: - use Illuminate\Support\Facades\Auth; +```php +use Illuminate\Support\Facades\Auth; - if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) { - // The user is being remembered... - } +if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) { + // The user is being remembered... +} +``` + +If your application offers "remember me" functionality, you may use the `viaRemember` method to determine if the currently authenticated user was authenticated using the "remember me" cookie: + +```php +use Illuminate\Support\Facades\Auth; + +if (Auth::viaRemember()) { + // ... +} +``` ### Other Authentication Methods -#### Authenticate A User Instance +#### Authenticate a User Instance If you need to set an existing user instance as the currently authenticated user, you may pass the user instance to the `Auth` facade's `login` method. The given user instance must be an implementation of the `Illuminate\Contracts\Auth\Authenticatable` [contract](/docs/{{version}}/contracts). The `App\Models\User` model included with Laravel already implements this interface. This method of authentication is useful when you already have a valid user instance, such as directly after a user registers with your application: - use Illuminate\Support\Facades\Auth; +```php +use Illuminate\Support\Facades\Auth; - Auth::login($user); +Auth::login($user); +``` You may pass a boolean value as the second argument to the `login` method. This value indicates if "remember me" functionality is desired for the authenticated session. Remember, this means that the session will be authenticated indefinitely or until the user manually logs out of the application: - Auth::login($user, $remember = true); +```php +Auth::login($user, $remember = true); +``` If needed, you may specify an authentication guard before calling the `login` method: - Auth::guard('admin')->login($user); +```php +Auth::guard('admin')->login($user); +``` -#### Authenticate A User By ID +#### Authenticate a User by ID To authenticate a user using their database record's primary key, you may use the `loginUsingId` method. This method accepts the primary key of the user you wish to authenticate: - Auth::loginUsingId(1); +```php +Auth::loginUsingId(1); +``` -You may pass a boolean value as the second argument to the `loginUsingId` method. This value indicates if "remember me" functionality is desired for the authenticated session. Remember, this means that the session will be authenticated indefinitely or until the user manually logs out of the application: +You may pass a boolean value to the `remember` argument of the `loginUsingId` method. This value indicates if "remember me" functionality is desired for the authenticated session. Remember, this means that the session will be authenticated indefinitely or until the user manually logs out of the application: - Auth::loginUsingId(1, $remember = true); +```php +Auth::loginUsingId(1, remember: true); +``` -#### Authenticate A User Once +#### Authenticate a User Once -You may use the `once` method to authenticate a user with the application for a single request. No sessions or cookies will be utilized when calling this method: +You may use the `once` method to authenticate a user with the application for a single request. No sessions or cookies will be utilized when calling this method, and the `Login` event will not be dispatched: - if (Auth::once($credentials)) { - // - } +```php +if (Auth::once($credentials)) { + // ... +} +``` ## HTTP Basic Authentication [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) provides a quick way to authenticate users of your application without setting up a dedicated "login" page. To get started, attach the `auth.basic` [middleware](/docs/{{version}}/middleware) to a route. The `auth.basic` middleware is included with the Laravel framework, so you do not need to define it: - Route::get('/profile', function () { - // Only authenticated users may access this route... - })->middleware('auth.basic'); +```php +Route::get('/profile', function () { + // Only authenticated users may access this route... +})->middleware('auth.basic'); +``` Once the middleware has been attached to the route, you will automatically be prompted for credentials when accessing the route in your browser. By default, the `auth.basic` middleware will assume the `email` column on your `users` database table is the user's "username". -#### A Note On FastCGI +#### A Note on FastCGI -If you are using PHP FastCGI and Apache to serve your Laravel application, HTTP Basic authentication may not work correctly. To correct these problems, the following lines may be added to your application's `.htaccess` file: +If you are using [PHP FastCGI](https://www.php.net/manual/en/install.fpm.php) and Apache to serve your Laravel application, HTTP Basic authentication may not work correctly. To correct these problems, the following lines may be added to your application's `.htaccess` file: ```apache RewriteCond %{HTTP:Authorization} ^(.+)$ @@ -364,33 +445,38 @@ RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] You may also use HTTP Basic Authentication without setting a user identifier cookie in the session. This is primarily helpful if you choose to use HTTP Authentication to authenticate requests to your application's API. To accomplish this, [define a middleware](/docs/{{version}}/middleware) that calls the `onceBasic` method. If no response is returned by the `onceBasic` method, the request may be passed further into the application: - middleware('auth.basic.once'); +Next, attach the middleware to a route: + +```php +Route::get('/api/user', function () { + // Only authenticated users may access this route... +})->middleware(AuthenticateOnceWithBasicAuth::class); +``` ## Logging Out @@ -399,44 +485,48 @@ To manually log users out of your application, you may use the `logout` method p In addition to calling the `logout` method, it is recommended that you invalidate the user's session and regenerate their [CSRF token](/docs/{{version}}/csrf). After logging the user out, you would typically redirect the user to the root of your application: - use Illuminate\Http\Request; - use Illuminate\Support\Facades\Auth; +```php +use Illuminate\Http\Request; +use Illuminate\Http\RedirectResponse; +use Illuminate\Support\Facades\Auth; - /** - * Log the user out of the application. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\Response - */ - public function logout(Request $request) - { - Auth::logout(); +/** + * Log the user out of the application. + */ +public function logout(Request $request): RedirectResponse +{ + Auth::logout(); - $request->session()->invalidate(); + $request->session()->invalidate(); - $request->session()->regenerateToken(); + $request->session()->regenerateToken(); - return redirect('/'); - } + return redirect('/'); +} +``` -### Invalidating Sessions On Other Devices +### Invalidating Sessions on Other Devices Laravel also provides a mechanism for invalidating and "logging out" a user's sessions that are active on other devices without invalidating the session on their current device. This feature is typically utilized when a user is changing or updating their password and you would like to invalidate sessions on other devices while keeping the current device authenticated. -Before getting started, you should make sure that the `Illuminate\Session\Middleware\AuthenticateSession` middleware is present and un-commented in your `App\Http\Kernel` class' `web` middleware group: +Before getting started, you should make sure that the `Illuminate\Session\Middleware\AuthenticateSession` middleware is included on the routes that should receive session authentication. Typically, you should place this middleware on a route group definition so that it can be applied to the majority of your application's routes. By default, the `AuthenticateSession` middleware may be attached to a route using the `auth.session` [middleware alias](/docs/{{version}}/middleware#middleware-aliases): - 'web' => [ +```php +Route::middleware(['auth', 'auth.session'])->group(function () { + Route::get('/', function () { // ... - \Illuminate\Session\Middleware\AuthenticateSession::class, - // ... - ], + }); +}); +``` Then, you may use the `logoutOtherDevices` method provided by the `Auth` facade. This method requires the user to confirm their current password, which your application should accept through an input form: - use Illuminate\Support\Facades\Auth; +```php +use Illuminate\Support\Facades\Auth; - Auth::logoutOtherDevices($currentPassword); +Auth::logoutOtherDevices($currentPassword); +``` When the `logoutOtherDevices` method is invoked, the user's other sessions will be invalidated entirely, meaning they will be "logged out" of all guards they were previously authenticated by. @@ -445,7 +535,8 @@ When the `logoutOtherDevices` method is invoked, the user's other sessions will While building your application, you may occasionally have actions that should require the user to confirm their password before the action is performed or before the user is redirected to a sensitive area of the application. Laravel includes built-in middleware to make this process a breeze. Implementing this feature will require you to define two routes: one route to display a view asking the user to confirm their password and another route to confirm that the password is valid and redirect the user to their intended destination. -> {tip} The following documentation discusses how to integrate with Laravel's password confirmation features directly; however, if you would like to get started more quickly, the [Laravel application starter kits](/docs/{{version}}/starter-kits) include support for this feature! +> [!NOTE] +> The following documentation discusses how to integrate with Laravel's password confirmation features directly; however, if you would like to get started more quickly, the [Laravel application starter kits](/docs/{{version}}/starter-kits) include support for this feature! ### Configuration @@ -460,32 +551,35 @@ After confirming their password, a user will not be asked to confirm their passw First, we will define a route to display a view that requests the user to confirm their password: - Route::get('/confirm-password', function () { - return view('auth.confirm-password'); - })->middleware('auth')->name('password.confirm'); +```php +Route::get('/confirm-password', function () { + return view('auth.confirm-password'); +})->middleware('auth')->name('password.confirm'); +``` As you might expect, the view that is returned by this route should have a form containing a `password` field. In addition, feel free to include text within the view that explains that the user is entering a protected area of the application and must confirm their password. -#### Confirming The Password +#### Confirming the Password Next, we will define a route that will handle the form request from the "confirm password" view. This route will be responsible for validating the password and redirecting the user to their intended destination: - use Illuminate\Http\Request; - use Illuminate\Support\Facades\Hash; - use Illuminate\Support\Facades\Redirect; +```php +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Hash; - Route::post('/confirm-password', function (Request $request) { - if (! Hash::check($request->password, $request->user()->password)) { - return back()->withErrors([ - 'password' => ['The provided password does not match our records.'] - ]); - } +Route::post('/confirm-password', function (Request $request) { + if (! Hash::check($request->password, $request->user()->password)) { + return back()->withErrors([ + 'password' => ['The provided password does not match our records.'] + ]); + } - $request->session()->passwordConfirmed(); + $request->session()->passwordConfirmed(); - return redirect()->intended(); - })->middleware(['auth', 'throttle:6,1']); + return redirect()->intended(); +})->middleware(['auth', 'throttle:6,1']); +``` Before moving on, let's examine this route in more detail. First, the request's `password` field is determined to actually match the authenticated user's password. If the password is valid, we need to inform Laravel's session that the user has confirmed their password. The `passwordConfirmed` method will set a timestamp in the user's session that Laravel can use to determine when the user last confirmed their password. Finally, we can redirect the user to their intended destination. @@ -494,136 +588,154 @@ Before moving on, let's examine this route in more detail. First, the request's You should ensure that any route that performs an action which requires recent password confirmation is assigned the `password.confirm` middleware. This middleware is included with the default installation of Laravel and will automatically store the user's intended destination in the session so that the user may be redirected to that location after confirming their password. After storing the user's intended destination in the session, the middleware will redirect the user to the `password.confirm` [named route](/docs/{{version}}/routing#named-routes): - Route::get('/settings', function () { - // ... - })->middleware(['password.confirm']); +```php +Route::get('/settings', function () { + // ... +})->middleware(['password.confirm']); - Route::post('/settings', function () { - // ... - })->middleware(['password.confirm']); +Route::post('/settings', function () { + // ... +})->middleware(['password.confirm']); +``` ## Adding Custom Guards -You may define your own authentication guards using the `extend` method on the `Auth` facade. You should place your call to the `extend` method within a [service provider](/docs/{{version}}/providers). Since Laravel already ships with an `AuthServiceProvider`, we can place the code in that provider: +You may define your own authentication guards using the `extend` method on the `Auth` facade. You should place your call to the `extend` method within a [service provider](/docs/{{version}}/providers). Since Laravel already ships with an `AppServiceProvider`, we can place the code in that provider: + +```php +registerPolicies(); - - Auth::extend('jwt', function ($app, $name, array $config) { - // Return an instance of Illuminate\Contracts\Auth\Guard... - - return new JwtGuard(Auth::createUserProvider($config['provider'])); - }); - } + Auth::extend('jwt', function (Application $app, string $name, array $config) { + // Return an instance of Illuminate\Contracts\Auth\Guard... + + return new JwtGuard(Auth::createUserProvider($config['provider'])); + }); } +} +``` As you can see in the example above, the callback passed to the `extend` method should return an implementation of `Illuminate\Contracts\Auth\Guard`. This interface contains a few methods you will need to implement to define a custom guard. Once your custom guard has been defined, you may reference the guard in the `guards` configuration of your `auth.php` configuration file: - 'guards' => [ - 'api' => [ - 'driver' => 'jwt', - 'provider' => 'users', - ], +```php +'guards' => [ + 'api' => [ + 'driver' => 'jwt', + 'provider' => 'users', ], +], +``` ### Closure Request Guards The simplest way to implement a custom, HTTP request based authentication system is by using the `Auth::viaRequest` method. This method allows you to quickly define your authentication process using a single closure. -To get started, call the `Auth::viaRequest` method within the `boot` method of your `AuthServiceProvider`. The `viaRequest` method accepts an authentication driver name as its first argument. This name can be any string that describes your custom guard. The second argument passed to the method should be a closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, `null`: - - use App\Models\User; - use Illuminate\Http\Request; - use Illuminate\Support\Facades\Auth; - - /** - * Register any application authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - Auth::viaRequest('custom-token', function (Request $request) { - return User::where('token', $request->token)->first(); - }); - } +To get started, call the `Auth::viaRequest` method within the `boot` method of your application's `AppServiceProvider`. The `viaRequest` method accepts an authentication driver name as its first argument. This name can be any string that describes your custom guard. The second argument passed to the method should be a closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, `null`: + +```php +use App\Models\User; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Auth::viaRequest('custom-token', function (Request $request) { + return User::where('token', (string) $request->token)->first(); + }); +} +``` Once your custom authentication driver has been defined, you may configure it as a driver within the `guards` configuration of your `auth.php` configuration file: - 'guards' => [ - 'api' => [ - 'driver' => 'custom-token', - ], +```php +'guards' => [ + 'api' => [ + 'driver' => 'custom-token', ], +], +``` + +Finally, you may reference the guard when assigning the authentication middleware to a route: + +```php +Route::middleware('auth:api')->group(function () { + // ... +}); +``` ## Adding Custom User Providers If you are not using a traditional relational database to store your users, you will need to extend Laravel with your own authentication user provider. We will use the `provider` method on the `Auth` facade to define a custom user provider. The user provider resolver should return an implementation of `Illuminate\Contracts\Auth\UserProvider`: - registerPolicies(); - - Auth::provider('mongo', function ($app, array $config) { - // Return an instance of Illuminate\Contracts\Auth\UserProvider... - - return new MongoUserProvider($app->make('mongo.connection')); - }); - } + Auth::provider('mongo', function (Application $app, array $config) { + // Return an instance of Illuminate\Contracts\Auth\UserProvider... + + return new MongoUserProvider($app->make('mongo.connection')); + }); } +} +``` After you have registered the provider using the `provider` method, you may switch to the new user provider in your `auth.php` configuration file. First, define a `provider` that uses your new driver: - 'providers' => [ - 'users' => [ - 'driver' => 'mongo', - ], +```php +'providers' => [ + 'users' => [ + 'driver' => 'mongo', ], +], +``` Finally, you may reference this provider in your `guards` configuration: - 'guards' => [ - 'web' => [ - 'driver' => 'session', - 'provider' => 'users', - ], +```php +'guards' => [ + 'web' => [ + 'driver' => 'session', + 'provider' => 'users', ], +], +``` ### The User Provider Contract @@ -632,18 +744,21 @@ Finally, you may reference this provider in your `guards` configuration: Let's take a look at the `Illuminate\Contracts\Auth\UserProvider` contract: - getAuthPassword()` to the value of `$credentials['password']`. This method should return `true` or `false` indicating whether the password is valid. +The `rehashPasswordIfRequired` method should rehash the given `$user`'s password if required and supported. For example, this method will typically use the `Hash::needsRehash` method to determine if the `$credentials['password']` value needs to be rehashed. If the password needs to be rehashed, the method should use the `Hash::make` method to rehash the password and update the user's record in the underlying persistent storage. + ### The Authenticatable Contract Now that we have explored each of the methods on the `UserProvider`, let's take a look at the `Authenticatable` contract. Remember, user providers should return implementations of this interface from the `retrieveById`, `retrieveByToken`, and `retrieveByCredentials` methods: - +## Automatic Password Rehashing -This interface is simple. The `getAuthIdentifierName` method should return the name of the "primary key" field of the user and the `getAuthIdentifier` method should return the "primary key" of the user. When using a MySQL back-end, this would likely be the auto-incrementing primary key assigned to the user record. The `getAuthPassword` method should return the user's hashed password. +Laravel's default password hashing algorithm is bcrypt. The "work factor" for bcrypt hashes can be adjusted via your application's `config/hashing.php` configuration file or the `BCRYPT_ROUNDS` environment variable. -This interface allows the authentication system to work with any "user" class, regardless of what ORM or storage abstraction layer you are using. By default, Laravel includes a `App\Models\User` class in the `app/Models` directory which implements this interface. +Typically, the bcrypt work factor should be increased over time as CPU / GPU processing power increases. If you increase the bcrypt work factor for your application, Laravel will gracefully and automatically rehash user passwords as users authenticate with your application via Laravel's starter kits or when you [manually authenticate users](#authenticating-users) via the `attempt` method. + +Typically, automatic password rehashing should not disrupt your application; however, you may disable this behavior by publishing the `hashing` configuration file: + +```shell +php artisan config:publish hashing +``` + +Once the configuration file has been published, you may set the `rehash_on_login` configuration value to `false`: + +```php +'rehash_on_login' => false, +``` ## Events -Laravel dispatches a variety of [events](/docs/{{version}}/events) during the authentication process. You may attach listeners to these events in your `EventServiceProvider`: - - /** - * The event listener mappings for the application. - * - * @var array - */ - protected $listen = [ - 'Illuminate\Auth\Events\Registered' => [ - 'App\Listeners\LogRegisteredUser', - ], - - 'Illuminate\Auth\Events\Attempting' => [ - 'App\Listeners\LogAuthenticationAttempt', - ], - - 'Illuminate\Auth\Events\Authenticated' => [ - 'App\Listeners\LogAuthenticated', - ], - - 'Illuminate\Auth\Events\Login' => [ - 'App\Listeners\LogSuccessfulLogin', - ], - - 'Illuminate\Auth\Events\Failed' => [ - 'App\Listeners\LogFailedLogin', - ], - - 'Illuminate\Auth\Events\Validated' => [ - 'App\Listeners\LogValidated', - ], - - 'Illuminate\Auth\Events\Verified' => [ - 'App\Listeners\LogVerified', - ], - - 'Illuminate\Auth\Events\Logout' => [ - 'App\Listeners\LogSuccessfulLogout', - ], - - 'Illuminate\Auth\Events\CurrentDeviceLogout' => [ - 'App\Listeners\LogCurrentDeviceLogout', - ], - - 'Illuminate\Auth\Events\OtherDeviceLogout' => [ - 'App\Listeners\LogOtherDeviceLogout', - ], - - 'Illuminate\Auth\Events\Lockout' => [ - 'App\Listeners\LogLockout', - ], - - 'Illuminate\Auth\Events\PasswordReset' => [ - 'App\Listeners\LogPasswordReset', - ], - ]; +Laravel dispatches a variety of [events](/docs/{{version}}/events) during the authentication process. You may [define listeners](/docs/{{version}}/events) for any of the following events: + +
+ +| Event Name | +| ---------------------------------------------- | +| `Illuminate\Auth\Events\Registered` | +| `Illuminate\Auth\Events\Attempting` | +| `Illuminate\Auth\Events\Authenticated` | +| `Illuminate\Auth\Events\Login` | +| `Illuminate\Auth\Events\Failed` | +| `Illuminate\Auth\Events\Validated` | +| `Illuminate\Auth\Events\Verified` | +| `Illuminate\Auth\Events\Logout` | +| `Illuminate\Auth\Events\CurrentDeviceLogout` | +| `Illuminate\Auth\Events\OtherDeviceLogout` | +| `Illuminate\Auth\Events\Lockout` | +| `Illuminate\Auth\Events\PasswordReset` | +| `Illuminate\Auth\Events\PasswordResetLinkSent` | + +
diff --git a/authorization.md b/authorization.md index 72c2641f278..b418b61703f 100644 --- a/authorization.md +++ b/authorization.md @@ -17,11 +17,12 @@ - [Guest Users](#guest-users) - [Policy Filters](#policy-filters) - [Authorizing Actions Using Policies](#authorizing-actions-using-policies) - - [Via The User Model](#via-the-user-model) - - [Via Controller Helpers](#via-controller-helpers) + - [Via the User Model](#via-the-user-model) + - [Via the Gate Facade](#via-the-gate-facade) - [Via Middleware](#via-middleware) - [Via Blade Templates](#via-blade-templates) - [Supplying Additional Context](#supplying-additional-context) +- [Authorization & Inertia](#authorization-and-inertia) ## Introduction @@ -30,7 +31,7 @@ In addition to providing built-in [authentication](/docs/{{version}}/authenticat Laravel provides two primary ways of authorizing actions: [gates](#gates) and [policies](#creating-policies). Think of gates and policies like routes and controllers. Gates provide a simple, closure-based approach to authorization while policies, like controllers, group logic around a particular model or resource. In this documentation, we'll explore gates first and then examine policies. -You do not need to choose between exclusively using gates or exclusively using policies when building an application. Most applications will most likely contain some mixture of gates and policies, and that is perfectly fine! Gates are most applicable to actions which are not related to any model or resource, such as viewing an administrator dashboard. In contrast, policies should be used when you wish to authorize an action for a particular model or resource. +You do not need to choose between exclusively using gates or exclusively using policies when building an application. Most applications will most likely contain some mixture of gates and policies, and that is perfectly fine! Gates are most applicable to actions that are not related to any model or resource, such as viewing an administrator dashboard. In contrast, policies should be used when you wish to authorize an action for a particular model or resource. ## Gates @@ -38,202 +39,252 @@ You do not need to choose between exclusively using gates or exclusively using p ### Writing Gates -> {note} Gates are a great way to learn the basics of Laravel's authorization features; however, when building robust Laravel applications you should consider using [policies](#creating-policies) to organize your authorization rules. +> [!WARNING] +> Gates are a great way to learn the basics of Laravel's authorization features; however, when building robust Laravel applications you should consider using [policies](#creating-policies) to organize your authorization rules. -Gates are simply closures that determine if a user is authorized to perform a given action. Typically, gates are defined within the `boot` method of the `App\Providers\AuthServiceProvider` class using the `Gate` facade. Gates always receive a user instance as their first argument and may optionally receive additional arguments such as a relevant Eloquent model. +Gates are simply closures that determine if a user is authorized to perform a given action. Typically, gates are defined within the `boot` method of the `App\Providers\AppServiceProvider` class using the `Gate` facade. Gates always receive a user instance as their first argument and may optionally receive additional arguments such as a relevant Eloquent model. In this example, we'll define a gate to determine if a user can update a given `App\Models\Post` model. The gate will accomplish this by comparing the user's `id` against the `user_id` of the user that created the post: - use App\Models\Post; - use App\Models\User; - use Illuminate\Support\Facades\Gate; - - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - Gate::define('update-post', function (User $user, Post $post) { - return $user->id === $post->user_id; - }); - } +```php +use App\Models\Post; +use App\Models\User; +use Illuminate\Support\Facades\Gate; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Gate::define('update-post', function (User $user, Post $post) { + return $user->id === $post->user_id; + }); +} +``` Like controllers, gates may also be defined using a class callback array: - use App\Policies\PostPolicy; - use Illuminate\Support\Facades\Gate; - - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - Gate::define('update-post', [PostPolicy::class, 'update']); - } +```php +use App\Policies\PostPolicy; +use Illuminate\Support\Facades\Gate; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Gate::define('update-post', [PostPolicy::class, 'update']); +} +``` ### Authorizing Actions To authorize an action using gates, you should use the `allows` or `denies` methods provided by the `Gate` facade. Note that you are not required to pass the currently authenticated user to these methods. Laravel will automatically take care of passing the user into the gate closure. It is typical to call the gate authorization methods within your application's controllers before performing an action that requires authorization: - allows('update-post', $post)) { - // The user can update the post... - } +```php +if (Gate::forUser($user)->allows('update-post', $post)) { + // The user can update the post... +} - if (Gate::forUser($user)->denies('update-post', $post)) { - // The user can't update the post... - } +if (Gate::forUser($user)->denies('update-post', $post)) { + // The user can't update the post... +} +``` You may authorize multiple actions at a time using the `any` or `none` methods: - if (Gate::any(['update-post', 'delete-post'], $post)) { - // The user can update or delete the post... - } +```php +if (Gate::any(['update-post', 'delete-post'], $post)) { + // The user can update or delete the post... +} - if (Gate::none(['update-post', 'delete-post'], $post)) { - // The user can't update or delete the post... - } +if (Gate::none(['update-post', 'delete-post'], $post)) { + // The user can't update or delete the post... +} +``` -#### Authorizing Or Throwing Exceptions +#### Authorizing or Throwing Exceptions -If you would like to attempt to authorize an action and automatically throw an `Illuminate\Auth\Access\AuthorizationException` if the user is not allowed to perform the given action, you may use the `Gate` facade's `authorize` method. Instances of `AuthorizationException` are automatically converted to a 403 HTTP response by Laravel's exception handler: +If you would like to attempt to authorize an action and automatically throw an `Illuminate\Auth\Access\AuthorizationException` if the user is not allowed to perform the given action, you may use the `Gate` facade's `authorize` method. Instances of `AuthorizationException` are automatically converted to a 403 HTTP response by Laravel: - Gate::authorize('update-post', $post); +```php +Gate::authorize('update-post', $post); - // The action is authorized... +// The action is authorized... +``` #### Supplying Additional Context The gate methods for authorizing abilities (`allows`, `denies`, `check`, `any`, `none`, `authorize`, `can`, `cannot`) and the authorization [Blade directives](#via-blade-templates) (`@can`, `@cannot`, `@canany`) can receive an array as their second argument. These array elements are passed as parameters to the gate closure, and can be used for additional context when making authorization decisions: - use App\Models\Category; - use App\Models\User; - use Illuminate\Support\Facades\Gate; - - Gate::define('create-post', function (User $user, Category $category, $pinned) { - if (! $user->canPublishToGroup($category->group)) { - return false; - } elseif ($pinned && ! $user->canPinPosts()) { - return false; - } +```php +use App\Models\Category; +use App\Models\User; +use Illuminate\Support\Facades\Gate; + +Gate::define('create-post', function (User $user, Category $category, bool $pinned) { + if (! $user->canPublishToGroup($category->group)) { + return false; + } elseif ($pinned && ! $user->canPinPosts()) { + return false; + } - return true; - }); + return true; +}); - if (Gate::check('create-post', [$category, $pinned])) { - // The user can create the post... - } +if (Gate::check('create-post', [$category, $pinned])) { + // The user can create the post... +} +``` ### Gate Responses So far, we have only examined gates that return simple boolean values. However, sometimes you may wish to return a more detailed response, including an error message. To do so, you may return an `Illuminate\Auth\Access\Response` from your gate: - use App\Models\User; - use Illuminate\Auth\Access\Response; - use Illuminate\Support\Facades\Gate; - - Gate::define('edit-settings', function (User $user) { - return $user->isAdmin - ? Response::allow() - : Response::deny('You must be an administrator.'); - }); +```php +use App\Models\User; +use Illuminate\Auth\Access\Response; +use Illuminate\Support\Facades\Gate; + +Gate::define('edit-settings', function (User $user) { + return $user->isAdmin + ? Response::allow() + : Response::deny('You must be an administrator.'); +}); +``` Even when you return an authorization response from your gate, the `Gate::allows` method will still return a simple boolean value; however, you may use the `Gate::inspect` method to get the full authorization response returned by the gate: - $response = Gate::inspect('edit-settings'); +```php +$response = Gate::inspect('edit-settings'); - if ($response->allowed()) { - // The action is authorized... - } else { - echo $response->message(); - } +if ($response->allowed()) { + // The action is authorized... +} else { + echo $response->message(); +} +``` When using the `Gate::authorize` method, which throws an `AuthorizationException` if the action is not authorized, the error message provided by the authorization response will be propagated to the HTTP response: - Gate::authorize('edit-settings'); +```php +Gate::authorize('edit-settings'); - // The action is authorized... +// The action is authorized... +``` + + +#### Customizing The HTTP Response Status + +When an action is denied via a Gate, a `403` HTTP response is returned; however, it can sometimes be useful to return an alternative HTTP status code. You may customize the HTTP status code returned for a failed authorization check using the `denyWithStatus` static constructor on the `Illuminate\Auth\Access\Response` class: + +```php +use App\Models\User; +use Illuminate\Auth\Access\Response; +use Illuminate\Support\Facades\Gate; + +Gate::define('edit-settings', function (User $user) { + return $user->isAdmin + ? Response::allow() + : Response::denyWithStatus(404); +}); +``` + +Because hiding resources via a `404` response is such a common pattern for web applications, the `denyAsNotFound` method is offered for convenience: + +```php +use App\Models\User; +use Illuminate\Auth\Access\Response; +use Illuminate\Support\Facades\Gate; + +Gate::define('edit-settings', function (User $user) { + return $user->isAdmin + ? Response::allow() + : Response::denyAsNotFound(); +}); +``` ### Intercepting Gate Checks Sometimes, you may wish to grant all abilities to a specific user. You may use the `before` method to define a closure that is run before all other authorization checks: - use Illuminate\Support\Facades\Gate; +```php +use App\Models\User; +use Illuminate\Support\Facades\Gate; - Gate::before(function ($user, $ability) { - if ($user->isAdministrator()) { - return true; - } - }); +Gate::before(function (User $user, string $ability) { + if ($user->isAdministrator()) { + return true; + } +}); +``` If the `before` closure returns a non-null result that result will be considered the result of the authorization check. You may use the `after` method to define a closure to be executed after all other authorization checks: - Gate::after(function ($user, $ability, $result, $arguments) { - if ($user->isAdministrator()) { - return true; - } - }); +```php +use App\Models\User; -Similar to the `before` method, if the `after` closure returns a non-null result that result will be considered the result of the authorization check. +Gate::after(function (User $user, string $ability, bool|null $result, mixed $arguments) { + if ($user->isAdministrator()) { + return true; + } +}); +``` + +Values returned by `after` closures will not override the result of the authorization check unless the gate or policy returned `null`. ### Inline Authorization -Occasionally, you may wish to determine if the currently authenticated user is authorized to perform a given action without writing a dedicate gate that corresponds to the action. Laravel allows you to perform these types of "inline" authorization checks via the `Gate::allowIf` and `Gate::denyIf` methods: +Occasionally, you may wish to determine if the currently authenticated user is authorized to perform a given action without writing a dedicated gate that corresponds to the action. Laravel allows you to perform these types of "inline" authorization checks via the `Gate::allowIf` and `Gate::denyIf` methods. Inline authorization does not execute any defined ["before" or "after" authorization hooks](#intercepting-gate-checks): ```php -use Illuminate\Support\Facades\Auth; +use App\Models\User; +use Illuminate\Support\Facades\Gate; -Gate::allowIf(fn ($user) => $user->isAdministrator()); +Gate::allowIf(fn (User $user) => $user->isAdministrator()); -Gate::denyIf(fn ($user) => $user->banned()); +Gate::denyIf(fn (User $user) => $user->banned()); ``` -If the action is not authorized or if no user is currently authenticated, Laravel will automatically throw an `Illuminate\Auth\Access\AuthorizationException` exception. Instances of `AuthorizationException` are automatically converted to a 403 HTTP response by Laravel's exception handler: +If the action is not authorized or if no user is currently authenticated, Laravel will automatically throw an `Illuminate\Auth\Access\AuthorizationException` exception. Instances of `AuthorizationException` are automatically converted to a 403 HTTP response by Laravel's exception handler. ## Creating Policies @@ -241,7 +292,7 @@ If the action is not authorized or if no user is currently authenticated, Larave ### Generating Policies -Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a `App\Models\Post` model and a corresponding `App\Policies\PostPolicy` to authorize user actions such as creating or updating posts. +Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have an `App\Models\Post` model and a corresponding `App\Policies\PostPolicy` to authorize user actions such as creating or updating posts. You may generate a policy using the `make:policy` Artisan command. The generated policy will be placed in the `app/Policies` directory. If this directory does not exist in your application, Laravel will create it for you: @@ -258,57 +309,57 @@ php artisan make:policy PostPolicy --model=Post ### Registering Policies -Once the policy class has been created, it needs to be registered. Registering policies is how we can inform Laravel which policy to use when authorizing actions against a given model type. - -The `App\Providers\AuthServiceProvider` included with fresh Laravel applications contains a `policies` property which maps your Eloquent models to their corresponding policies. Registering a policy will instruct Laravel which policy to utilize when authorizing actions against a given Eloquent model: + +#### Policy Discovery - PostPolicy::class, - ]; +Gate::guessPolicyNamesUsing(function (string $modelClass) { + // Return the name of the policy class for the given model... +}); +``` - /** - * Register any application authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); + +#### Manually Registering Policies - // - } - } +Using the `Gate` facade, you may manually register policies and their corresponding models within the `boot` method of your application's `AppServiceProvider`: - -#### Policy Auto-Discovery +```php +use App\Models\Order; +use App\Policies\OrderPolicy; +use Illuminate\Support\Facades\Gate; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Gate::policy(Order::class, OrderPolicy::class); +} +``` -Instead of manually registering model policies, Laravel can automatically discover policies as long as the model and policy follow standard Laravel naming conventions. Specifically, the policies must be in a `Policies` directory at or above the directory that contains your models. So, for example, the models may be placed in the `app/Models` directory while the policies may be placed in the `app/Policies` directory. In this situation, Laravel will check for policies in `app/Models/Policies` then `app/Policies`. In addition, the policy name must match the model name and have a `Policy` suffix. So, a `User` model would correspond to a `UserPolicy` policy class. +Alternatively, you may place the `UsePolicy` attribute on a model class to inform Laravel of the model's corresponding policy: -If you would like to define your own policy discovery logic, you may register a custom policy discovery callback using the `Gate::guessPolicyNamesUsing` method. Typically, this method should be called from the `boot` method of your application's `AuthServiceProvider`: +```php + {note} Any policies that are explicitly mapped in your `AuthServiceProvider` will take precedence over any potentially auto-discovered policies. +#[UsePolicy(OrderPolicy::class)] +class Order extends Model +{ + // +} +``` ## Writing Policies @@ -320,177 +371,215 @@ Once the policy class has been registered, you may add methods for each action i The `update` method will receive a `User` and a `Post` instance as its arguments, and should return `true` or `false` indicating whether the user is authorized to update the given `Post`. So, in this example, we will verify that the user's `id` matches the `user_id` on the post: - id === $post->user_id; - } + return $user->id === $post->user_id; } +} +``` You may continue to define additional methods on the policy as needed for the various actions it authorizes. For example, you might define `view` or `delete` methods to authorize various `Post` related actions, but remember you are free to give your policy methods any name you like. If you used the `--model` option when generating your policy via the Artisan console, it will already contain methods for the `viewAny`, `view`, `create`, `update`, `delete`, `restore`, and `forceDelete` actions. -> {tip} All policies are resolved via the Laravel [service container](/docs/{{version}}/container), allowing you to type-hint any needed dependencies in the policy's constructor to have them automatically injected. +> [!NOTE] +> All policies are resolved via the Laravel [service container](/docs/{{version}}/container), allowing you to type-hint any needed dependencies in the policy's constructor to have them automatically injected. ### Policy Responses So far, we have only examined policy methods that return simple boolean values. However, sometimes you may wish to return a more detailed response, including an error message. To do so, you may return an `Illuminate\Auth\Access\Response` instance from your policy method: - use App\Models\Post; - use App\Models\User; - use Illuminate\Auth\Access\Response; - - /** - * Determine if the given post can be updated by the user. - * - * @param \App\Models\User $user - * @param \App\Models\Post $post - * @return \Illuminate\Auth\Access\Response - */ - public function update(User $user, Post $post) - { - return $user->id === $post->user_id - ? Response::allow() - : Response::deny('You do not own this post.'); - } +```php +use App\Models\Post; +use App\Models\User; +use Illuminate\Auth\Access\Response; + +/** + * Determine if the given post can be updated by the user. + */ +public function update(User $user, Post $post): Response +{ + return $user->id === $post->user_id + ? Response::allow() + : Response::deny('You do not own this post.'); +} +``` When returning an authorization response from your policy, the `Gate::allows` method will still return a simple boolean value; however, you may use the `Gate::inspect` method to get the full authorization response returned by the gate: - use Illuminate\Support\Facades\Gate; +```php +use Illuminate\Support\Facades\Gate; - $response = Gate::inspect('update', $post); +$response = Gate::inspect('update', $post); - if ($response->allowed()) { - // The action is authorized... - } else { - echo $response->message(); - } +if ($response->allowed()) { + // The action is authorized... +} else { + echo $response->message(); +} +``` When using the `Gate::authorize` method, which throws an `AuthorizationException` if the action is not authorized, the error message provided by the authorization response will be propagated to the HTTP response: - Gate::authorize('update', $post); +```php +Gate::authorize('update', $post); + +// The action is authorized... +``` + + +#### Customizing the HTTP Response Status - // The action is authorized... +When an action is denied via a policy method, a `403` HTTP response is returned; however, it can sometimes be useful to return an alternative HTTP status code. You may customize the HTTP status code returned for a failed authorization check using the `denyWithStatus` static constructor on the `Illuminate\Auth\Access\Response` class: + +```php +use App\Models\Post; +use App\Models\User; +use Illuminate\Auth\Access\Response; + +/** + * Determine if the given post can be updated by the user. + */ +public function update(User $user, Post $post): Response +{ + return $user->id === $post->user_id + ? Response::allow() + : Response::denyWithStatus(404); +} +``` + +Because hiding resources via a `404` response is such a common pattern for web applications, the `denyAsNotFound` method is offered for convenience: + +```php +use App\Models\Post; +use App\Models\User; +use Illuminate\Auth\Access\Response; + +/** + * Determine if the given post can be updated by the user. + */ +public function update(User $user, Post $post): Response +{ + return $user->id === $post->user_id + ? Response::allow() + : Response::denyAsNotFound(); +} +``` ### Methods Without Models Some policy methods only receive an instance of the currently authenticated user. This situation is most common when authorizing `create` actions. For example, if you are creating a blog, you may wish to determine if a user is authorized to create any posts at all. In these situations, your policy method should only expect to receive a user instance: - /** - * Determine if the given user can create posts. - * - * @param \App\Models\User $user - * @return bool - */ - public function create(User $user) - { - return $user->role == 'writer'; - } +```php +/** + * Determine if the given user can create posts. + */ +public function create(User $user): bool +{ + return $user->role == 'writer'; +} +``` ### Guest Users By default, all gates and policies automatically return `false` if the incoming HTTP request was not initiated by an authenticated user. However, you may allow these authorization checks to pass through to your gates and policies by declaring an "optional" type-hint or supplying a `null` default value for the user argument definition: - id === $post->user_id; - } + return $user?->id === $post->user_id; } +} +``` ### Policy Filters For certain users, you may wish to authorize all actions within a given policy. To accomplish this, define a `before` method on the policy. The `before` method will be executed before any other methods on the policy, giving you an opportunity to authorize the action before the intended policy method is actually called. This feature is most commonly used for authorizing application administrators to perform any action: - use App\Models\User; - - /** - * Perform pre-authorization checks. - * - * @param \App\Models\User $user - * @param string $ability - * @return void|bool - */ - public function before(User $user, $ability) - { - if ($user->isAdministrator()) { - return true; - } +```php +use App\Models\User; + +/** + * Perform pre-authorization checks. + */ +public function before(User $user, string $ability): bool|null +{ + if ($user->isAdministrator()) { + return true; } + return null; +} +``` + If you would like to deny all authorization checks for a particular type of user then you may return `false` from the `before` method. If `null` is returned, the authorization check will fall through to the policy method. -> {note} The `before` method of a policy class will not be called if the class doesn't contain a method with a name matching the name of the ability being checked. +> [!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 name of the ability being checked. ## Authorizing Actions Using Policies -### Via The User Model +### Via the User Model The `App\Models\User` model that is included with your Laravel application includes two helpful methods for authorizing actions: `can` and `cannot`. The `can` and `cannot` methods receive the name of the action you wish to authorize and the relevant model. For example, let's determine if a user is authorized to update a given `App\Models\Post` model. Typically, this will be done within a controller method: - user()->cannot('update', $post)) { - abort(403); - } - - // Update the post... + if ($request->user()->cannot('update', $post)) { + abort(403); } + + // Update the post... + + return redirect('/posts'); } +} +``` If a [policy is registered](#registering-policies) for the given model, the `can` method will automatically call the appropriate policy and return the boolean result. If no policy is registered for the model, the `can` method will attempt to call the closure-based Gate matching the given action name. @@ -499,168 +588,139 @@ If a [policy is registered](#registering-policies) for the given model, the `can Remember, some actions may correspond to policy methods like `create` that do not require a model instance. In these situations, you may pass a class name to the `can` method. The class name will be used to determine which policy to use when authorizing the action: - user()->cannot('create', Post::class)) { - abort(403); - } - - // Create the post... + if ($request->user()->cannot('create', Post::class)) { + abort(403); } - } - -### Via Controller Helpers + // Create the post... -In addition to helpful methods provided to the `App\Models\User` model, Laravel provides a helpful `authorize` method to any of your controllers which extend the `App\Http\Controllers\Controller` base class. - -Like the `can` method, this method accepts the name of the action you wish to authorize and the relevant model. If the action is not authorized, the `authorize` method will throw an `Illuminate\Auth\Access\AuthorizationException` exception which the Laravel exception handler will automatically convert to an HTTP response with a 403 status code: - - +### Via the `Gate` Facade - use App\Http\Controllers\Controller; - use App\Models\Post; - use Illuminate\Http\Request; +In addition to helpful methods provided to the `App\Models\User` model, you can always authorize actions via the `Gate` facade's `authorize` method. - class PostController extends Controller - { - /** - * Update the given blog post. - * - * @param \Illuminate\Http\Request $request - * @param \App\Models\Post $post - * @return \Illuminate\Http\Response - * - * @throws \Illuminate\Auth\Access\AuthorizationException - */ - public function update(Request $request, Post $post) - { - $this->authorize('update', $post); - - // The current user can update the blog post... - } - } +Like the `can` method, this method accepts the name of the action you wish to authorize and the relevant model. If the action is not authorized, the `authorize` method will throw an `Illuminate\Auth\Access\AuthorizationException` exception which the Laravel exception handler will automatically convert to an HTTP response with a 403 status code: - -#### Actions That Don't Require Models +```php +authorize('create', Post::class); - - // The current user can create blog posts... - } - - -#### Authorizing Resource Controllers + Gate::authorize('update', $post); -If you are utilizing [resource controllers](/docs/{{version}}/controllers#resource-controllers), you may make use of the `authorizeResource` method in your controller's constructor. This method will attach the appropriate `can` middleware definitions to the resource controller's methods. - -The `authorizeResource` method accepts the model's class name as its first argument, and the name of the route / request parameter that will contain the model's ID as its second argument. You should ensure your [resource controller](/docs/{{version}}/controllers#resource-controllers) is created using the `--model` flag so that it has the required method signatures and type hints: - - authorizeResource(Post::class, 'post'); - } + return redirect('/posts'); } +} +``` -The following controller methods will be mapped to their corresponding policy method. When requests are routed to the given controller method, the corresponding policy method will automatically be invoked before the controller method is executed: + +#### Actions That Don't Require Models -| Controller Method | Policy Method | -| --- | --- | -| index | viewAny | -| show | view | -| create | create | -| store | create | -| edit | update | -| update | update | -| destroy | delete | +As previously discussed, some policy methods like `create` do not require a model instance. In these situations, you should pass a class name to the `authorize` method. The class name will be used to determine which policy to use when authorizing the action: -> {tip} You may use the `make:policy` command with the `--model` option to quickly generate a policy class for a given model: `php artisan make:policy PostPolicy --model=Post`. +```php +use App\Models\Post; +use Illuminate\Http\RedirectResponse; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Gate; + +/** + * Create a new blog post. + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ +public function create(Request $request): RedirectResponse +{ + Gate::authorize('create', Post::class); + + // The current user can create blog posts... + + return redirect('/posts'); +} +``` ### Via Middleware -Laravel includes a middleware that can authorize actions before the incoming request even reaches your routes or controllers. By default, the `Illuminate\Auth\Middleware\Authorize` middleware is assigned the `can` key in your `App\Http\Kernel` class. Let's explore an example of using the `can` middleware to authorize that a user can update a post: +Laravel includes a middleware that can authorize actions before the incoming request even reaches your routes or controllers. By default, the `Illuminate\Auth\Middleware\Authorize` middleware may be attached to a route using the `can` [middleware alias](/docs/{{version}}/middleware#middleware-aliases), which is automatically registered by Laravel. Let's explore an example of using the `can` middleware to authorize that a user can update a post: - use App\Models\Post; +```php +use App\Models\Post; - Route::put('/post/{post}', function (Post $post) { - // The current user may update the post... - })->middleware('can:update,post'); +Route::put('/post/{post}', function (Post $post) { + // The current user may update the post... +})->middleware('can:update,post'); +``` -In this example, we're passing the `can` middleware two arguments. The first is the name of the action we wish to authorize and the second is the route parameter we wish to pass to the policy method. In this case, since we are using [implicit model binding](/docs/{{version}}/routing#implicit-binding), a `App\Models\Post` model will be passed to the policy method. If the user is not authorized to perform the given action, an HTTP response with a 403 status code will be returned by the middleware. +In this example, we're passing the `can` middleware two arguments. The first is the name of the action we wish to authorize and the second is the route parameter we wish to pass to the policy method. In this case, since we are using [implicit model binding](/docs/{{version}}/routing#implicit-binding), an `App\Models\Post` model will be passed to the policy method. If the user is not authorized to perform the given action, an HTTP response with a 403 status code will be returned by the middleware. For convenience, you may also attach the `can` middleware to your route using the `can` method: - use App\Models\Post; +```php +use App\Models\Post; - Route::put('/post/{post}', function (Post $post) { - // The current user may update the post... - })->can('update', 'post'); +Route::put('/post/{post}', function (Post $post) { + // The current user may update the post... +})->can('update', 'post'); +``` #### Actions That Don't Require Models Again, some policy methods like `create` do not require a model instance. In these situations, you may pass a class name to the middleware. The class name will be used to determine which policy to use when authorizing the action: - Route::post('/post', function () { - // The current user may create posts... - })->middleware('can:create,App\Models\Post'); +```php +Route::post('/post', function () { + // The current user may create posts... +})->middleware('can:create,App\Models\Post'); +``` Specifying the entire class name within a string middleware definition can become cumbersome. For that reason, you may choose to attach the `can` middleware to your route using the `can` method: - use App\Models\Post; +```php +use App\Models\Post; - Route::post('/post', function () { - // The current user may create posts... - })->can('create', Post::class); +Route::post('/post', function () { + // The current user may create posts... +})->can('create', Post::class); +``` ### Via Blade Templates @@ -725,34 +785,73 @@ Like most of the other authorization methods, you may pass a class name to the ` When authorizing actions using policies, you may pass an array as the second argument to the various authorization functions and helpers. The first element in the array will be used to determine which policy should be invoked, while the rest of the array elements are passed as parameters to the policy method and can be used for additional context when making authorization decisions. For example, consider the following `PostPolicy` method definition which contains an additional `$category` parameter: - /** - * Determine if the given post can be updated by the user. - * - * @param \App\Models\User $user - * @param \App\Models\Post $post - * @param int $category - * @return bool - */ - public function update(User $user, Post $post, int $category) - { - return $user->id === $post->user_id && - $user->canUpdateCategory($category); - } +```php +/** + * Determine if the given post can be updated by the user. + */ +public function update(User $user, Post $post, int $category): bool +{ + return $user->id === $post->user_id && + $user->canUpdateCategory($category); +} +``` When attempting to determine if the authenticated user can update a given post, we can invoke this policy method like so: +```php +/** + * Update the given blog post. + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ +public function update(Request $request, Post $post): RedirectResponse +{ + Gate::authorize('update', [$post, $request->category]); + + // The current user can update the blog post... + + return redirect('/posts'); +} +``` + + +## Authorization & Inertia + +Although authorization must always be handled on the server, it can often be convenient to provide your frontend application with authorization data in order to properly render your application's UI. Laravel does not define a required convention for exposing authorization information to an Inertia powered frontend. + +However, if you are using one of Laravel's Inertia-based [starter kits](/docs/{{version}}/starter-kits), your application already contains a `HandleInertiaRequests` middleware. Within this middleware's `share` method, you may return shared data that will be provided to all Inertia pages in your application. This shared data can serve as a convenient location to define authorization information for the user: + +```php + */ - public function update(Request $request, Post $post) + public function share(Request $request) { - $this->authorize('update', [$post, $request->category]); - - // The current user can update the blog post... + return [ + ...parent::share($request), + 'auth' => [ + 'user' => $request->user(), + 'permissions' => [ + 'post' => [ + 'create' => $request->user()->can('create', Post::class), + ], + ], + ], + ]; } +} +``` diff --git a/billing.md b/billing.md index 02142de24ee..4597418e535 100644 --- a/billing.md +++ b/billing.md @@ -3,7 +3,6 @@ - [Introduction](#introduction) - [Upgrading Cashier](#upgrading-cashier) - [Installation](#installation) - - [Database Migrations](#database-migrations) - [Configuration](#configuration) - [Billable Model](#billable-model) - [API Keys](#api-keys) @@ -11,6 +10,9 @@ - [Tax Configuration](#tax-configuration) - [Logging](#logging) - [Using Custom Models](#using-custom-models) +- [Quickstart](#quickstart) + - [Selling Products](#quickstart-selling-products) + - [Selling Subscriptions](#quickstart-selling-subscriptions) - [Customers](#customers) - [Retrieving Customers](#retrieving-customers) - [Creating Customers](#creating-customers) @@ -22,8 +24,8 @@ - [Payment Methods](#payment-methods) - [Storing Payment Methods](#storing-payment-methods) - [Retrieving Payment Methods](#retrieving-payment-methods) - - [Determining If A User Has A Payment Method](#check-for-a-payment-method) - - [Updating The Default Payment Method](#updating-the-default-payment-method) + - [Payment Method Presence](#payment-method-presence) + - [Updating the Default Payment Method](#updating-the-default-payment-method) - [Adding Payment Methods](#adding-payment-methods) - [Deleting Payment Methods](#deleting-payment-methods) - [Subscriptions](#subscriptions) @@ -31,8 +33,9 @@ - [Checking Subscription Status](#checking-subscription-status) - [Changing Prices](#changing-prices) - [Subscription Quantity](#subscription-quantity) - - [Multiprice Subscriptions](#multiprice-subscriptions) - - [Metered Billing](#metered-billing) + - [Subscriptions With Multiple Products](#subscriptions-with-multiple-products) + - [Multiple Subscriptions](#multiple-subscriptions) + - [Usage Based Billing](#usage-based-billing) - [Subscription Taxes](#subscription-taxes) - [Subscription Anchor Date](#subscription-anchor-date) - [Canceling Subscriptions](#cancelling-subscriptions) @@ -47,18 +50,21 @@ - [Single Charges](#single-charges) - [Simple Charge](#simple-charge) - [Charge With Invoice](#charge-with-invoice) + - [Creating Payment Intents](#creating-payment-intents) - [Refunding Charges](#refunding-charges) - [Checkout](#checkout) - [Product Checkouts](#product-checkouts) - [Single Charge Checkouts](#single-charge-checkouts) - [Subscription Checkouts](#subscription-checkouts) - [Collecting Tax IDs](#collecting-tax-ids) + - [Guest Checkouts](#guest-checkouts) - [Invoices](#invoices) - [Retrieving Invoices](#retrieving-invoices) - [Upcoming Invoices](#upcoming-invoices) - [Previewing Subscription Invoices](#previewing-subscription-invoices) - [Generating Invoice PDFs](#generating-invoice-pdfs) - [Handling Failed Payments](#handling-failed-payments) + - [Confirming Payments](#confirming-payments) - [Strong Customer Authentication (SCA)](#strong-customer-authentication) - [Payments Requiring Additional Confirmation](#payments-requiring-additional-confirmation) - [Off-session Payment Notifications](#off-session-payment-notifications) @@ -75,7 +81,8 @@ When upgrading to a new version of Cashier, it's important that you carefully review [the upgrade guide](https://github.com/laravel/cashier-stripe/blob/master/UPGRADE.md). -> {note} To prevent breaking changes, Cashier uses a fixed Stripe API version. Cashier 13 utilizes Stripe API version `2020-08-27`. The Stripe API version will be updated on minor releases in order to make use of new Stripe features and improvements. +> [!WARNING] +> To prevent breaking changes, Cashier uses a fixed Stripe API version. Cashier 16 utilizes Stripe API version `2025-07-30.basil`. The Stripe API version will be updated on minor releases in order to make use of new Stripe features and improvements. ## Installation @@ -86,38 +93,30 @@ First, install the Cashier package for Stripe using the Composer package manager composer require laravel/cashier ``` -> {note} To ensure Cashier properly handles all Stripe events, remember to [set up Cashier's webhook handling](#handling-stripe-webhooks). +After installing the package, publish Cashier's migrations using the `vendor:publish` Artisan command: - -### Database Migrations +```shell +php artisan vendor:publish --tag="cashier-migrations" +``` -Cashier's service provider registers its own database migration directory, so remember to migrate your database after installing the package. The Cashier migrations will add several columns to your `users` table as well as create a new `subscriptions` table to hold all of your customer's subscriptions: +Then, migrate your database: ```shell php artisan migrate ``` -If you need to overwrite the migrations that ship with Cashier, you can publish them using the `vendor:publish` Artisan command: +Cashier's migrations will add several columns to your `users` table. They will also create a new `subscriptions` table to hold all of your customer's subscriptions and a `subscription_items` table for subscriptions with multiple prices. + +If you wish, you can also publish Cashier's configuration file using the `vendor:publish` Artisan command: ```shell -php artisan vendor:publish --tag="cashier-migrations" +php artisan vendor:publish --tag="cashier-config" ``` -If you would like to prevent Cashier's migrations from running entirely, you may use the `ignoreMigrations` method provided by Cashier. Typically, this method should be called in the `register` method of your `AppServiceProvider`: - - use Laravel\Cashier\Cashier; - - /** - * Register any application services. - * - * @return void - */ - public function register() - { - Cashier::ignoreMigrations(); - } +Lastly, to ensure Cashier properly handles all Stripe events, remember to [configure Cashier's webhook handling](#handling-stripe-webhooks). -> {note} Stripe recommends that any column used for storing Stripe identifiers should be case-sensitive. Therefore, you should ensure the column collation for the `stripe_id` column is set to `utf8_bin` when using MySQL. More information regarding this can be found in the [Stripe documentation](https://stripe.com/docs/upgrades#what-changes-does-stripe-consider-to-be-backwards-compatible). +> [!WARNING] +> Stripe recommends that any column used for storing Stripe identifiers should be case-sensitive. Therefore, you should ensure the column collation for the `stripe_id` column is set to `utf8_bin` when using MySQL. More information regarding this can be found in the [Stripe documentation](https://stripe.com/docs/upgrades#what-changes-does-stripe-consider-to-be-backwards-compatible). ## Configuration @@ -127,29 +126,32 @@ If you would like to prevent Cashier's migrations from running entirely, you may Before using Cashier, add the `Billable` trait to your billable model definition. Typically, this will be the `App\Models\User` model. This trait provides various methods to allow you to perform common billing tasks, such as creating subscriptions, applying coupons, and updating payment method information: - use Laravel\Cashier\Billable; +```php +use Laravel\Cashier\Billable; - class User extends Authenticatable - { - use Billable; - } +class User extends Authenticatable +{ + use Billable; +} +``` Cashier assumes your billable model will be the `App\Models\User` class that ships with Laravel. If you wish to change this you may specify a different model via the `useCustomerModel` method. This method should typically be called in the `boot` method of your `AppServiceProvider` class: - use App\Models\Cashier\User; - use Laravel\Cashier\Cashier; - - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - Cashier::useCustomerModel(User::class); - } +```php +use App\Models\Cashier\User; +use Laravel\Cashier\Cashier; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Cashier::useCustomerModel(User::class); +} +``` -> {note} If you're using a model other than Laravel's supplied `App\Models\User` model, you'll need to publish and alter the [Cashier migrations](#installation) provided to match your alternative model's table name. +> [!WARNING] +> If you're using a model other than Laravel's supplied `App\Models\User` model, you'll need to publish and alter the [Cashier migrations](#installation) provided to match your alternative model's table name. ### API Keys @@ -159,8 +161,12 @@ Next, you should configure your Stripe API keys in your application's `.env` fil ```ini STRIPE_KEY=your-stripe-key STRIPE_SECRET=your-stripe-secret +STRIPE_WEBHOOK_SECRET=your-stripe-webhook-secret ``` +> [!WARNING] +> You should ensure that the `STRIPE_WEBHOOK_SECRET` environment variable is defined in your application's `.env` file, as this variable is used to ensure that incoming webhooks are actually from Stripe. + ### Currency Configuration @@ -176,31 +182,30 @@ In addition to configuring Cashier's currency, you may also specify a locale to CASHIER_CURRENCY_LOCALE=nl_BE ``` -> {note} In order to use locales other than `en`, ensure the `ext-intl` PHP extension is installed and configured on your server. +> [!WARNING] +> In order to use locales other than `en`, ensure the `ext-intl` PHP extension is installed and configured on your server. ### Tax Configuration Thanks to [Stripe Tax](https://stripe.com/tax), it's possible to automatically calculate taxes for all invoices generated by Stripe. You can enable automatic tax calculation by invoking the `calculateTaxes` method in the `boot` method of your application's `App\Providers\AppServiceProvider` class: - use Laravel\Cashier\Cashier; +```php +use Laravel\Cashier\Cashier; - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - Cashier::calculateTaxes(); - } +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Cashier::calculateTaxes(); +} +``` Once tax calculation has been enabled, any new subscriptions and any one-off invoices that are generated will receive automatic tax calculation. For this feature to work properly, your customer's billing details, such as the customer's name, address, and tax ID, need to be synced to Stripe. You may use the [customer data synchronization](#syncing-customer-data-with-stripe) and [Tax ID](#tax-ids) methods offered by Cashier to accomplish this. -> {note} Unfortunately, for now, no tax is calculated for [single charges](#single-charges) or [single charge checkouts](#single-charge-checkouts). In addition, Stripe Tax is currently "invite-only" during its beta period. You can request access to Stripe Tax via the [Stripe Tax website](https://stripe.com/tax#request-access). - ### Logging @@ -217,28 +222,242 @@ Exceptions that are generated by API calls to Stripe will be logged through your You are free to extend the models used internally by Cashier by defining your own model and extending the corresponding Cashier model: - use Laravel\Cashier\Subscription as CashierSubscription; +```php +use Laravel\Cashier\Subscription as CashierSubscription; - class Subscription extends CashierSubscription - { - // ... - } +class Subscription extends CashierSubscription +{ + // ... +} +``` After defining your model, you may instruct Cashier to use your custom model via the `Laravel\Cashier\Cashier` class. Typically, you should inform Cashier about your custom models in the `boot` method of your application's `App\Providers\AppServiceProvider` class: - use App\Models\Cashier\Subscription; - use App\Models\Cashier\SubscriptionItem; +```php +use App\Models\Cashier\Subscription; +use App\Models\Cashier\SubscriptionItem; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Cashier::useSubscriptionModel(Subscription::class); + Cashier::useSubscriptionItemModel(SubscriptionItem::class); +} +``` + + +## Quickstart + + +### Selling Products + +> [!NOTE] +> Before utilizing Stripe Checkout, you should define Products with fixed prices in your Stripe dashboard. In addition, you should [configure Cashier's webhook handling](#handling-stripe-webhooks). + +Offering product and subscription billing via your application can be intimidating. However, thanks to Cashier and [Stripe Checkout](https://stripe.com/payments/checkout), you can easily build modern, robust payment integrations. + +To charge customers for non-recurring, single-charge products, we'll utilize Cashier to direct customers to Stripe Checkout, where they will provide their payment details and confirm their purchase. Once the payment has been made via Checkout, the customer will be redirected to a success URL of your choosing within your application: + +```php +use Illuminate\Http\Request; + +Route::get('/checkout', function (Request $request) { + $stripePriceId = 'price_deluxe_album'; + + $quantity = 1; + + return $request->user()->checkout([$stripePriceId => $quantity], [ + 'success_url' => route('checkout-success'), + 'cancel_url' => route('checkout-cancel'), + ]); +})->name('checkout'); + +Route::view('/checkout/success', 'checkout.success')->name('checkout-success'); +Route::view('/checkout/cancel', 'checkout.cancel')->name('checkout-cancel'); +``` + +As you can see in the example above, we will utilize Cashier's provided `checkout` method to redirect the customer to Stripe Checkout for a given "price identifier". When using Stripe, "prices" refer to [defined prices for specific products](https://stripe.com/docs/products-prices/how-products-and-prices-work). + +If necessary, the `checkout` method will automatically create a customer in Stripe and connect that Stripe customer record to the corresponding user in your application's database. After completing the checkout session, the customer will be redirected to a dedicated success or cancellation page where you can display an informational message to the customer. + + +#### Providing Meta Data to Stripe Checkout + +When selling products, it's common to keep track of completed orders and purchased products via `Cart` and `Order` models defined by your own application. When redirecting customers to Stripe Checkout to complete a purchase, you may need to provide an existing order identifier so that you can associate the completed purchase with the corresponding order when the customer is redirected back to your application. + +To accomplish this, you may provide an array of `metadata` to the `checkout` method. Let's imagine that a pending `Order` is created within our application when a user begins the checkout process. Remember, the `Cart` and `Order` models in this example are illustrative and not provided by Cashier. You are free to implement these concepts based on the needs of your own application: + +```php +use App\Models\Cart; +use App\Models\Order; +use Illuminate\Http\Request; + +Route::get('/cart/{cart}/checkout', function (Request $request, Cart $cart) { + $order = Order::create([ + 'cart_id' => $cart->id, + 'price_ids' => $cart->price_ids, + 'status' => 'incomplete', + ]); + + return $request->user()->checkout($order->price_ids, [ + 'success_url' => route('checkout-success').'?session_id={CHECKOUT_SESSION_ID}', + 'cancel_url' => route('checkout-cancel'), + 'metadata' => ['order_id' => $order->id], + ]); +})->name('checkout'); +``` + +As you can see in the example above, when a user begins the checkout process, we will provide all of the cart / order's associated Stripe price identifiers to the `checkout` method. Of course, your application is responsible for associating these items with the "shopping cart" or order as a customer adds them. We also provide the order's ID to the Stripe Checkout session via the `metadata` array. Finally, we have added the `CHECKOUT_SESSION_ID` template variable to the Checkout success route. When Stripe redirects customers back to your application, this template variable will automatically be populated with the Checkout session ID. + +Next, let's build the Checkout success route. This is the route that users will be redirected to after their purchase has been completed via Stripe Checkout. Within this route, we can retrieve the Stripe Checkout session ID and the associated Stripe Checkout instance in order to access our provided meta data and update our customer's order accordingly: + +```php +use App\Models\Order; +use Illuminate\Http\Request; +use Laravel\Cashier\Cashier; + +Route::get('/checkout/success', function (Request $request) { + $sessionId = $request->get('session_id'); + if ($sessionId === null) { + return; + } + + $session = Cashier::stripe()->checkout->sessions->retrieve($sessionId); + + if ($session->payment_status !== 'paid') { + return; + } + + $orderId = $session['metadata']['order_id'] ?? null; + + $order = Order::findOrFail($orderId); + + $order->update(['status' => 'completed']); + + return view('checkout-success', ['order' => $order]); +})->name('checkout-success'); +``` + +Please refer to Stripe's documentation for more information on the [data contained by the Checkout session object](https://stripe.com/docs/api/checkout/sessions/object). + + +### Selling Subscriptions + +> [!NOTE] +> Before utilizing Stripe Checkout, you should define Products with fixed prices in your Stripe dashboard. In addition, you should [configure Cashier's webhook handling](#handling-stripe-webhooks). + +Offering product and subscription billing via your application can be intimidating. However, thanks to Cashier and [Stripe Checkout](https://stripe.com/payments/checkout), you can easily build modern, robust payment integrations. + +To learn how to sell subscriptions using Cashier and Stripe Checkout, let's consider the simple scenario of a subscription service with a basic monthly (`price_basic_monthly`) and yearly (`price_basic_yearly`) plan. These two prices could be grouped under a "Basic" product (`pro_basic`) in our Stripe dashboard. In addition, our subscription service might offer an Expert plan as `pro_expert`. + +First, let's discover how a customer can subscribe to our services. Of course, you can imagine the customer might click a "subscribe" button for the Basic plan on our application's pricing page. This button or link should direct the user to a Laravel route which creates the Stripe Checkout session for their chosen plan: + +```php +use Illuminate\Http\Request; + +Route::get('/subscription-checkout', function (Request $request) { + return $request->user() + ->newSubscription('default', 'price_basic_monthly') + ->trialDays(5) + ->allowPromotionCodes() + ->checkout([ + 'success_url' => route('your-success-route'), + 'cancel_url' => route('your-cancel-route'), + ]); +}); +``` + +As you can see in the example above, we will redirect the customer to a Stripe Checkout session which will allow them to subscribe to our Basic plan. After a successful checkout or cancellation, the customer will be redirected back to the URL we provided to the `checkout` method. To know when their subscription has actually started (since some payment methods require a few seconds to process), we'll also need to [configure Cashier's webhook handling](#handling-stripe-webhooks). + +Now that customers can start subscriptions, we need to restrict certain portions of our application so that only subscribed users can access them. Of course, we can always determine a user's current subscription status via the `subscribed` method provided by Cashier's `Billable` trait: + +```blade +@if ($user->subscribed()) +

You are subscribed.

+@endif +``` + +We can even easily determine if a user is subscribed to specific product or price: + +```blade +@if ($user->subscribedToProduct('pro_basic')) +

You are subscribed to our Basic product.

+@endif + +@if ($user->subscribedToPrice('price_basic_monthly')) +

You are subscribed to our monthly Basic plan.

+@endif +``` + + +#### Building a Subscribed Middleware + +For convenience, you may wish to create a [middleware](/docs/{{version}}/middleware) which determines if the incoming request is from a subscribed user. Once this middleware has been defined, you may easily assign it to a route to prevent users that are not subscribed from accessing the route: + +```php +user()?->subscribed()) { + // Redirect user to billing page and ask them to subscribe... + return redirect('/billing'); + } + + return $next($request); } +} +``` + +Once the middleware has been defined, you may assign it to a route: + +```php +use App\Http\Middleware\Subscribed; + +Route::get('/dashboard', function () { + // ... +})->middleware([Subscribed::class]); +``` + + +#### Allowing Customers to Manage Their Billing Plan + +Of course, customers may want to change their subscription plan to another product or "tier". The easiest way to allow this is by directing customers to Stripe's [Customer Billing Portal](https://stripe.com/docs/no-code/customer-portal), which provides a hosted user interface that allows customers to download invoices, update their payment method, and change subscription plans. + +First, define a link or button within your application that directs users to a Laravel route which we will utilize to initiate a Billing Portal session: + +```blade + + Billing + +``` + +Next, let's define the route that initiates a Stripe Customer Billing Portal session and redirects the user to the Portal. The `redirectToBillingPortal` method accepts the URL that users should be returned to when exiting the Portal: + +```php +use Illuminate\Http\Request; + +Route::get('/billing', function (Request $request) { + return $request->user()->redirectToBillingPortal(route('dashboard')); +})->middleware(['auth'])->name('billing'); +``` + +> [!NOTE] +> As long as you have configured Cashier's webhook handling, Cashier will automatically keep your application's Cashier-related database tables in sync by inspecting the incoming webhooks from Stripe. So, for example, when a user cancels their subscription via Stripe's Customer Billing Portal, Cashier will receive the corresponding webhook and mark the subscription as "canceled" in your application's database. ## Customers @@ -248,84 +467,112 @@ After defining your model, you may instruct Cashier to use your custom model via You can retrieve a customer by their Stripe ID using the `Cashier::findBillable` method. This method will return an instance of the billable model: - use Laravel\Cashier\Cashier; +```php +use Laravel\Cashier\Cashier; - $user = Cashier::findBillable($stripeId); +$user = Cashier::findBillable($stripeId); +``` ### Creating Customers Occasionally, you may wish to create a Stripe customer without beginning a subscription. You may accomplish this using the `createAsStripeCustomer` method: - $stripeCustomer = $user->createAsStripeCustomer(); +```php +$stripeCustomer = $user->createAsStripeCustomer(); +``` Once the customer has been created in Stripe, you may begin a subscription at a later date. You may provide an optional `$options` array to pass in any additional [customer creation parameters that are supported by the Stripe API](https://stripe.com/docs/api/customers/create): - $stripeCustomer = $user->createAsStripeCustomer($options); +```php +$stripeCustomer = $user->createAsStripeCustomer($options); +``` You may use the `asStripeCustomer` method if you want to return the Stripe customer object for a billable model: - $stripeCustomer = $user->asStripeCustomer(); +```php +$stripeCustomer = $user->asStripeCustomer(); +``` The `createOrGetStripeCustomer` method may be used if you would like to retrieve the Stripe customer object for a given billable model but are not sure whether the billable model is already a customer within Stripe. This method will create a new customer in Stripe if one does not already exist: - $stripeCustomer = $user->createOrGetStripeCustomer(); +```php +$stripeCustomer = $user->createOrGetStripeCustomer(); +``` ### Updating Customers Occasionally, you may wish to update the Stripe customer directly with additional information. You may accomplish this using the `updateStripeCustomer` method. This method accepts an array of [customer update options supported by the Stripe API](https://stripe.com/docs/api/customers/update): - $stripeCustomer = $user->updateStripeCustomer($options); +```php +$stripeCustomer = $user->updateStripeCustomer($options); +``` ### Balances Stripe allows you to credit or debit a customer's "balance". Later, this balance will be credited or debited on new invoices. To check the customer's total balance you may use the `balance` method that is available on your billable model. The `balance` method will return a formatted string representation of the balance in the customer's currency: - $balance = $user->balance(); +```php +$balance = $user->balance(); +``` -To credit a customer's balance, you may provide a negative value to the `applyBalance` method. If you wish, you may also provide a description: +To credit a customer's balance, you may provide a value to the `creditBalance` method. If you wish, you may also provide a description: - $user->applyBalance(-500, 'Premium customer top-up.'); +```php +$user->creditBalance(500, 'Premium customer top-up.'); +``` -Providing a positive value to the `applyBalance` method will debit the customer's balance: +Providing a value to the `debitBalance` method will debit the customer's balance: - $user->applyBalance(300, 'Bad usage penalty.'); +```php +$user->debitBalance(300, 'Bad usage penalty.'); +``` The `applyBalance` method will create new customer balance transactions for the customer. You may retrieve these transaction records using the `balanceTransactions` method, which may be useful in order to provide a log of credits and debits for the customer to review: - // Retrieve all transactions... - $transactions = $user->balanceTransactions(); +```php +// Retrieve all transactions... +$transactions = $user->balanceTransactions(); - foreach ($transactions as $transaction) { - // Transaction amount... - $amount = $transaction->amount(); // $2.31 +foreach ($transactions as $transaction) { + // Transaction amount... + $amount = $transaction->amount(); // $2.31 - // Retrieve the related invoice when available... - $invoice = $transaction->invoice(); - } + // Retrieve the related invoice when available... + $invoice = $transaction->invoice(); +} +``` ### Tax IDs Cashier offers an easy way to manage a customer's tax IDs. For example, the `taxIds` method may be used to retrieve all of the [tax IDs](https://stripe.com/docs/api/customer_tax_ids/object) that are assigned to a customer as a collection: - $taxIds = $user->taxIds(); +```php +$taxIds = $user->taxIds(); +``` You can also retrieve a specific tax ID for a customer by its identifier: - $taxId = $user->findTaxId('txi_belgium'); +```php +$taxId = $user->findTaxId('txi_belgium'); +``` You may create a new Tax ID by providing a valid [type](https://stripe.com/docs/api/customer_tax_ids/object#tax_id_object-type) and value to the `createTaxId` method: - $taxId = $user->createTaxId('eu_vat', 'BE0123456789'); +```php +$taxId = $user->createTaxId('eu_vat', 'BE0123456789'); +``` The `createTaxId` method will immediately add the VAT ID to the customer's account. [Verification of VAT IDs is also done by Stripe](https://stripe.com/docs/invoicing/customer/tax-ids#validation); however, this is an asynchronous process. You can be notified of verification updates by subscribing to the `customer.tax_id.updated` webhook event and inspecting [the VAT IDs `verification` parameter](https://stripe.com/docs/api/customer_tax_ids/object#tax_id_object-verification). For more information on handling webhooks, please consult the [documentation on defining webhook handlers](#handling-stripe-webhooks). You may delete a tax ID using the `deleteTaxId` method: - $user->deleteTaxId('txi_belgium'); +```php +$user->deleteTaxId('txi_belgium'); +``` ### Syncing Customer Data With Stripe @@ -334,60 +581,67 @@ Typically, when your application's users update their name, email address, or ot To automate this, you may define an event listener on your billable model that reacts to the model's `updated` event. Then, within your event listener, you may invoke the `syncStripeCustomerDetails` method on the model: - use function Illuminate\Events\queueable; - - /** - * The "booted" method of the model. - * - * @return void - */ - protected static function booted() - { - static::updated(queueable(function ($customer) { - if ($customer->hasStripeId()) { - $customer->syncStripeCustomerDetails(); - } - })); - } +```php +use App\Models\User; +use function Illuminate\Events\queueable; + +/** + * The "booted" method of the model. + */ +protected static function booted(): void +{ + static::updated(queueable(function (User $customer) { + if ($customer->hasStripeId()) { + $customer->syncStripeCustomerDetails(); + } + })); +} +``` Now, every time your customer model is updated, its information will be synced with Stripe. For convenience, Cashier will automatically sync your customer's information with Stripe on the initial creation of the customer. You may customize the columns used for syncing customer information to Stripe by overriding a variety of methods provided by Cashier. For example, you may override the `stripeName` method to customize the attribute that should be considered the customer's "name" when Cashier syncs customer information to Stripe: - /** - * Get the customer name that should be synced to Stripe. - * - * @return string|null - */ - public function stripeName() - { - return $this->company_name; - } +```php +/** + * Get the customer name that should be synced to Stripe. + */ +public function stripeName(): string|null +{ + return $this->company_name; +} +``` -Similarly, you may override the `stripeEmail`, `stripePhone`, and `stripeAddress` methods. These methods will sync information to their corresponding customer parameters when [updating the Stripe customer object](https://stripe.com/docs/api/customers/update). If you wish to take total control over the customer information sync process, you may override the `syncStripeCustomerDetails` method. +Similarly, you may override the `stripeEmail`, `stripePhone` (20 character maximum), `stripeAddress`, and `stripePreferredLocales` methods. These methods will sync information to their corresponding customer parameters when [updating the Stripe customer object](https://stripe.com/docs/api/customers/update). If you wish to take total control over the customer information sync process, you may override the `syncStripeCustomerDetails` method. ### Billing Portal Stripe offers [an easy way to set up a billing portal](https://stripe.com/docs/billing/subscriptions/customer-portal) so that your customer can manage their subscription, payment methods, and view their billing history. You can redirect your users to the billing portal by invoking the `redirectToBillingPortal` method on the billable model from a controller or route: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/billing-portal', function (Request $request) { - return $request->user()->redirectToBillingPortal(); - }); +Route::get('/billing-portal', function (Request $request) { + return $request->user()->redirectToBillingPortal(); +}); +``` By default, when the user is finished managing their subscription, they will be able to return to the `home` route of your application via a link within the Stripe billing portal. You may provide a custom URL that the user should return to by passing the URL as an argument to the `redirectToBillingPortal` method: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/billing-portal', function (Request $request) { - return $request->user()->redirectToBillingPortal(route('billing')); - }); +Route::get('/billing-portal', function (Request $request) { + return $request->user()->redirectToBillingPortal(route('billing')); +}); +``` If you would like to generate the URL to the billing portal without generating an HTTP redirect response, you may invoke the `billingPortalUrl` method: - $url = $request->user()->billingPortalUrl(route('billing')); +```php +$url = $request->user()->billingPortalUrl(route('billing')); +``` ## Payment Methods @@ -395,16 +649,18 @@ If you would like to generate the URL to the billing portal without generating a ### Storing Payment Methods -In order to create subscriptions or perform "one off" charges with Stripe, you will need to store a payment method and retrieve its identifier from Stripe. The approach used to accomplish this differs based on whether you plan to use the payment method for subscriptions or single charges, so we will examine both below. +In order to create subscriptions or perform "one-off" charges with Stripe, you will need to store a payment method and retrieve its identifier from Stripe. The approach used to accomplish this differs based on whether you plan to use the payment method for subscriptions or single charges, so we will examine both below. -#### Payment Methods For Subscriptions +#### Payment Methods for Subscriptions When storing a customer's credit card information for future use by a subscription, the Stripe "Setup Intents" API must be used to securely gather the customer's payment method details. A "Setup Intent" indicates to Stripe the intention to charge a customer's payment method. Cashier's `Billable` trait includes the `createSetupIntent` method to easily create a new Setup Intent. You should invoke this method from the route or controller that will render the form which gathers your customer's payment method details: - return view('update-payment-method', [ - 'intent' => $user->createSetupIntent() - ]); +```php +return view('update-payment-method', [ + 'intent' => $user->createSetupIntent() +]); +``` After you have created the Setup Intent and passed it to the view, you should attach its secret to the element that will gather the payment method. For example, consider this "update payment method" form: @@ -461,10 +717,11 @@ cardButton.addEventListener('click', async (e) => { After the card has been verified by Stripe, you may pass the resulting `setupIntent.payment_method` identifier to your Laravel application, where it can be attached to the customer. The payment method can either be [added as a new payment method](#adding-payment-methods) or [used to update the default payment method](#updating-the-default-payment-method). You can also immediately use the payment method identifier to [create a new subscription](#creating-subscriptions). -> {tip} If you would like more information about Setup Intents and gathering customer payment details please [review this overview provided by Stripe](https://stripe.com/docs/payments/save-and-reuse#php). +> [!NOTE] +> If you would like more information about Setup Intents and gathering customer payment details please [review this overview provided by Stripe](https://stripe.com/docs/payments/save-and-reuse#php). -#### Payment Methods For Single Charges +#### Payment Methods for Single Charges Of course, when making a single charge against a customer's payment method, we will only need to use a payment method identifier once. Due to Stripe limitations, you may not use the stored default payment method of a customer for single charges. You must allow the customer to enter their payment method details using the Stripe.js library. For example, consider the following form: @@ -522,83 +779,114 @@ If the card is verified successfully, you may pass the `paymentMethod.id` to you The `paymentMethods` method on the billable model instance returns a collection of `Laravel\Cashier\PaymentMethod` instances: - $paymentMethods = $user->paymentMethods(); +```php +$paymentMethods = $user->paymentMethods(); +``` -By default, this method will return payment methods of the `card` type. To retrieve payment methods of a different type, you may pass the `type` as an argument to the method: +By default, this method will return payment methods of every type. To retrieve payment methods of a specific type, you may pass the `type` as an argument to the method: - $paymentMethods = $user->paymentMethods('sepa_debit'); +```php +$paymentMethods = $user->paymentMethods('sepa_debit'); +``` To retrieve the customer's default payment method, the `defaultPaymentMethod` method may be used: - $paymentMethod = $user->defaultPaymentMethod(); +```php +$paymentMethod = $user->defaultPaymentMethod(); +``` You can retrieve a specific payment method that is attached to the billable model using the `findPaymentMethod` method: - $paymentMethod = $user->findPaymentMethod($paymentMethodId); +```php +$paymentMethod = $user->findPaymentMethod($paymentMethodId); +``` - -### Determining If A User Has A Payment Method + +### Payment Method Presence To determine if a billable model has a default payment method attached to their account, invoke the `hasDefaultPaymentMethod` method: - if ($user->hasDefaultPaymentMethod()) { - // - } +```php +if ($user->hasDefaultPaymentMethod()) { + // ... +} +``` You may use the `hasPaymentMethod` method to determine if a billable model has at least one payment method attached to their account: - if ($user->hasPaymentMethod()) { - // - } +```php +if ($user->hasPaymentMethod()) { + // ... +} +``` -This method will determine if the billable model has payment methods of the `card` type. To determine if a payment method of another type exists for the model, you may pass the `type` as an argument to the method: +This method will determine if the billable model has any payment method at all. To determine if a payment method of a specific type exists for the model, you may pass the `type` as an argument to the method: - if ($user->hasPaymentMethod('sepa_debit')) { - // - } +```php +if ($user->hasPaymentMethod('sepa_debit')) { + // ... +} +``` -### Updating The Default Payment Method +### Updating the Default Payment Method The `updateDefaultPaymentMethod` method may be used to update a customer's default payment method information. This method accepts a Stripe payment method identifier and will assign the new payment method as the default billing payment method: - $user->updateDefaultPaymentMethod($paymentMethod); +```php +$user->updateDefaultPaymentMethod($paymentMethod); +``` To sync your default payment method information with the customer's default payment method information in Stripe, you may use the `updateDefaultPaymentMethodFromStripe` method: - $user->updateDefaultPaymentMethodFromStripe(); +```php +$user->updateDefaultPaymentMethodFromStripe(); +``` -> {note} The default payment method on a customer can only be used for invoicing and creating new subscriptions. Due to limitations imposed by Stripe, it may not be used for single charges. +> [!WARNING] +> The default payment method on a customer can only be used for invoicing and creating new subscriptions. Due to limitations imposed by Stripe, it may not be used for single charges. ### Adding Payment Methods To add a new payment method, you may call the `addPaymentMethod` method on the billable model, passing the payment method identifier: - $user->addPaymentMethod($paymentMethod); +```php +$user->addPaymentMethod($paymentMethod); +``` -> {tip} To learn how to retrieve payment method identifiers please review the [payment method storage documentation](#storing-payment-methods). +> [!NOTE] +> To learn how to retrieve payment method identifiers please review the [payment method storage documentation](#storing-payment-methods). ### Deleting Payment Methods To delete a payment method, you may call the `delete` method on the `Laravel\Cashier\PaymentMethod` instance you wish to delete: - $paymentMethod->delete(); +```php +$paymentMethod->delete(); +``` The `deletePaymentMethod` method will delete a specific payment method from the billable model: - $user->deletePaymentMethod('pm_visa'); +```php +$user->deletePaymentMethod('pm_visa'); +``` The `deletePaymentMethods` method will delete all of the payment method information for the billable model: - $user->deletePaymentMethods(); +```php +$user->deletePaymentMethods(); +``` -By default, this method will delete payment methods of the `card` type. To delete payment methods of a different type you can pass the `type` as an argument to the method: +By default, this method will delete payment methods of every type. To delete payment methods of a specific type you can pass the `type` as an argument to the method: - $user->deletePaymentMethods('sepa_debit'); +```php +$user->deletePaymentMethods('sepa_debit'); +``` -> {note} If a user has an active subscription, your application should not allow them to delete their default payment method. +> [!WARNING] +> If a user has an active subscription, your application should not allow them to delete their default payment method. ## Subscriptions @@ -610,175 +898,271 @@ Subscriptions provide a way to set up recurring payments for your customers. Str To create a subscription, first retrieve an instance of your billable model, which typically will be an instance of `App\Models\User`. Once you have retrieved the model instance, you may use the `newSubscription` method to create the model's subscription: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::post('/user/subscribe', function (Request $request) { - $request->user()->newSubscription( - 'default', 'price_monthly' - )->create($request->paymentMethodId); +Route::post('/user/subscribe', function (Request $request) { + $request->user()->newSubscription( + 'default', 'price_monthly' + )->create($request->paymentMethodId); - // ... - }); + // ... +}); +``` -The first argument passed to the `newSubscription` method should be the internal name of the subscription. If your application only offers a single subscription, you might call this `default` or `primary`. This subscription name is only for internal application usage and is not meant to be shown to users. In addition, it should not contain spaces and it should never be changed after creating the subscription. The second argument is the specific price the user is subscribing to. This value should correspond to the price's identifier in Stripe. +The first argument passed to the `newSubscription` method should be the internal type of the subscription. If your application only offers a single subscription, you might call this `default` or `primary`. This subscription type is only for internal application usage and is not meant to be shown to users. In addition, it should not contain spaces and it should never be changed after creating the subscription. The second argument is the specific price the user is subscribing to. This value should correspond to the price's identifier in Stripe. The `create` method, which accepts [a Stripe payment method identifier](#storing-payment-methods) or Stripe `PaymentMethod` object, will begin the subscription as well as update your database with the billable model's Stripe customer ID and other relevant billing information. -> {note} Passing a payment method identifier directly to the `create` subscription method will also automatically add it to the user's stored payment methods. +> [!WARNING] +> Passing a payment method identifier directly to the `create` subscription method will also automatically add it to the user's stored payment methods. -#### Collecting Recurring Payments Via Invoice Emails +#### Collecting Recurring Payments via Invoice Emails Instead of collecting a customer's recurring payments automatically, you may instruct Stripe to email an invoice to the customer each time their recurring payment is due. Then, the customer may manually pay the invoice once they receive it. The customer does not need to provide a payment method up front when collecting recurring payments via invoices: - $user->newSubscription('default', 'price_monthly')->createAndSendInvoice(); +```php +$user->newSubscription('default', 'price_monthly')->createAndSendInvoice(); +``` + +The amount of time a customer has to pay their invoice before their subscription is canceled is determined by the `days_until_due` option. By default, this is 30 days; however, you may provide a specific value for this option if you wish: -The amount of time a customer has to pay their invoice before their subscription is canceled is determined by your subscription and invoice settings within the [Stripe dashboard](https://dashboard.stripe.com/settings/billing/automatic). +```php +$user->newSubscription('default', 'price_monthly')->createAndSendInvoice([], [ + 'days_until_due' => 30 +]); +``` #### Quantities If you would like to set a specific [quantity](https://stripe.com/docs/billing/subscriptions/quantities) for the price when creating the subscription, you should invoke the `quantity` method on the subscription builder before creating the subscription: - $user->newSubscription('default', 'price_monthly') - ->quantity(5) - ->create($paymentMethod); +```php +$user->newSubscription('default', 'price_monthly') + ->quantity(5) + ->create($paymentMethod); +``` #### Additional Details If you would like to specify additional [customer](https://stripe.com/docs/api/customers/create) or [subscription](https://stripe.com/docs/api/subscriptions/create) options supported by Stripe, you may do so by passing them as the second and third arguments to the `create` method: - $user->newSubscription('default', 'price_monthly')->create($paymentMethod, [ - 'email' => $email, - ], [ - 'metadata' => ['note' => 'Some extra information.'], - ]); +```php +$user->newSubscription('default', 'price_monthly')->create($paymentMethod, [ + 'email' => $email, +], [ + 'metadata' => ['note' => 'Some extra information.'], +]); +``` #### Coupons If you would like to apply a coupon when creating the subscription, you may use the `withCoupon` method: - $user->newSubscription('default', 'price_monthly') - ->withCoupon('code') - ->create($paymentMethod); +```php +$user->newSubscription('default', 'price_monthly') + ->withCoupon('code') + ->create($paymentMethod); +``` + +Or, if you would like to apply a [Stripe promotion code](https://stripe.com/docs/billing/subscriptions/discounts/codes), you may use the `withPromotionCode` method: + +```php +$user->newSubscription('default', 'price_monthly') + ->withPromotionCode('promo_code_id') + ->create($paymentMethod); +``` + +The given promotion code ID should be the Stripe API ID assigned to the promotion code and not the customer facing promotion code. If you need to find a promotion code ID based on a given customer facing promotion code, you may use the `findPromotionCode` method: + +```php +// Find a promotion code ID by its customer facing code... +$promotionCode = $user->findPromotionCode('SUMMERSALE'); + +// Find an active promotion code ID by its customer facing code... +$promotionCode = $user->findActivePromotionCode('SUMMERSALE'); +``` + +In the example above, the returned `$promotionCode` object is an instance of `Laravel\Cashier\PromotionCode`. This class decorates an underlying `Stripe\PromotionCode` object. You can retrieve the coupon related to the promotion code by invoking the `coupon` method: + +```php +$coupon = $user->findPromotionCode('SUMMERSALE')->coupon(); +``` + +The coupon instance allows you to determine the discount amount and whether the coupon represents a fixed discount or percentage based discount: -Or, if you would like to apply a [Stripe promotion code](https://stripe.com/docs/billing/subscriptions/discounts/codes), you may use the `withPromotionCode` method. The given promotion code ID should be the Stripe API ID assigned to the promotion code and not the customer facing promotion code: +```php +if ($coupon->isPercentage()) { + return $coupon->percentOff().'%'; // 21.5% +} else { + return $coupon->amountOff(); // $5.99 +} +``` + +You can also retrieve the discounts that are currently applied to a customer or subscription: + +```php +$discount = $billable->discount(); + +$discount = $subscription->discount(); +``` + +The returned `Laravel\Cashier\Discount` instances decorate an underlying `Stripe\Discount` object instance. You may retrieve the coupon related to this discount by invoking the `coupon` method: + +```php +$coupon = $subscription->discount()->coupon(); +``` - $user->newSubscription('default', 'price_monthly') - ->withPromotionCode('promo_code') - ->create($paymentMethod); +If you would like to apply a new coupon or promotion code to a customer or subscription, you may do so via the `applyCoupon` or `applyPromotionCode` methods: + +```php +$billable->applyCoupon('coupon_id'); +$billable->applyPromotionCode('promotion_code_id'); + +$subscription->applyCoupon('coupon_id'); +$subscription->applyPromotionCode('promotion_code_id'); +``` + +Remember, you should use the Stripe API ID assigned to the promotion code and not the customer facing promotion code. Only one coupon or promotion code can be applied to a customer or subscription at a given time. + +For more info on this subject, please consult the Stripe documentation regarding [coupons](https://stripe.com/docs/billing/subscriptions/coupons) and [promotion codes](https://stripe.com/docs/billing/subscriptions/coupons/codes). #### Adding Subscriptions If you would like to add a subscription to a customer who already has a default payment method you may invoke the `add` method on the subscription builder: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $user->newSubscription('default', 'price_monthly')->add(); +$user->newSubscription('default', 'price_monthly')->add(); +``` -#### Creating Subscriptions From The Stripe Dashboard +#### Creating Subscriptions From the Stripe Dashboard -You may also create subscriptions from the Stripe dashboard itself. When doing so, Cashier will sync newly added subscriptions and assign them a name of `default`. To customize the subscription name that is assigned to dashboard created subscriptions, [extend the `WebhookController`](/docs/{{version}}/billing#defining-webhook-event-handlers) and overwrite the `newSubscriptionName` method. +You may also create subscriptions from the Stripe dashboard itself. When doing so, Cashier will sync newly added subscriptions and assign them a type of `default`. To customize the subscription type that is assigned to dashboard created subscriptions, [define webhook event handlers](#defining-webhook-event-handlers). -In addition, you may only create one type of subscription via the Stripe dashboard. If your application offers multiple subscriptions that use different names, only one type of subscription may be added through the Stripe dashboard. +In addition, you may only create one type of subscription via the Stripe dashboard. If your application offers multiple subscriptions that use different types, only one type of subscription may be added through the Stripe dashboard. -Finally, you should always make sure to only add one active subscription per type of subscription offered by your application. If customer has two `default` subscriptions, only the most recently added subscription will be used by Cashier even though both would be synced with your application's database. +Finally, you should always make sure to only add one active subscription per type of subscription offered by your application. If a customer has two `default` subscriptions, only the most recently added subscription will be used by Cashier even though both would be synced with your application's database. ### Checking Subscription Status -Once a customer is subscribed to your application, you may easily check their subscription status using a variety of convenient methods. First, the `subscribed` method returns `true` if the customer has an active subscription, even if the subscription is currently within its trial period. The `subscribed` method accepts the name of the subscription as its first argument: +Once a customer is subscribed to your application, you may easily check their subscription status using a variety of convenient methods. First, the `subscribed` method returns `true` if the customer has an active subscription, even if the subscription is currently within its trial period. The `subscribed` method accepts the type of the subscription as its first argument: - if ($user->subscribed('default')) { - // - } +```php +if ($user->subscribed('default')) { + // ... +} +``` The `subscribed` method also makes a great candidate for a [route middleware](/docs/{{version}}/middleware), allowing you to filter access to routes and controllers based on the user's subscription status: - user() && ! $request->user()->subscribed('default')) { - // This user is not a paying customer... - return redirect('billing'); - } - - return $next($request); + if ($request->user() && ! $request->user()->subscribed('default')) { + // This user is not a paying customer... + return redirect('/billing'); } + + return $next($request); } +} +``` If you would like to determine if a user is still within their trial period, you may use the `onTrial` method. This method can be useful for determining if you should display a warning to the user that they are still on their trial period: - if ($user->subscription('default')->onTrial()) { - // - } +```php +if ($user->subscription('default')->onTrial()) { + // ... +} +``` The `subscribedToProduct` method may be used to determine if the user is subscribed to a given product based on a given Stripe product's identifier. In Stripe, products are collections of prices. In this example, we will determine if the user's `default` subscription is actively subscribed to the application's "premium" product. The given Stripe product identifier should correspond to one of your product's identifiers in the Stripe dashboard: - if ($user->subscribedToProduct('prod_premium', 'default')) { - // - } +```php +if ($user->subscribedToProduct('prod_premium', 'default')) { + // ... +} +``` By passing an array to the `subscribedToProduct` method, you may determine if the user's `default` subscription is actively subscribed to the application's "basic" or "premium" product: - if ($user->subscribedToProduct(['prod_basic', 'prod_premium'], 'default')) { - // - } +```php +if ($user->subscribedToProduct(['prod_basic', 'prod_premium'], 'default')) { + // ... +} +``` The `subscribedToPrice` method may be used to determine if a customer's subscription corresponds to a given price ID: - if ($user->subscribedToPrice('price_basic_monthly', 'default')) { - // - } +```php +if ($user->subscribedToPrice('price_basic_monthly', 'default')) { + // ... +} +``` The `recurring` method may be used to determine if the user is currently subscribed and is no longer within their trial period: - if ($user->subscription('default')->recurring()) { - // - } +```php +if ($user->subscription('default')->recurring()) { + // ... +} +``` -> {note} If a user has two subscriptions with the same name, the most recent subscription will always be returned by the `subscription` method. For example, a user might have two subscription records named `default`; however, one of the subscriptions may be an old, expired subscription, while the other is the current, active subscription. The most recent subscription will always be returned while older subscriptions are kept in the database for historical review. +> [!WARNING] +> If a user has two subscriptions with the same type, the most recent subscription will always be returned by the `subscription` method. For example, a user might have two subscription records with the type of `default`; however, one of the subscriptions may be an old, expired subscription, while the other is the current, active subscription. The most recent subscription will always be returned while older subscriptions are kept in the database for historical review. #### Canceled Subscription Status To determine if the user was once an active subscriber but has canceled their subscription, you may use the `canceled` method: - if ($user->subscription('default')->canceled()) { - // - } +```php +if ($user->subscription('default')->canceled()) { + // ... +} +``` You may also determine if a user has canceled their subscription but are still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was originally scheduled to expire on March 10th, the user is on their "grace period" until March 10th. Note that the `subscribed` method still returns `true` during this time: - if ($user->subscription('default')->onGracePeriod()) { - // - } +```php +if ($user->subscription('default')->onGracePeriod()) { + // ... +} +``` To determine if the user has canceled their subscription and is no longer within their "grace period", you may use the `ended` method: - if ($user->subscription('default')->ended()) { - // - } +```php +if ($user->subscription('default')->ended()) { + // ... +} +``` #### Incomplete and Past Due Status @@ -787,13 +1171,15 @@ If a subscription requires a secondary payment action after creation the subscri Similarly, if a secondary payment action is required when swapping prices the subscription will be marked as `past_due`. When your subscription is in either of these states it will not be active until the customer has confirmed their payment. Determining if a subscription has an incomplete payment may be accomplished using the `hasIncompletePayment` method on the billable model or a subscription instance: - if ($user->hasIncompletePayment('default')) { - // - } +```php +if ($user->hasIncompletePayment('default')) { + // ... +} - if ($user->subscription('default')->hasIncompletePayment()) { - // - } +if ($user->subscription('default')->hasIncompletePayment()) { + // ... +} +``` When a subscription has an incomplete payment, you should direct the user to Cashier's payment confirmation page, passing the `latestPayment` identifier. You may use the `latestPayment` method available on subscription instance to retrieve this identifier: @@ -803,395 +1189,481 @@ When a subscription has an incomplete payment, you should direct the user to Cas ``` -If you would like the subscription to still be considered active when it's in a `past_due` state, you may use the `keepPastDueSubscriptionsActive` method provided by Cashier. Typically, this method should be called in the `register` method of your `App\Providers\AppServiceProvider`: +If you would like the subscription to still be considered active when it's in a `past_due` or `incomplete` state, you may use the `keepPastDueSubscriptionsActive` and `keepIncompleteSubscriptionsActive` methods provided by Cashier. Typically, these methods should be called in the `register` method of your `App\Providers\AppServiceProvider`: - use Laravel\Cashier\Cashier; +```php +use Laravel\Cashier\Cashier; - /** - * Register any application services. - * - * @return void - */ - public function register() - { - Cashier::keepPastDueSubscriptionsActive(); - } +/** + * Register any application services. + */ +public function register(): void +{ + Cashier::keepPastDueSubscriptionsActive(); + Cashier::keepIncompleteSubscriptionsActive(); +} +``` -> {note} When a subscription is in an `incomplete` state it cannot be changed until the payment is confirmed. Therefore, the `swap` and `updateQuantity` methods will throw an exception when the subscription is in an `incomplete` state. +> [!WARNING] +> When a subscription is in an `incomplete` state it cannot be changed until the payment is confirmed. Therefore, the `swap` and `updateQuantity` methods will throw an exception when the subscription is in an `incomplete` state. #### Subscription Scopes Most subscription states are also available as query scopes so that you may easily query your database for subscriptions that are in a given state: - // Get all active subscriptions... - $subscriptions = Subscription::query()->active()->get(); +```php +// Get all active subscriptions... +$subscriptions = Subscription::query()->active()->get(); - // Get all of the canceled subscriptions for a user... - $subscriptions = $user->subscriptions()->canceled()->get(); +// Get all of the canceled subscriptions for a user... +$subscriptions = $user->subscriptions()->canceled()->get(); +``` A complete list of available scopes is available below: - Subscription::query()->active(); - Subscription::query()->canceled(); - Subscription::query()->ended(); - Subscription::query()->incomplete(); - Subscription::query()->notCanceled(); - Subscription::query()->notOnGracePeriod(); - Subscription::query()->notOnTrial(); - Subscription::query()->onGracePeriod(); - Subscription::query()->onTrial(); - Subscription::query()->pastDue(); - Subscription::query()->recurring(); +```php +Subscription::query()->active(); +Subscription::query()->canceled(); +Subscription::query()->ended(); +Subscription::query()->incomplete(); +Subscription::query()->notCanceled(); +Subscription::query()->notOnGracePeriod(); +Subscription::query()->notOnTrial(); +Subscription::query()->onGracePeriod(); +Subscription::query()->onTrial(); +Subscription::query()->pastDue(); +Subscription::query()->recurring(); +``` ### Changing Prices After a customer is subscribed to your application, they may occasionally want to change to a new subscription price. To swap a customer to a new price, pass the Stripe price's identifier to the `swap` method. When swapping prices, it is assumed that the user would like to re-activate their subscription if it was previously canceled. The given price identifier should correspond to a Stripe price identifier available in the Stripe dashboard: - use App\Models\User; +```php +use App\Models\User; - $user = App\Models\User::find(1); +$user = App\Models\User::find(1); - $user->subscription('default')->swap('price_yearly'); +$user->subscription('default')->swap('price_yearly'); +``` If the customer is on trial, the trial period will be maintained. Additionally, if a "quantity" exists for the subscription, that quantity will also be maintained. If you would like to swap prices and cancel any trial period the customer is currently on, you may invoke the `skipTrial` method: - $user->subscription('default') - ->skipTrial() - ->swap('price_yearly'); +```php +$user->subscription('default') + ->skipTrial() + ->swap('price_yearly'); +``` If you would like to swap prices and immediately invoice the customer instead of waiting for their next billing cycle, you may use the `swapAndInvoice` method: - $user = User::find(1); +```php +$user = User::find(1); - $user->subscription('default')->swapAndInvoice('price_yearly'); +$user->subscription('default')->swapAndInvoice('price_yearly'); +``` #### Prorations By default, Stripe prorates charges when swapping between prices. The `noProrate` method may be used to update the subscription's price without prorating the charges: - $user->subscription('default')->noProrate()->swap('price_yearly'); +```php +$user->subscription('default')->noProrate()->swap('price_yearly'); +``` For more information on subscription proration, consult the [Stripe documentation](https://stripe.com/docs/billing/subscriptions/prorations). -> {note} Executing the `noProrate` method before the `swapAndInvoice` method will have no effect on proration. An invoice will always be issued. +> [!WARNING] +> Executing the `noProrate` method before the `swapAndInvoice` method will have no effect on proration. An invoice will always be issued. ### Subscription Quantity Sometimes subscriptions are affected by "quantity". For example, a project management application might charge $10 per month per project. You may use the `incrementQuantity` and `decrementQuantity` methods to easily increment or decrement your subscription quantity: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $user->subscription('default')->incrementQuantity(); +$user->subscription('default')->incrementQuantity(); - // Add five to the subscription's current quantity... - $user->subscription('default')->incrementQuantity(5); +// Add five to the subscription's current quantity... +$user->subscription('default')->incrementQuantity(5); - $user->subscription('default')->decrementQuantity(); +$user->subscription('default')->decrementQuantity(); - // Subtract five from the subscription's current quantity... - $user->subscription('default')->decrementQuantity(5); +// Subtract five from the subscription's current quantity... +$user->subscription('default')->decrementQuantity(5); +``` Alternatively, you may set a specific quantity using the `updateQuantity` method: - $user->subscription('default')->updateQuantity(10); +```php +$user->subscription('default')->updateQuantity(10); +``` The `noProrate` method may be used to update the subscription's quantity without prorating the charges: - $user->subscription('default')->noProrate()->updateQuantity(10); +```php +$user->subscription('default')->noProrate()->updateQuantity(10); +``` For more information on subscription quantities, consult the [Stripe documentation](https://stripe.com/docs/subscriptions/quantities). - -#### Multiprice Subscription Quantities + +#### Quantities for Subscriptions With Multiple Products -If your subscription is a [multiprice subscription](#multiprice-subscriptions), you should pass the name of the price whose quantity you wish to increment or decrement as the second argument to the increment / decrement methods: +If your subscription is a [subscription with multiple products](#subscriptions-with-multiple-products), you should pass the ID of the price whose quantity you wish to increment or decrement as the second argument to the increment / decrement methods: - $user->subscription('default')->incrementQuantity(1, 'price_chat'); +```php +$user->subscription('default')->incrementQuantity(1, 'price_chat'); +``` - -### Multiprice Subscriptions + +### Subscriptions With Multiple Products -[Multiprice subscriptions](https://stripe.com/docs/billing/subscriptions/multiple-products) allow you to assign multiple billing prices to a single subscription. For example, imagine you are building a customer service "helpdesk" application that has a base subscription price of $10 per month but offers a live chat add-on price for an additional $15 per month. Multiprice subscription information is stored in Cashier's `subscription_items` database table. +[Subscription with multiple products](https://stripe.com/docs/billing/subscriptions/multiple-products) allow you to assign multiple billing products to a single subscription. For example, imagine you are building a customer service "helpdesk" application that has a base subscription price of $10 per month but offers a live chat add-on product for an additional $15 per month. Information for subscriptions with multiple products is stored in Cashier's `subscription_items` database table. -You may specify multiple prices for a given subscription by passing an array of prices as the second argument to the `newSubscription` method: +You may specify multiple products for a given subscription by passing an array of prices as the second argument to the `newSubscription` method: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::post('/user/subscribe', function (Request $request) { - $request->user()->newSubscription('default', [ - 'price_monthly', - 'price_chat', - ])->create($request->paymentMethodId); +Route::post('/user/subscribe', function (Request $request) { + $request->user()->newSubscription('default', [ + 'price_monthly', + 'price_chat', + ])->create($request->paymentMethodId); - // ... - }); + // ... +}); +``` In the example above, the customer will have two prices attached to their `default` subscription. Both prices will be charged on their respective billing intervals. If necessary, you may use the `quantity` method to indicate a specific quantity for each price: - $user = User::find(1); +```php +$user = User::find(1); - $user->newSubscription('default', ['price_monthly', 'price_chat']) - ->quantity(5, 'price_chat') - ->create($paymentMethod); +$user->newSubscription('default', ['price_monthly', 'price_chat']) + ->quantity(5, 'price_chat') + ->create($paymentMethod); +``` If you would like to add another price to an existing subscription, you may invoke the subscription's `addPrice` method: - $user = User::find(1); +```php +$user = User::find(1); - $user->subscription('default')->addPrice('price_chat'); +$user->subscription('default')->addPrice('price_chat'); +``` The example above will add the new price and the customer will be billed for it on their next billing cycle. If you would like to bill the customer immediately you may use the `addPriceAndInvoice` method: - $user->subscription('default')->addPriceAndInvoice('price_chat'); +```php +$user->subscription('default')->addPriceAndInvoice('price_chat'); +``` If you would like to add a price with a specific quantity, you can pass the quantity as the second argument of the `addPrice` or `addPriceAndInvoice` methods: - $user = User::find(1); +```php +$user = User::find(1); - $user->subscription('default')->addPrice('price_chat', 5); +$user->subscription('default')->addPrice('price_chat', 5); +``` You may remove prices from subscriptions using the `removePrice` method: - $user->subscription('default')->removePrice('price_chat'); +```php +$user->subscription('default')->removePrice('price_chat'); +``` -> {note} You may not remove the last price on a subscription. Instead, you should simply cancel the subscription. +> [!WARNING] +> You may not remove the last price on a subscription. Instead, you should simply cancel the subscription. #### Swapping Prices -You may also change the prices attached to a multiprice subscription. For example, imagine a customer has a `price_basic` subscription with a `price_chat` add-on price and you want to upgrade the customer from the `price_basic` to the `price_pro` price: +You may also change the prices attached to a subscription with multiple products. For example, imagine a customer has a `price_basic` subscription with a `price_chat` add-on product and you want to upgrade the customer from the `price_basic` to the `price_pro` price: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $user->subscription('default')->swap(['price_pro', 'price_chat']); +$user->subscription('default')->swap(['price_pro', 'price_chat']); +``` When executing the example above, the underlying subscription item with the `price_basic` is deleted and the one with the `price_chat` is preserved. Additionally, a new subscription item for the `price_pro` is created. You can also specify subscription item options by passing an array of key / value pairs to the `swap` method. For example, you may need to specify the subscription price quantities: - $user = User::find(1); +```php +$user = User::find(1); - $user->subscription('default')->swap([ - 'price_pro' => ['quantity' => 5], - 'price_chat' - ]); +$user->subscription('default')->swap([ + 'price_pro' => ['quantity' => 5], + 'price_chat' +]); +``` If you want to swap a single price on a subscription, you may do so using the `swap` method on the subscription item itself. This approach is particularly useful if you would like to preserve all of the existing metadata on the subscription's other prices: - $user = User::find(1); +```php +$user = User::find(1); - $user->subscription('default') - ->findItemOrFail('price_basic') - ->swap('price_pro'); +$user->subscription('default') + ->findItemOrFail('price_basic') + ->swap('price_pro'); +``` #### Proration -By default, Stripe will prorate charges when adding or removing prices from a multiprice subscription. If you would like to make a price adjustment without proration, you should chain the `noProrate` method onto your price operation: +By default, Stripe will prorate charges when adding or removing prices from a subscription with multiple products. If you would like to make a price adjustment without proration, you should chain the `noProrate` method onto your price operation: - $user->subscription('default')->noProrate()->removePrice('price_chat'); +```php +$user->subscription('default')->noProrate()->removePrice('price_chat'); +``` #### Quantities -If you would like to update quantities on individual subscription prices, you may do so using the [existing quantity methods](#subscription-quantity) by passing the name of the price as an additional argument to the method: +If you would like to update quantities on individual subscription prices, you may do so using the [existing quantity methods](#subscription-quantity) by passing the ID of the price as an additional argument to the method: - $user = User::find(1); +```php +$user = User::find(1); - $user->subscription('default')->incrementQuantity(5, 'price_chat'); +$user->subscription('default')->incrementQuantity(5, 'price_chat'); - $user->subscription('default')->decrementQuantity(3, 'price_chat'); +$user->subscription('default')->decrementQuantity(3, 'price_chat'); - $user->subscription('default')->updateQuantity(10, 'price_chat'); +$user->subscription('default')->updateQuantity(10, 'price_chat'); +``` -> {note} When a subscription has multiple prices the `stripe_price` and `quantity` attributes on the `Subscription` model will be `null`. To access the individual price attributes, you should use the `items` relationship available on the `Subscription` model. +> [!WARNING] +> When a subscription has multiple prices the `stripe_price` and `quantity` attributes on the `Subscription` model will be `null`. To access the individual price attributes, you should use the `items` relationship available on the `Subscription` model. #### Subscription Items When a subscription has multiple prices, it will have multiple subscription "items" stored in your database's `subscription_items` table. You may access these via the `items` relationship on the subscription: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $subscriptionItem = $user->subscription('default')->items->first(); +$subscriptionItem = $user->subscription('default')->items->first(); - // Retrieve the Stripe price and quantity for a specific item... - $stripePrice = $subscriptionItem->stripe_price; - $quantity = $subscriptionItem->quantity; +// Retrieve the Stripe price and quantity for a specific item... +$stripePrice = $subscriptionItem->stripe_price; +$quantity = $subscriptionItem->quantity; +``` You can also retrieve a specific price using the `findItemOrFail` method: - $user = User::find(1); +```php +$user = User::find(1); - $subscriptionItem = $user->subscription('default')->findItemOrFail('price_chat'); +$subscriptionItem = $user->subscription('default')->findItemOrFail('price_chat'); +``` - -### Metered Billing + +### Multiple Subscriptions -[Metered billing](https://stripe.com/docs/billing/subscriptions/metered-billing) allows you to charge customers based on their product usage during a billing cycle. For example, you may charge customers based on the number of text messages or emails they send per month. +Stripe allows your customers to have multiple subscriptions simultaneously. For example, you may run a gym that offers a swimming subscription and a weight-lifting subscription, and each subscription may have different pricing. Of course, customers should be able to subscribe to either or both plans. -To start using metered billing, you will first need to create a new product in your Stripe dashboard with a metered price. Then, use the `meteredPrice` to add the metered price ID to a customer subscription: +When your application creates subscriptions, you may provide the type of the subscription to the `newSubscription` method. The type may be any string that represents the type of subscription the user is initiating: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::post('/user/subscribe', function (Request $request) { - $request->user()->newSubscription('default') - ->meteredPrice('price_metered') - ->create($request->paymentMethodId); +Route::post('/swimming/subscribe', function (Request $request) { + $request->user()->newSubscription('swimming') + ->price('price_swimming_monthly') + ->create($request->paymentMethodId); - // ... - }); + // ... +}); +``` -You may also start a metered subscription via [Stripe Checkout](#checkout): +In this example, we initiated a monthly swimming subscription for the customer. However, they may want to swap to a yearly subscription at a later time. When adjusting the customer's subscription, we can simply swap the price on the `swimming` subscription: - $checkout = Auth::user() - ->newSubscription('default', []) - ->meteredPrice('price_metered') - ->checkout(); +```php +$user->subscription('swimming')->swap('price_swimming_yearly'); +``` - return view('your-checkout-view', [ - 'checkout' => $checkout, - ]); +Of course, you may also cancel the subscription entirely: - -#### Reporting Usage +```php +$user->subscription('swimming')->cancel(); +``` -As your customer uses your application, you will report their usage to Stripe so that they can be billed accurately. To increment the usage of a metered subscription, you may use the `reportUsage` method: + +### Usage Based Billing - $user = User::find(1); +[Usage based billing](https://stripe.com/docs/billing/subscriptions/metered-billing) allows you to charge customers based on their product usage during a billing cycle. For example, you may charge customers based on the number of text messages or emails they send per month. - $user->subscription('default')->reportUsage(); +To start using usage billing, you will first need to create a new product in your Stripe dashboard with a [usage based billing model](https://docs.stripe.com/billing/subscriptions/usage-based/implementation-guide) and a [meter](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage#configure-meter). After creating the meter, store the associated event name and meter ID, which you will need to report and retrieve usage. Then, use the `meteredPrice` method to add the metered price ID to a customer subscription: -By default, a "usage quantity" of 1 is added to the billing period. Alternatively, you may pass a specific amount of "usage" to add to the customer's usage for the billing period: +```php +use Illuminate\Http\Request; - $user = User::find(1); +Route::post('/user/subscribe', function (Request $request) { + $request->user()->newSubscription('default') + ->meteredPrice('price_metered') + ->create($request->paymentMethodId); - $user->subscription('default')->reportUsage(15); + // ... +}); +``` -If your application offers multiple prices on a single subscription, you will need to use the `reportUsageFor` method to specify the metered price you want to report usage for: +You may also start a metered subscription via [Stripe Checkout](#checkout): - $user = User::find(1); +```php +$checkout = Auth::user() + ->newSubscription('default', []) + ->meteredPrice('price_metered') + ->checkout(); - $user->subscription('default')->reportUsageFor('price_metered', 15); +return view('your-checkout-view', [ + 'checkout' => $checkout, +]); +``` -Sometimes, you may need to update usage which you have previously reported. To accomplish this, you may pass a timestamp or a `DateTimeInterface` instance as the second parameter to `reportUsage`. When doing so, Stripe will update the usage that was reported at that given time. You can continue to update previous usage records as the given date and time is still within the current billing period: + +#### Reporting Usage - $user = User::find(1); +As your customer uses your application, you will report their usage to Stripe so that they can be billed accurately. To report the usage of a metered event, you may use the `reportMeterEvent` method on your `Billable` model: - $user->subscription('default')->reportUsage(5, $timestamp); +```php +$user = User::find(1); - -#### Retrieving Usage Records +$user->reportMeterEvent('emails-sent'); +``` -To retrieve a customer's past usage, you may use a subscription instance's `usageRecords` method: +By default, a "usage quantity" of 1 is added to the billing period. Alternatively, you may pass a specific amount of "usage" to add to the customer's usage for the billing period: - $user = User::find(1); +```php +$user = User::find(1); - $usageRecords = $user->subscription('default')->usageRecords(); +$user->reportMeterEvent('emails-sent', quantity: 15); +``` -If your application offers multiple prices on a single subscription, you may use the `usageRecordsFor` method to specify the metered price that you wish to retrieve usage records for: +To retrieve a customer's event summary for a meter, you may use a `Billable` instance's `meterEventSummaries` method: - $user = User::find(1); +```php +$user = User::find(1); - $usageRecords = $user->subscription('default')->usageRecordsFor('price_metered'); +$meterUsage = $user->meterEventSummaries($meterId); -The `usageRecords` and `usageRecordsFor` methods return a Collection instance containing an associative array of usage records. You may iterate over this array to display a customer's total usage: +$meterUsage->first()->aggregated_value // 10 +``` - @foreach ($usageRecords as $usageRecord) - - Period Starting: {{ $usageRecord['period']['start'] }} - - Period Ending: {{ $usageRecord['period']['end'] }} - - Total Usage: {{ $usageRecord['total_usage'] }} - @endforeach +Please refer to Stripe's [Meter Event Summary object documentation](https://docs.stripe.com/api/billing/meter-event_summary/object) for more information on meter event summaries. -For a full reference of all usage data returned and how to use Stripe's cursor based pagination, please consult [the official Stripe API documentation](https://stripe.com/docs/api/usage_records/subscription_item_summary_list). +To [list all meters](https://docs.stripe.com/api/billing/meter/list), you may use a `Billable` instance's `meters` method: + +```php +$user = User::find(1); + +$user->meters(); +``` ### Subscription Taxes -> {note} Instead of calculating Tax Rates manually, you can [automatically calculate taxes using Stripe Tax](#tax-configuration) +> [!WARNING] +> Instead of calculating Tax Rates manually, you can [automatically calculate taxes using Stripe Tax](#tax-configuration) To specify the tax rates a user pays on a subscription, you should implement the `taxRates` method on your billable model and return an array containing the Stripe tax rate IDs. You can define these tax rates in [your Stripe dashboard](https://dashboard.stripe.com/test/tax-rates): - /** - * The tax rates that should apply to the customer's subscriptions. - * - * @return array - */ - public function taxRates() - { - return ['txr_id']; - } +```php +/** + * The tax rates that should apply to the customer's subscriptions. + * + * @return array + */ +public function taxRates(): array +{ + return ['txr_id']; +} +``` The `taxRates` method enables you to apply a tax rate on a customer-by-customer basis, which may be helpful for a user base that spans multiple countries and tax rates. -If you're offering multiprice subscriptions, you may define different tax rates for each price by implementing a `priceTaxRates` method on your billable model: - - /** - * The tax rates that should apply to the customer's subscriptions. - * - * @return array - */ - public function priceTaxRates() - { - return [ - 'price_monthly' => ['txr_id'], - ]; - } +If you're offering subscriptions with multiple products, you may define different tax rates for each price by implementing a `priceTaxRates` method on your billable model: + +```php +/** + * The tax rates that should apply to the customer's subscriptions. + * + * @return array> + */ +public function priceTaxRates(): array +{ + return [ + 'price_monthly' => ['txr_id'], + ]; +} +``` -> {note} The `taxRates` method only applies to subscription charges. If you use Cashier to make "one off" charges, you will need to manually specify the tax rate at that time. +> [!WARNING] +> The `taxRates` method only applies to subscription charges. If you use Cashier to make "one-off" charges, you will need to manually specify the tax rate at that time. #### Syncing Tax Rates When changing the hard-coded tax rate IDs returned by the `taxRates` method, the tax settings on any existing subscriptions for the user will remain the same. If you wish to update the tax value for existing subscriptions with the new `taxRates` values, you should call the `syncTaxRates` method on the user's subscription instance: - $user->subscription('default')->syncTaxRates(); +```php +$user->subscription('default')->syncTaxRates(); +``` -This will also sync any multiprice subscription item tax rates. If your application is offering multiprice subscriptions, you should ensure that your billable model implements the `priceTaxRates` method [discussed above](#subscription-taxes). +This will also sync any item tax rates for a subscription with multiple products. If your application is offering subscriptions with multiple products, you should ensure that your billable model implements the `priceTaxRates` method [discussed above](#subscription-taxes). #### Tax Exemption Cashier also offers the `isNotTaxExempt`, `isTaxExempt`, and `reverseChargeApplies` methods to determine if the customer is tax exempt. These methods will call the Stripe API to determine a customer's tax exemption status: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $user->isTaxExempt(); - $user->isNotTaxExempt(); - $user->reverseChargeApplies(); +$user->isTaxExempt(); +$user->isNotTaxExempt(); +$user->reverseChargeApplies(); +``` -> {note} These methods are also available on any `Laravel\Cashier\Invoice` object. However, when invoked on an `Invoice` object, the methods will determine the exemption status at the time the invoice was created. +> [!WARNING] +> These methods are also available on any `Laravel\Cashier\Invoice` object. However, when invoked on an `Invoice` object, the methods will determine the exemption status at the time the invoice was created. ### Subscription Anchor Date By default, the billing cycle anchor is the date the subscription was created or, if a trial period is used, the date that the trial ends. If you would like to modify the billing anchor date, you may use the `anchorBillingCycleOn` method: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::post('/user/subscribe', function (Request $request) { - $anchor = Carbon::parse('first day of next month'); +Route::post('/user/subscribe', function (Request $request) { + $anchor = Carbon::parse('first day of next month'); - $request->user()->newSubscription('default', 'price_monthly') - ->anchorBillingCycleOn($anchor->startOfDay()) - ->create($request->paymentMethodId); + $request->user()->newSubscription('default', 'price_monthly') + ->anchorBillingCycleOn($anchor->startOfDay()) + ->create($request->paymentMethodId); - // ... - }); + // ... +}); +``` For more information on managing subscription billing cycles, consult the [Stripe billing cycle documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle) @@ -1200,7 +1672,9 @@ For more information on managing subscription billing cycles, consult the [Strip To cancel a subscription, call the `cancel` method on the user's subscription: - $user->subscription('default')->cancel(); +```php +$user->subscription('default')->cancel(); +``` When a subscription is canceled, Cashier will automatically set the `ends_at` column in your `subscriptions` database table. This column is used to know when the `subscribed` method should begin returning `false`. @@ -1208,30 +1682,48 @@ For example, if a customer cancels a subscription on March 1st, but the subscrip You may determine if a user has canceled their subscription but are still on their "grace period" using the `onGracePeriod` method: - if ($user->subscription('default')->onGracePeriod()) { - // - } +```php +if ($user->subscription('default')->onGracePeriod()) { + // ... +} +``` If you wish to cancel a subscription immediately, call the `cancelNow` method on the user's subscription: - $user->subscription('default')->cancelNow(); +```php +$user->subscription('default')->cancelNow(); +``` If you wish to cancel a subscription immediately and invoice any remaining un-invoiced metered usage or new / pending proration invoice items, call the `cancelNowAndInvoice` method on the user's subscription: - $user->subscription('default')->cancelNowAndInvoice(); +```php +$user->subscription('default')->cancelNowAndInvoice(); +``` You may also choose to cancel the subscription at a specific moment in time: - $user->subscription('default')->cancelAt( - now()->addDays(10) - ); +```php +$user->subscription('default')->cancelAt( + now()->addDays(10) +); +``` + +Finally, you should always cancel user subscriptions before deleting the associated user model: + +```php +$user->subscription('default')->cancelNow(); + +$user->delete(); +``` ### Resuming Subscriptions If a customer has canceled their subscription and you wish to resume it, you may invoke the `resume` method on the subscription. The customer must still be within their "grace period" in order to resume a subscription: - $user->subscription('default')->resume(); +```php +$user->subscription('default')->resume(); +``` If the customer cancels a subscription and then resumes that subscription before the subscription has fully expired the customer will not be billed immediately. Instead, their subscription will be re-activated and they will be billed on the original billing cycle. @@ -1243,44 +1735,65 @@ If the customer cancels a subscription and then resumes that subscription before If you would like to offer trial periods to your customers while still collecting payment method information up front, you should use the `trialDays` method when creating your subscriptions: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::post('/user/subscribe', function (Request $request) { - $request->user()->newSubscription('default', 'price_monthly') - ->trialDays(10) - ->create($request->paymentMethodId); +Route::post('/user/subscribe', function (Request $request) { + $request->user()->newSubscription('default', 'price_monthly') + ->trialDays(10) + ->create($request->paymentMethodId); - // ... - }); + // ... +}); +``` This method will set the trial period ending date on the subscription record within the database and instruct Stripe to not begin billing the customer until after this date. When using the `trialDays` method, Cashier will overwrite any default trial period configured for the price in Stripe. -> {note} If the customer's subscription is not canceled before the trial ending date they will be charged as soon as the trial expires, so you should be sure to notify your users of their trial ending date. +> [!WARNING] +> If the customer's subscription is not canceled before the trial ending date they will be charged as soon as the trial expires, so you should be sure to notify your users of their trial ending date. The `trialUntil` method allows you to provide a `DateTime` instance that specifies when the trial period should end: - use Carbon\Carbon; +```php +use Illuminate\Support\Carbon; - $user->newSubscription('default', 'price_monthly') - ->trialUntil(Carbon::now()->addDays(10)) - ->create($paymentMethod); +$user->newSubscription('default', 'price_monthly') + ->trialUntil(Carbon::now()->addDays(10)) + ->create($paymentMethod); +``` You may determine if a user is within their trial period using either the `onTrial` method of the user instance or the `onTrial` method of the subscription instance. The two examples below are equivalent: - if ($user->onTrial('default')) { - // - } +```php +if ($user->onTrial('default')) { + // ... +} - if ($user->subscription('default')->onTrial()) { - // - } +if ($user->subscription('default')->onTrial()) { + // ... +} +``` You may use the `endTrial` method to immediately end a subscription trial: - $user->subscription('default')->endTrial(); +```php +$user->subscription('default')->endTrial(); +``` + +To determine if an existing trial has expired, you may use the `hasExpiredTrial` methods: + +```php +if ($user->hasExpiredTrial('default')) { + // ... +} + +if ($user->subscription('default')->hasExpiredTrial()) { + // ... +} +``` -#### Defining Trial Days In Stripe / Cashier +#### Defining Trial Days in Stripe / Cashier You may choose to define how many trial days your price's receive in the Stripe dashboard or always pass them explicitly using Cashier. If you choose to define your price's trial days in Stripe you should be aware that new subscriptions, including new subscriptions for a customer that had a subscription in the past, will always receive a trial period unless you explicitly call the `skipTrial()` method. @@ -1289,62 +1802,76 @@ You may choose to define how many trial days your price's receive in the Stripe If you would like to offer trial periods without collecting the user's payment method information up front, you may set the `trial_ends_at` column on the user record to your desired trial ending date. This is typically done during user registration: - use App\Models\User; +```php +use App\Models\User; - $user = User::create([ - // ... - 'trial_ends_at' => now()->addDays(10), - ]); +$user = User::create([ + // ... + 'trial_ends_at' => now()->addDays(10), +]); +``` -> {note} Be sure to add a [date cast](/docs/{{version}}/eloquent-mutators##date-casting) for the `trial_ends_at` attribute within your billable model's class definition. +> [!WARNING] +> Be sure to add a [date cast](/docs/{{version}}/eloquent-mutators#date-casting) for the `trial_ends_at` attribute within your billable model's class definition. Cashier refers to this type of trial as a "generic trial", since it is not attached to any existing subscription. The `onTrial` method on the billable model instance will return `true` if the current date is not past the value of `trial_ends_at`: - if ($user->onTrial()) { - // User is within their trial period... - } +```php +if ($user->onTrial()) { + // User is within their trial period... +} +``` Once you are ready to create an actual subscription for the user, you may use the `newSubscription` method as usual: - $user = User::find(1); +```php +$user = User::find(1); - $user->newSubscription('default', 'price_monthly')->create($paymentMethod); +$user->newSubscription('default', 'price_monthly')->create($paymentMethod); +``` -To retrieve the user's trial ending date, you may use the `trialEndsAt` method. This method will return a Carbon date instance if a user is on a trial or `null` if they aren't. You may also pass an optional subscription name parameter if you would like to get the trial ending date for a specific subscription other than the default one: +To retrieve the user's trial ending date, you may use the `trialEndsAt` method. This method will return a Carbon date instance if a user is on a trial or `null` if they aren't. You may also pass an optional subscription type parameter if you would like to get the trial ending date for a specific subscription other than the default one: - if ($user->onTrial()) { - $trialEndsAt = $user->trialEndsAt('main'); - } +```php +if ($user->onTrial()) { + $trialEndsAt = $user->trialEndsAt('main'); +} +``` You may also use the `onGenericTrial` method if you wish to know specifically that the user is within their "generic" trial period and has not yet created an actual subscription: - if ($user->onGenericTrial()) { - // User is within their "generic" trial period... - } +```php +if ($user->onGenericTrial()) { + // User is within their "generic" trial period... +} +``` ### Extending Trials The `extendTrial` method allows you to extend the trial period of a subscription after the subscription has been created. If the trial has already expired and the customer is already being billed for the subscription, you can still offer them an extended trial. The time spent within the trial period will be deducted from the customer's next invoice: - use App\Models\User; +```php +use App\Models\User; - $subscription = User::find(1)->subscription('default'); +$subscription = User::find(1)->subscription('default'); - // End the trial 7 days from now... - $subscription->extendTrial( - now()->addDays(7) - ); +// End the trial 7 days from now... +$subscription->extendTrial( + now()->addDays(7) +); - // Add an additional 5 days to the trial... - $subscription->extendTrial( - $subscription->trial_ends_at->addDays(5) - ); +// Add an additional 5 days to the trial... +$subscription->extendTrial( + $subscription->trial_ends_at->addDays(5) +); +``` ## Handling Stripe Webhooks -> {tip} You may use [the Stripe CLI](https://stripe.com/docs/stripe-cli) to help test webhooks during local development. +> [!NOTE] +> You may use [the Stripe CLI](https://stripe.com/docs/stripe-cli) to help test webhooks during local development. Stripe can notify your application of a variety of events via webhooks. By default, a route that points to Cashier's webhook controller is automatically registered by the Cashier service provider. This controller will handle all incoming webhook requests. @@ -1357,7 +1884,9 @@ To ensure your application can handle Stripe webhooks, be sure to configure the - `customer.subscription.deleted` - `customer.updated` - `customer.deleted` +- `payment_method.automatically_updated` - `invoice.payment_action_required` +- `invoice.payment_succeeded` For convenience, Cashier includes a `cashier:webhook` Artisan command. This command will create a webhook in Stripe that listens to all of the events required by Cashier: @@ -1383,16 +1912,21 @@ After creation, the webhook will be immediately active. If you wish to create th php artisan cashier:webhook --disabled ``` -> {note} Make sure you protect incoming Stripe webhook requests with Cashier's included [webhook signature verification](#verifying-webhook-signatures) middleware. +> [!WARNING] +> Make sure you protect incoming Stripe webhook requests with Cashier's included [webhook signature verification](#verifying-webhook-signatures) middleware. -#### Webhooks & CSRF Protection +#### Webhooks and CSRF Protection -Since Stripe webhooks need to bypass Laravel's [CSRF protection](/docs/{{version}}/csrf), be sure to list the URI as an exception in your application's `App\Http\Middleware\VerifyCsrfToken` middleware or list the route outside of the `web` middleware group: +Since Stripe webhooks need to bypass Laravel's [CSRF protection](/docs/{{version}}/csrf), you should ensure that Laravel does not attempt to validate the CSRF token for incoming Stripe webhooks. To accomplish this, you should exclude `stripe/*` from CSRF protection in your application's `bootstrap/app.php` file: - protected $except = [ +```php +->withMiddleware(function (Middleware $middleware): void { + $middleware->validateCsrfTokens(except: [ 'stripe/*', - ]; + ]); +}) +``` ### Defining Webhook Event Handlers @@ -1404,46 +1938,26 @@ Cashier automatically handles subscription cancellations for failed charges and Both events contain the full payload of the Stripe webhook. For example, if you wish to handle the `invoice.payment_succeeded` webhook, you may register a [listener](/docs/{{version}}/events#defining-listeners) that will handle the event: - payload['type'] === 'invoice.payment_succeeded') { - // Handle the incoming event... - } + if ($event->payload['type'] === 'invoice.payment_succeeded') { + // Handle the incoming event... } } - -Once your listener has been defined, you may register it within your application's `EventServiceProvider`: - - [ - StripeEventListener::class, - ], - ]; - } +} +``` ### Verifying Webhook Signatures @@ -1458,73 +1972,135 @@ To enable webhook verification, ensure that the `STRIPE_WEBHOOK_SECRET` environm ### Simple Charge -> {note} The `charge` method accepts the amount you would like to charge in the lowest denominator of the currency used by your application. For example, when using United States Dollars, amounts should be specified in pennies. - If you would like to make a one-time charge against a customer, you may use the `charge` method on a billable model instance. You will need to [provide a payment method identifier](#payment-methods-for-single-charges) as the second argument to the `charge` method: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::post('/purchase', function (Request $request) { - $stripeCharge = $request->user()->charge( - 100, $request->paymentMethodId - ); +Route::post('/purchase', function (Request $request) { + $stripeCharge = $request->user()->charge( + 100, $request->paymentMethodId + ); - // ... - }); + // ... +}); +``` The `charge` method accepts an array as its third argument, allowing you to pass any options you wish to the underlying Stripe charge creation. More information regarding the options available to you when creating charges may be found in the [Stripe documentation](https://stripe.com/docs/api/charges/create): - $user->charge(100, $paymentMethod, [ - 'custom_option' => $value, - ]); +```php +$user->charge(100, $paymentMethod, [ + 'custom_option' => $value, +]); +``` You may also use the `charge` method without an underlying customer or user. To accomplish this, invoke the `charge` method on a new instance of your application's billable model: - use App\Models\User; +```php +use App\Models\User; - $stripeCharge = (new User)->charge(100, $paymentMethod); +$stripeCharge = (new User)->charge(100, $paymentMethod); +``` The `charge` method will throw an exception if the charge fails. If the charge is successful, an instance of `Laravel\Cashier\Payment` will be returned from the method: - try { - $payment = $user->charge(100, $paymentMethod); - } catch (Exception $e) { - // - } +```php +try { + $payment = $user->charge(100, $paymentMethod); +} catch (Exception $e) { + // ... +} +``` + +> [!WARNING] +> The `charge` method accepts the payment amount in the lowest denominator of the currency used by your application. For example, if customers are paying in United States Dollars, amounts should be specified in pennies. ### Charge With Invoice -Sometimes you may need to make a one-time charge and offer a PDF receipt to your customer. The `invoicePrice` method lets you do just that. For example, let's invoice a customer for five new shirts: +Sometimes you may need to make a one-time charge and offer a PDF invoice to your customer. The `invoicePrice` method lets you do just that. For example, let's invoice a customer for five new shirts: - $user->invoicePrice('price_tshirt', 5); +```php +$user->invoicePrice('price_tshirt', 5); +``` The invoice will be immediately charged against the user's default payment method. The `invoicePrice` method also accepts an array as its third argument. This array contains the billing options for the invoice item. The fourth argument accepted by the method is also an array which should contain the billing options for the invoice itself: - $user->invoicePrice('price_tshirt', 5, [ - 'discounts' => [ - ['coupon' => 'SUMMER21SALE'] - ], - ], [ - 'default_tax_rates' => ['txr_id'], - ]); +```php +$user->invoicePrice('price_tshirt', 5, [ + 'discounts' => [ + ['coupon' => 'SUMMER21SALE'] + ], +], [ + 'default_tax_rates' => ['txr_id'], +]); +``` + +Similarly to `invoicePrice`, you may use the `tabPrice` method to create a one-time charge for multiple items (up to 250 items per invoice) by adding them to the customer's "tab" and then invoicing the customer. For example, we may invoice a customer for five shirts and two mugs: + +```php +$user->tabPrice('price_tshirt', 5); +$user->tabPrice('price_mug', 2); +$user->invoice(); +``` Alternatively, you may use the `invoiceFor` method to make a "one-off" charge against the customer's default payment method: - $user->invoiceFor('One Time Fee', 500); +```php +$user->invoiceFor('One Time Fee', 500); +``` + +Although the `invoiceFor` method is available for you to use, it is recommended that you use the `invoicePrice` and `tabPrice` methods with pre-defined prices. By doing so, you will have access to better analytics and data within your Stripe dashboard regarding your sales on a per-product basis. + +> [!WARNING] +> The `invoice`, `invoicePrice`, and `invoiceFor` methods will create a Stripe invoice which will retry failed billing attempts. If you do not want invoices to retry failed charges, you will need to close them using the Stripe API after the first failed charge. -Although the `invoiceFor` method is available for you to use, it is recommendeded that you use the `invoicePrice` method with pre-defined prices. By doing so, you will have access to better analytics and data within your Stripe dashboard regarding your sales on a per-product basis. + +### Creating Payment Intents -> {note} The `invoicePrice` and `invoiceFor` methods will create a Stripe invoice which will retry failed billing attempts. If you do not want invoices to retry failed charges, you will need to close them using the Stripe API after the first failed charge. +You can create a new Stripe payment intent by invoking the `pay` method on a billable model instance. Calling this method will create a payment intent that is wrapped in a `Laravel\Cashier\Payment` instance: + +```php +use Illuminate\Http\Request; + +Route::post('/pay', function (Request $request) { + $payment = $request->user()->pay( + $request->get('amount') + ); + + return $payment->client_secret; +}); +``` + +After creating the payment intent, you can return the client secret to your application's frontend so that the user can complete the payment in their browser. To read more about building entire payment flows using Stripe payment intents, please consult the [Stripe documentation](https://stripe.com/docs/payments/accept-a-payment?platform=web). + +When using the `pay` method, the default payment methods that are enabled within your Stripe dashboard will be available to the customer. Alternatively, if you only want to allow for some specific payment methods to be used, you may use the `payWith` method: + +```php +use Illuminate\Http\Request; + +Route::post('/pay', function (Request $request) { + $payment = $request->user()->payWith( + $request->get('amount'), ['card', 'bancontact'] + ); + + return $payment->client_secret; +}); +``` + +> [!WARNING] +> The `pay` and `payWith` methods accept the payment amount in the lowest denominator of the currency used by your application. For example, if customers are paying in United States Dollars, amounts should be specified in pennies. ### Refunding Charges If you need to refund a Stripe charge, you may use the `refund` method. This method accepts the Stripe [payment intent ID](#payment-methods-for-single-charges) as its first argument: - $payment = $user->charge(100, $paymentMethodId); +```php +$payment = $user->charge(100, $paymentMethodId); - $user->refund($payment->id); +$user->refund($payment->id); +``` ## Invoices @@ -1534,110 +2110,132 @@ If you need to refund a Stripe charge, you may use the `refund` method. This met You may easily retrieve an array of a billable model's invoices using the `invoices` method. The `invoices` method returns a collection of `Laravel\Cashier\Invoice` instances: - $invoices = $user->invoices(); +```php +$invoices = $user->invoices(); +``` If you would like to include pending invoices in the results, you may use the `invoicesIncludingPending` method: - $invoices = $user->invoicesIncludingPending(); +```php +$invoices = $user->invoicesIncludingPending(); +``` You may use the `findInvoice` method to retrieve a specific invoice by its ID: - $invoice = $user->findInvoice($invoiceId); +```php +$invoice = $user->findInvoice($invoiceId); +``` #### Displaying Invoice Information When listing the invoices for the customer, you may use the invoice's methods to display the relevant invoice information. For example, you may wish to list every invoice in a table, allowing the user to easily download any of them: - - @foreach ($invoices as $invoice) - - - - - - @endforeach -
{{ $invoice->date()->toFormattedDateString() }}{{ $invoice->total() }}Download
+```blade + + @foreach ($invoices as $invoice) + + + + + + @endforeach +
{{ $invoice->date()->toFormattedDateString() }}{{ $invoice->total() }}Download
+``` ### Upcoming Invoices To retrieve the upcoming invoice for a customer, you may use the `upcomingInvoice` method: - $invoice = $user->upcomingInvoice(); +```php +$invoice = $user->upcomingInvoice(); +``` -Similary, if the customer has multiple subscriptions, you can also retrieve the upcoming invoice for a specific subscription: +Similarly, if the customer has multiple subscriptions, you can also retrieve the upcoming invoice for a specific subscription: - $invoice = $user->subscription('default')->upcomingInvoice(); +```php +$invoice = $user->subscription('default')->upcomingInvoice(); +``` -### Previewing Subscription Invoice +### Previewing Subscription Invoices Using the `previewInvoice` method, you can preview an invoice before making price changes. This will allow you to determine what your customer's invoice will look like when a given price change is made: - $invoice = $user->subscription('default')->previewInvoice('price_yearly'); +```php +$invoice = $user->subscription('default')->previewInvoice('price_yearly'); +``` You may pass an array of prices to the `previewInvoice` method in order to preview invoices with multiple new prices: - $invoice = $user->subscription('default')->previewInvoice(['price_yearly', 'price_metered']); +```php +$invoice = $user->subscription('default')->previewInvoice(['price_yearly', 'price_metered']); +``` ### Generating Invoice PDFs -From within a route or controller, you may use the `downloadInvoice` method to generate a PDF download of a given invoice. This method will automatically generate the proper HTTP response needed to download the invoice: +Before generating invoice PDFs, you should use Composer to install the Dompdf library, which is the default invoice renderer for Cashier: - use Illuminate\Http\Request; +```shell +composer require dompdf/dompdf +``` - Route::get('/user/invoice/{invoice}', function (Request $request, $invoiceId) { - return $request->user()->downloadInvoice($invoiceId, [ - 'vendor' => 'Your Company', - 'product' => 'Your Product', - ]); - }); +From within a route or controller, you may use the `downloadInvoice` method to generate a PDF download of a given invoice. This method will automatically generate the proper HTTP response needed to download the invoice: + +```php +use Illuminate\Http\Request; -By default, all data on the invoice is derived from the customer and invoice data stored in Stripe. However, you can customize some of this data by providing an array as the second argument to the `downloadInvoice` method. This array allows you to customize information such as your company and product details: +Route::get('/user/invoice/{invoice}', function (Request $request, string $invoiceId) { + return $request->user()->downloadInvoice($invoiceId); +}); +``` - return $request->user()->downloadInvoice($invoiceId, [ - 'vendor' => 'Your Company', - 'product' => 'Your Product', - 'street' => 'Main Str. 1', - 'location' => '2000 Antwerp, Belgium', - 'phone' => '+32 499 00 00 00', - 'email' => 'info@example.com', - 'url' => 'https://example.com/', - 'vendorVat' => 'BE123456789', - ], 'my-invoice'); +By default, all data on the invoice is derived from the customer and invoice data stored in Stripe. The filename is based on your `app.name` config value. However, you can customize some of this data by providing an array as the second argument to the `downloadInvoice` method. This array allows you to customize information such as your company and product details: + +```php +return $request->user()->downloadInvoice($invoiceId, [ + 'vendor' => 'Your Company', + 'product' => 'Your Product', + 'street' => 'Main Str. 1', + 'location' => '2000 Antwerp, Belgium', + 'phone' => '+32 499 00 00 00', + 'email' => 'info@example.com', + 'url' => 'https://example.com/', + 'vendorVat' => 'BE123456789', +]); +``` The `downloadInvoice` method also allows for a custom filename via its third argument. This filename will automatically be suffixed with `.pdf`: - return $request->user()->downloadInvoice($invoiceId, [], 'my-invoice'); +```php +return $request->user()->downloadInvoice($invoiceId, [], 'my-invoice'); +``` #### Custom Invoice Renderer Cashier also makes it possible to use a custom invoice renderer. By default, Cashier uses the `DompdfInvoiceRenderer` implementation, which utilizes the [dompdf](https://github.com/dompdf/dompdf) PHP library to generate Cashier's invoices. However, you may use any renderer you wish by implementing the `Laravel\Cashier\Contracts\InvoiceRenderer` interface. For example, you may wish to render an invoice PDF using an API call to a third-party PDF rendering service: - use Illuminate\Support\Facades\Http; - use Laravel\Cashier\Contracts\InvoiceRenderer; - use Laravel\Cashier\Invoice; +```php +use Illuminate\Support\Facades\Http; +use Laravel\Cashier\Contracts\InvoiceRenderer; +use Laravel\Cashier\Invoice; - class ApiInvoiceRenderer implements InvoiceRenderer +class ApiInvoiceRenderer implements InvoiceRenderer +{ + /** + * Render the given invoice and return the raw PDF bytes. + */ + public function render(Invoice $invoice, array $data = [], array $options = []): string { - /** - * Render the given invoice and return the raw PDF bytes. - * - * @param \Laravel\Cashier\Invoice. $invoice - * @param array $data - * @param array $options - * @return string - */ - public function render(Invoice $invoice, array $data = [], array $options = []): string - { - $html = $invoice->view($data)->render(); - - return Http::get('https://example.com/html-to-pdf', ['html' => $html])->get()->body(); - } + $html = $invoice->view($data)->render(); + + return Http::get('https://example.com/html-to-pdf', ['html' => $html])->get()->body(); } +} +``` Once you have implemented the invoice renderer contract, you should update the `cashier.invoices.renderer` configuration value in your application's `config/cashier.php` configuration file. This configuration value should be set to the class name of your custom renderer implementation. @@ -1653,130 +2251,153 @@ The following documentation contains information on how to get started using Str You may perform a checkout for an existing product that has been created within your Stripe dashboard using the `checkout` method on a billable model. The `checkout` method will initiate a new Stripe Checkout session. By default, you're required to pass a Stripe Price ID: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/product-checkout', function (Request $request) { - return $request->user()->checkout('price_tshirt'); - }); +Route::get('/product-checkout', function (Request $request) { + return $request->user()->checkout('price_tshirt'); +}); +``` If needed, you may also specify a product quantity: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/product-checkout', function (Request $request) { - return $request->user()->checkout(['price_tshirt' => 15]); - }); +Route::get('/product-checkout', function (Request $request) { + return $request->user()->checkout(['price_tshirt' => 15]); +}); +``` When a customer visits this route they will be redirected to Stripe's Checkout page. By default, when a user successfully completes or cancels a purchase they will be redirected to your `home` route location, but you may specify custom callback URLs using the `success_url` and `cancel_url` options: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/product-checkout', function (Request $request) { - return $request->user()->checkout(['price_tshirt' => 1], [ - 'success_url' => route('your-success-route'), - 'cancel_url' => route('your-cancel-route'), - ]); - }); +Route::get('/product-checkout', function (Request $request) { + return $request->user()->checkout(['price_tshirt' => 1], [ + 'success_url' => route('your-success-route'), + 'cancel_url' => route('your-cancel-route'), + ]); +}); +``` When defining your `success_url` checkout option, you may instruct Stripe to add the checkout session ID as a query string parameter when invoking your URL. To do so, add the literal string `{CHECKOUT_SESSION_ID}` to your `success_url` query string. Stripe will replace this placeholder with the actual checkout session ID: - use Illuminate\Http\Request; - use Stripe\Checkout\Session; - use Stripe\Customer; +```php +use Illuminate\Http\Request; +use Stripe\Checkout\Session; +use Stripe\Customer; - Route::get('/product-checkout', function (Request $request) { - return $request->user()->checkout(['price_tshirt' => 1], [ - 'success_url' => route('checkout-success') . '?session_id={CHECKOUT_SESSION_ID}', - 'cancel_url' => route('checkout-cancel'), - ]); - }); +Route::get('/product-checkout', function (Request $request) { + return $request->user()->checkout(['price_tshirt' => 1], [ + 'success_url' => route('checkout-success').'?session_id={CHECKOUT_SESSION_ID}', + 'cancel_url' => route('checkout-cancel'), + ]); +}); - Route::get('/checkout-success', function (Request $request) { - $checkoutSession = $request->user()->stripe()->checkout->sessions->retrieve($request->get('session_id')); +Route::get('/checkout-success', function (Request $request) { + $checkoutSession = $request->user()->stripe()->checkout->sessions->retrieve($request->get('session_id')); - return view('checkout.success', ['checkoutSession' => $checkoutSession]); - })->name('checkout-success'); + return view('checkout.success', ['checkoutSession' => $checkoutSession]); +})->name('checkout-success'); +``` #### Promotion Codes By default, Stripe Checkout does not allow [user redeemable promotion codes](https://stripe.com/docs/billing/subscriptions/discounts/codes). Luckily, there's an easy way to enable these for your Checkout page. To do so, you may invoke the `allowPromotionCodes` method: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/product-checkout', function (Request $request) { - return $request->user() - ->allowPromotionCodes() - ->checkout('price_tshirt'); - }); +Route::get('/product-checkout', function (Request $request) { + return $request->user() + ->allowPromotionCodes() + ->checkout('price_tshirt'); +}); +``` ### Single Charge Checkouts You can also perform a simple charge for an ad-hoc product that has not been created in your Stripe dashboard. To do so you may use the `checkoutCharge` method on a billable model and pass it a chargeable amount, a product name, and an optional quantity. When a customer visits this route they will be redirected to Stripe's Checkout page: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/charge-checkout', function (Request $request) { - return $request->user()->checkoutCharge(1200, 'T-Shirt', 5); - }); +Route::get('/charge-checkout', function (Request $request) { + return $request->user()->checkoutCharge(1200, 'T-Shirt', 5); +}); +``` -> {note} When using the `checkoutCharge` method, Stripe will always create a new product and price in your Stripe dashboard. Therefore, we recommend that you create the products up front in your Stripe dashboard and use the `checkout` method instead. +> [!WARNING] +> When using the `checkoutCharge` method, Stripe will always create a new product and price in your Stripe dashboard. Therefore, we recommend that you create the products up front in your Stripe dashboard and use the `checkout` method instead. ### Subscription Checkouts -> {note} Using Stripe Checkout for subscriptions requires you to enable the `customer.subscription.created` webhook in your Stripe dashboard. This webhook will create the subscription record in your database and store all of the relevant subscription items. +> [!WARNING] +> Using Stripe Checkout for subscriptions requires you to enable the `customer.subscription.created` webhook in your Stripe dashboard. This webhook will create the subscription record in your database and store all of the relevant subscription items. You may also use Stripe Checkout to initiate subscriptions. After defining your subscription with Cashier's subscription builder methods, you may call the `checkout `method. When a customer visits this route they will be redirected to Stripe's Checkout page: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/subscription-checkout', function (Request $request) { - return $request->user() - ->newSubscription('default', 'price_monthly') - ->checkout(); - }); +Route::get('/subscription-checkout', function (Request $request) { + return $request->user() + ->newSubscription('default', 'price_monthly') + ->checkout(); +}); +``` Just as with product checkouts, you may customize the success and cancellation URLs: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/subscription-checkout', function (Request $request) { - return $request->user() - ->newSubscription('default', 'price_monthly') - ->checkout([ - 'success_url' => route('your-success-route'), - 'cancel_url' => route('your-cancel-route'), - ]); - }); +Route::get('/subscription-checkout', function (Request $request) { + return $request->user() + ->newSubscription('default', 'price_monthly') + ->checkout([ + 'success_url' => route('your-success-route'), + 'cancel_url' => route('your-cancel-route'), + ]); +}); +``` Of course, you can also enable promotion codes for subscription checkouts: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/subscription-checkout', function (Request $request) { - return $request->user() - ->newSubscription('default', 'price_monthly') - ->allowPromotionCodes() - ->checkout(); - }); +Route::get('/subscription-checkout', function (Request $request) { + return $request->user() + ->newSubscription('default', 'price_monthly') + ->allowPromotionCodes() + ->checkout(); +}); +``` -> {note} Unfortunately Stripe Checkout does not support all subscription billing options when starting subscriptions. Using the `anchorBillingCycleOn` method on the subscription builder, setting proration behavior, or setting payment behavior will not have any effect during Stripe Checkout sessions. Please consult [the Stripe Checkout Session API documentation](https://stripe.com/docs/api/checkout/sessions/create) to review which parameters are available. +> [!WARNING] +> Unfortunately Stripe Checkout does not support all subscription billing options when starting subscriptions. Using the `anchorBillingCycleOn` method on the subscription builder, setting proration behavior, or setting payment behavior will not have any effect during Stripe Checkout sessions. Please consult [the Stripe Checkout Session API documentation](https://stripe.com/docs/api/checkout/sessions/create) to review which parameters are available. -#### Stripe Checkout & Trial Periods +#### Stripe Checkout and Trial Periods Of course, you can define a trial period when building a subscription that will be completed using Stripe Checkout: - $checkout = Auth::user()->newSubscription('default', 'price_monthly') - ->trialDays(3) - ->checkout(); +```php +$checkout = Auth::user()->newSubscription('default', 'price_monthly') + ->trialDays(3) + ->checkout(); +``` However, the trial period must be at least 48 hours, which is the minimum amount of trial time supported by Stripe Checkout. -#### Subscriptions & Webhooks +#### Subscriptions and Webhooks Remember, Stripe and Cashier update subscription statuses via webhooks, so there's a possibility a subscription might not yet be active when the customer returns to the application after entering their payment information. To handle this scenario, you may wish to display a message informing the user that their payment or subscription is pending. @@ -1785,11 +2406,49 @@ Remember, Stripe and Cashier update subscription statuses via webhooks, so there Checkout also supports collecting a customer's Tax ID. To enable this on a checkout session, invoke the `collectTaxIds` method when creating the session: - $checkout = $user->collectTaxIds()->checkout('price_tshirt'); +```php +$checkout = $user->collectTaxIds()->checkout('price_tshirt'); +``` When this method is invoked, a new checkbox will be available to the customer that allows them to indicate if they're purchasing as a company. If so, they will have the opportunity to provide their Tax ID number. -> {note} If you have already configured [automatic tax collection](#tax-configuration) in your application's service provider then this feature will be enabled automatically and there is no need to invoke the `collectTaxIds` method. +> [!WARNING] +> If you have already configured [automatic tax collection](#tax-configuration) in your application's service provider then this feature will be enabled automatically and there is no need to invoke the `collectTaxIds` method. + + +### Guest Checkouts + +Using the `Checkout::guest` method, you may initiate checkout sessions for guests of your application that do not have an "account": + +```php +use Illuminate\Http\Request; +use Laravel\Cashier\Checkout; + +Route::get('/product-checkout', function (Request $request) { + return Checkout::guest()->create('price_tshirt', [ + 'success_url' => route('your-success-route'), + 'cancel_url' => route('your-cancel-route'), + ]); +}); +``` + +Similarly to when creating checkout sessions for existing users, you may utilize additional methods available on the `Laravel\Cashier\CheckoutBuilder` instance to customize the guest checkout session: + +```php +use Illuminate\Http\Request; +use Laravel\Cashier\Checkout; + +Route::get('/product-checkout', function (Request $request) { + return Checkout::guest() + ->withPromotionCode('promo-code') + ->create('price_tshirt', [ + 'success_url' => route('your-success-route'), + 'cancel_url' => route('your-cancel-route'), + ]); +}); +``` + +After a guest checkout has been completed, Stripe can dispatch a `checkout.session.completed` webhook event, so make sure to [configure your Stripe webhook](https://dashboard.stripe.com/webhooks) to actually send this event to your application. Once the webhook has been enabled within the Stripe dashboard, you may [handle the webhook with Cashier](#handling-stripe-webhooks). The object contained in the webhook payload will be a [checkout object](https://stripe.com/docs/api/checkout/sessions/object) that you may inspect in order to fulfill your customer's order. ## Handling Failed Payments @@ -1798,17 +2457,19 @@ Sometimes, payments for subscriptions or single charges can fail. When this happ First, you could redirect your customer to the dedicated payment confirmation page which is included with Cashier. This page already has an associated named route that is registered via Cashier's service provider. So, you may catch the `IncompletePayment` exception and redirect the user to the payment confirmation page: - use Laravel\Cashier\Exceptions\IncompletePayment; +```php +use Laravel\Cashier\Exceptions\IncompletePayment; - try { - $subscription = $user->newSubscription('default', 'price_monthly') - ->create($paymentMethod); - } catch (IncompletePayment $exception) { - return redirect()->route( - 'cashier.payment', - [$exception->payment->id, 'redirect' => route('home')] - ); - } +try { + $subscription = $user->newSubscription('default', 'price_monthly') + ->create($paymentMethod); +} catch (IncompletePayment $exception) { + return redirect()->route( + 'cashier.payment', + [$exception->payment->id, 'redirect' => route('home')] + ); +} +``` On the payment confirmation page, the customer will be prompted to enter their credit card information again and perform any additional actions required by Stripe, such as "3D Secure" confirmation. After confirming their payment, the user will be redirected to the URL provided by the `redirect` parameter specified above. Upon redirection, `message` (string) and `success` (integer) query string variables will be added to the URL. The payment page currently supports the following payment method types: @@ -1831,38 +2492,56 @@ Payment exceptions may be thrown for the following methods: `charge`, `invoiceFo Determining if an existing subscription has an incomplete payment may be accomplished using the `hasIncompletePayment` method on the billable model or a subscription instance: - if ($user->hasIncompletePayment('default')) { - // - } +```php +if ($user->hasIncompletePayment('default')) { + // ... +} - if ($user->subscription('default')->hasIncompletePayment()) { - // - } +if ($user->subscription('default')->hasIncompletePayment()) { + // ... +} +``` You can derive the specific status of an incomplete payment by inspecting the `payment` property on the exception instance: - use Laravel\Cashier\Exceptions\IncompletePayment; +```php +use Laravel\Cashier\Exceptions\IncompletePayment; - try { - $user->charge(1000, 'pm_card_threeDSecure2Required'); - } catch (IncompletePayment $exception) { - // Get the payment intent status... - $exception->payment->status; +try { + $user->charge(1000, 'pm_card_threeDSecure2Required'); +} catch (IncompletePayment $exception) { + // Get the payment intent status... + $exception->payment->status; - // Check specific conditions... - if ($exception->payment->requiresPaymentMethod()) { - // ... - } elseif ($exception->payment->requiresConfirmation()) { - // ... - } + // Check specific conditions... + if ($exception->payment->requiresPaymentMethod()) { + // ... + } elseif ($exception->payment->requiresConfirmation()) { + // ... } +} +``` + + +### Confirming Payments + +Some payment methods require additional data in order to confirm payments. For example, SEPA payment methods require additional "mandate" data during the payment process. You may provide this data to Cashier using the `withPaymentConfirmationOptions` method: + +```php +$subscription->withPaymentConfirmationOptions([ + 'mandate_data' => '...', +])->swap('price_xxx'); +``` + +You may consult the [Stripe API documentation](https://stripe.com/docs/api/payment_intents/confirm) to review all of the options accepted when confirming payments. ## Strong Customer Authentication If your business or one of your customers is based in Europe you will need to abide by the EU's Strong Customer Authentication (SCA) regulations. These regulations were imposed in September 2019 by the European Union to prevent payment fraud. Luckily, Stripe and Cashier are prepared for building SCA compliant applications. -> {note} Before getting started, review [Stripe's guide on PSD2 and SCA](https://stripe.com/guides/strong-customer-authentication) as well as their [documentation on the new SCA APIs](https://stripe.com/docs/strong-customer-authentication). +> [!WARNING] +> Before getting started, review [Stripe's guide on PSD2 and SCA](https://stripe.com/guides/strong-customer-authentication) as well as their [documentation on the new SCA APIs](https://stripe.com/docs/strong-customer-authentication). ### Payments Requiring Additional Confirmation @@ -1889,40 +2568,50 @@ CASHIER_PAYMENT_NOTIFICATION=Laravel\Cashier\Notifications\ConfirmPayment To ensure that off-session payment confirmation notifications are delivered, verify that [Stripe webhooks are configured](#handling-stripe-webhooks) for your application and the `invoice.payment_action_required` webhook is enabled in your Stripe dashboard. In addition, your `Billable` model should also use Laravel's `Illuminate\Notifications\Notifiable` trait. -> {note} Notifications will be sent even when customers are manually making a payment that requires additional confirmation. Unfortunately, there is no way for Stripe to know that the payment was done manually or "off-session". But, a customer will simply see a "Payment Successful" message if they visit the payment page after already confirming their payment. The customer will not be allowed to accidentally confirm the same payment twice and incur an accidental second charge. +> [!WARNING] +> Notifications will be sent even when customers are manually making a payment that requires additional confirmation. Unfortunately, there is no way for Stripe to know that the payment was done manually or "off-session". But, a customer will simply see a "Payment Successful" message if they visit the payment page after already confirming their payment. The customer will not be allowed to accidentally confirm the same payment twice and incur an accidental second charge. ## Stripe SDK Many of Cashier's objects are wrappers around Stripe SDK objects. If you would like to interact with the Stripe objects directly, you may conveniently retrieve them using the `asStripe` method: - $stripeSubscription = $subscription->asStripeSubscription(); +```php +$stripeSubscription = $subscription->asStripeSubscription(); - $stripeSubscription->application_fee_percent = 5; +$stripeSubscription->application_fee_percent = 5; - $stripeSubscription->save(); +$stripeSubscription->save(); +``` You may also use the `updateStripeSubscription` method to update a Stripe subscription directly: - $subscription->updateStripeSubscription(['application_fee_percent' => 5]); +```php +$subscription->updateStripeSubscription(['application_fee_percent' => 5]); +``` You may invoke the `stripe` method on the `Cashier` class if you would like to use the `Stripe\StripeClient` client directly. For example, you could use this method to access the `StripeClient` instance and retrieve a list of prices from your Stripe account: - use Laravel\Cashier\Cashier; +```php +use Laravel\Cashier\Cashier; - $prices = Cashier::stripe()->prices->all(); +$prices = Cashier::stripe()->prices->all(); +``` ## Testing -When testing an application that uses Cashier, you may mock the actual HTTP requests to the Stripe API; however, this requires you to partially re-implement Cashier's own behavior. Therefore, we recommend allowing your tests to hit the actual Stripe API. While this is slower, it provides more confidence that your application is working as expected and any slow tests may be placed within their own PHPUnit testing group. +When testing an application that uses Cashier, you may mock the actual HTTP requests to the Stripe API; however, this requires you to partially re-implement Cashier's own behavior. Therefore, we recommend allowing your tests to hit the actual Stripe API. While this is slower, it provides more confidence that your application is working as expected and any slow tests may be placed within their own Pest / PHPUnit testing group. When testing, remember that Cashier itself already has a great test suite, so you should only focus on testing the subscription and payment flow of your own application and not every underlying Cashier behavior. To get started, add the **testing** version of your Stripe secret to your `phpunit.xml` file: - +```xml + +``` Now, whenever you interact with Cashier while testing, it will send actual API requests to your Stripe testing environment. For convenience, you should pre-fill your Stripe testing account with subscriptions / prices that you may use during testing. -> {tip} In order to test a variety of billing scenarios, such as credit card denials and failures, you may use the vast range of [testing card numbers and tokens](https://stripe.com/docs/testing) provided by Stripe. +> [!NOTE] +> In order to test a variety of billing scenarios, such as credit card denials and failures, you may use the vast range of [testing card numbers and tokens](https://stripe.com/docs/testing) provided by Stripe. diff --git a/blade.md b/blade.md index ef8beae7d02..245aa7e1c2d 100644 --- a/blade.md +++ b/blade.md @@ -1,30 +1,36 @@ # Blade Templates - [Introduction](#introduction) + - [Supercharging Blade With Livewire](#supercharging-blade-with-livewire) - [Displaying Data](#displaying-data) - [HTML Entity Encoding](#html-entity-encoding) - - [Blade & JavaScript Frameworks](#blade-and-javascript-frameworks) + - [Blade and JavaScript Frameworks](#blade-and-javascript-frameworks) - [Blade Directives](#blade-directives) - [If Statements](#if-statements) - [Switch Statements](#switch-statements) - [Loops](#loops) - [The Loop Variable](#the-loop-variable) - [Conditional Classes](#conditional-classes) - - [Checked / Selected / Disabled](#checked-and-selected) + - [Additional Attributes](#additional-attributes) - [Including Subviews](#including-subviews) - [The `@once` Directive](#the-once-directive) - [Raw PHP](#raw-php) - [Comments](#comments) - [Components](#components) - [Rendering Components](#rendering-components) - - [Passing Data To Components](#passing-data-to-components) + - [Index Components](#index-components) + - [Passing Data to Components](#passing-data-to-components) - [Component Attributes](#component-attributes) - [Reserved Keywords](#reserved-keywords) - [Slots](#slots) - [Inline Component Views](#inline-component-views) - - [Anonymous Components](#anonymous-components) - [Dynamic Components](#dynamic-components) - [Manually Registering Components](#manually-registering-components) +- [Anonymous Components](#anonymous-components) + - [Anonymous Index Components](#anonymous-index-components) + - [Data Properties / Attributes](#data-properties-attributes) + - [Accessing Parent Data](#accessing-parent-data) + - [Anonymous Components Paths](#anonymous-component-paths) - [Building Layouts](#building-layouts) - [Layouts Using Components](#layouts-using-components) - [Layouts Using Template Inheritance](#layouts-using-template-inheritance) @@ -35,6 +41,7 @@ - [Stacks](#stacks) - [Service Injection](#service-injection) - [Rendering Inline Blade Templates](#rendering-inline-blade-templates) +- [Rendering Blade Fragments](#rendering-blade-fragments) - [Extending Blade](#extending-blade) - [Custom Echo Handlers](#custom-echo-handlers) - [Custom If Statements](#custom-if-statements) @@ -44,22 +51,29 @@ Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates. In fact, all Blade templates are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade template files use the `.blade.php` file extension and are typically stored in the `resources/views` directory. -Blade views may be returned from routes or controller using the global `view` helper. Of course, as mentioned in the documentation on [views](/docs/{{version}}/views), data may be passed to the Blade view using the `view` helper's second argument: +Blade views may be returned from routes or controllers using the global `view` helper. Of course, as mentioned in the documentation on [views](/docs/{{version}}/views), data may be passed to the Blade view using the `view` helper's second argument: - Route::get('/', function () { - return view('greeting', ['name' => 'Finn']); - }); +```php +Route::get('/', function () { + return view('greeting', ['name' => 'Finn']); +}); +``` + + +### Supercharging Blade With Livewire -> {tip} Want to take your Blade templates to the next level and build dynamic interfaces with ease? Check out [Laravel Livewire](https://laravel-livewire.com). +Want to take your Blade templates to the next level and build dynamic interfaces with ease? Check out [Laravel Livewire](https://livewire.laravel.com). Livewire allows you to write Blade components that are augmented with dynamic functionality that would typically only be possible via frontend frameworks like React or Vue, providing a great approach to building modern, reactive frontends without the complexities, client-side rendering, or build steps of many JavaScript frameworks. ## Displaying Data You may display data that is passed to your Blade views by wrapping the variable in curly braces. For example, given the following route: - Route::get('/', function () { - return view('welcome', ['name' => 'Samantha']); - }); +```php +Route::get('/', function () { + return view('welcome', ['name' => 'Samantha']); +}); +``` You may display the contents of the `name` variable like so: @@ -67,7 +81,8 @@ You may display the contents of the `name` variable like so: Hello, {{ $name }}. ``` -> {tip} Blade's `{{ }}` echo statements are automatically sent through PHP's `htmlspecialchars` function to prevent XSS attacks. +> [!NOTE] +> Blade's `{{ }}` echo statements are automatically sent through PHP's `htmlspecialchars` function to prevent XSS attacks. You are not limited to displaying the contents of the variables passed to the view. You may also echo the results of any PHP function. In fact, you can put any PHP code you wish inside of a Blade echo statement: @@ -78,27 +93,27 @@ The current UNIX timestamp is {{ time() }}. ### HTML Entity Encoding -By default, Blade (and the Laravel `e` helper) will double encode HTML entities. If you would like to disable double encoding, call the `Blade::withoutDoubleEncoding` method from the `boot` method of your `AppServiceProvider`: +By default, Blade (and the Laravel `e` function) will double encode HTML entities. If you would like to disable double encoding, call the `Blade::withoutDoubleEncoding` method from the `boot` method of your `AppServiceProvider`: - #### Displaying Unescaped Data @@ -109,10 +124,11 @@ By default, Blade `{{ }}` statements are automatically sent through PHP's `htmls Hello, {!! $name !!}. ``` -> {note} Be very careful when echoing content that is supplied by users of your application. You should typically use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data. +> [!WARNING] +> Be very careful when echoing content that is supplied by users of your application. You should typically use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data. -### Blade & JavaScript Frameworks +### Blade and JavaScript Frameworks Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the `@` symbol to inform the Blade rendering engine an expression should remain untouched. For example: @@ -139,13 +155,13 @@ The `@` symbol may also be used to escape Blade directives: Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example: -```blade +```php ``` -However, instead of manually calling `json_encode`, you may use the `Illuminate\Support\Js::from` method directive. The `from` method accepts the same arguments as PHP's `json_encode` function; however, it will ensure that the resulting JSON is properly escaped for inclusion within HTML quotes. The `from` method will return a string `JSON.parse` JavaScript statement that will convert the given object or array into a valid JavaScript object: +However, instead of manually calling `json_encode`, you may use the `Illuminate\Support\Js::from` method directive. The `from` method accepts the same arguments as PHP's `json_encode` function; however, it will ensure that the resulting JSON has been properly escaped for inclusion within HTML quotes. The `from` method will return a string `JSON.parse` JavaScript statement that will convert the given object or array into a valid JavaScript object: ```blade ``` -> {note} You should only use the `Js::from` method to render existing variables as JSON. The Blade templating is based on regular expressions and attempts to pass a complex expression to the directive may cause unexpected failures. +> [!WARNING] +> You should only use the `Js::from` method to render existing variables as JSON. The Blade templating is based on regular expressions and attempts to pass a complex expression to the directive may cause unexpected failures. #### The `@verbatim` Directive @@ -291,6 +308,30 @@ You may use the `sectionMissing` directive to determine if a section does not ha @endif ``` + +#### Session Directives + +The `@session` directive may be used to determine if a [session](/docs/{{version}}/session) value exists. If the session value exists, the template contents within the `@session` and `@endsession` directives will be evaluated. Within the `@session` directive's contents, you may echo the `$value` variable to display the session value: + +```blade +@session('status') +
+ {{ $value }} +
+@endsession +``` + + +#### Context Directives + +The `@context` directive may be used to determine if a [context](/docs/{{version}}/context) value exists. If the context value exists, the template contents within the `@context` and `@endcontext` directives will be evaluated. Within the `@context` directive's contents, you may echo the `$value` variable to display the context value: + +```blade +@context('canonical') + +@endcontext +``` + ### Switch Statements @@ -336,9 +377,10 @@ In addition to conditional statements, Blade provides simple directives for work @endwhile ``` -> {tip} While iterating through a `foreach` loop, you may use the [loop variable](#the-loop-variable) to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop. +> [!NOTE] +> While iterating through a `foreach` loop, you may use the [loop variable](#the-loop-variable) to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop. -When using loops you may also end the loop or skip the current iteration using the `@continue` and `@break` directives: +When using loops you may also skip the current iteration or end the loop using the `@continue` and `@break` directives: ```blade @foreach ($users as $user) @@ -399,21 +441,25 @@ If you are in a nested loop, you may access the parent loop's `$loop` variable v The `$loop` variable also contains a variety of other useful properties: -Property | Description -------------- | ------------- -`$loop->index` | The index of the current loop iteration (starts at 0). -`$loop->iteration` | The current loop iteration (starts at 1). -`$loop->remaining` | The iterations remaining in the loop. -`$loop->count` | The total number of items in the array being iterated. -`$loop->first` | Whether this is the first iteration through the loop. -`$loop->last` | Whether this is the last iteration through the loop. -`$loop->even` | Whether this is an even iteration through the loop. -`$loop->odd` | Whether this is an odd iteration through the loop. -`$loop->depth` | The nesting level of the current loop. -`$loop->parent` | When in a nested loop, the parent's loop variable. +
+ +| Property | Description | +| ------------------ | ------------------------------------------------------ | +| `$loop->index` | The index of the current loop iteration (starts at 0). | +| `$loop->iteration` | The current loop iteration (starts at 1). | +| `$loop->remaining` | The iterations remaining in the loop. | +| `$loop->count` | The total number of items in the array being iterated. | +| `$loop->first` | Whether this is the first iteration through the loop. | +| `$loop->last` | Whether this is the last iteration through the loop. | +| `$loop->even` | Whether this is an even iteration through the loop. | +| `$loop->odd` | Whether this is an odd iteration through the loop. | +| `$loop->depth` | The nesting level of the current loop. | +| `$loop->parent` | When in a nested loop, the parent's loop variable. | + +
-### Conditional Classes +### Conditional Classes & Styles The `@class` directive conditionally compiles a CSS class string. The directive accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list: @@ -433,16 +479,33 @@ The `@class` directive conditionally compiles a CSS class string. The directive ``` - -### Checked / Selected / Disabled +Likewise, the `@style` directive may be used to conditionally add inline CSS styles to an HTML element: + +```blade +@php + $isActive = true; +@endphp + + $isActive, +])> + + +``` + + +### Additional Attributes For convenience, you may use the `@checked` directive to easily indicate if a given HTML checkbox input is "checked". This directive will echo `checked` if the provided condition evaluates to `true`: ```blade -active)) /> +active)) +/> ``` Likewise, the `@selected` directive may be used to indicate if a given select option should be "selected": @@ -463,10 +526,33 @@ Additionally, the `@disabled` directive may be used to indicate if a given eleme ``` +Moreover, the `@readonly` directive may be used to indicate if a given element should be "readonly": + +```blade +isNotAdmin()) +/> +``` + +In addition, the `@required` directive may be used to indicate if a given element should be "required": + +```blade +isAdmin()) +/> +``` + ### Including Subviews -> {tip} While you're free to use the `@include` directive, Blade [components](#components) provide similar functionality and offer several benefits over the `@include` directive such as data and attribute binding. +> [!NOTE] +> While you're free to use the `@include` directive, Blade [components](#components) provide similar functionality and offer several benefits over the `@include` directive such as data and attribute binding. Blade's `@include` directive allows you to include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view: @@ -506,10 +592,11 @@ To include the first view that exists from a given array of views, you may use t @includeFirst(['custom.admin', 'admin'], ['status' => 'complete']) ``` -> {note} You should avoid using the `__DIR__` and `__FILE__` constants in your Blade views, since they will refer to the location of the cached, compiled view. +> [!WARNING] +> You should avoid using the `__DIR__` and `__FILE__` constants in your Blade views, since they will refer to the location of the cached, compiled view. -#### Rendering Views For Collections +#### Rendering Views for Collections You may combine loops and includes into one line with Blade's `@each` directive: @@ -525,7 +612,8 @@ You may also pass a fourth argument to the `@each` directive. This argument dete @each('view.name', $jobs, 'job', 'view.empty') ``` -> {note} Views rendered via `@each` do not inherit the variables from the parent view. If the child view requires these variables, you should use the `@foreach` and `@include` directives instead. +> [!WARNING] +> Views rendered via `@each` do not inherit the variables from the parent view. If the child view requires these variables, you should use the `@foreach` and `@include` directives instead. ### The `@once` Directive @@ -552,6 +640,20 @@ Since the `@once` directive is often used in conjunction with the `@push` or `@p @endPushOnce ``` +If you are pushing duplicate content from two separate Blade templates, you should provide a unique identifier as the second argument to the `@pushOnce` directive to ensure the content is only rendered once: + +```blade + +@pushOnce('scripts', 'chart.js') + +@endPushOnce + + +@pushOnce('scripts', 'chart.js') + +@endPushOnce +``` + ### Raw PHP @@ -563,6 +665,45 @@ In some situations, it's useful to embed PHP code into your views. You can use t @endphp ``` +Or, if you only need to use PHP to import a class, you may use the `@use` directive: + +```blade +@use('App\Models\Flight') +``` + +A second argument may be provided to the `@use` directive to alias the imported class: + +```blade +@use('App\Models\Flight', 'FlightModel') +``` + +If you have multiple classes within the same namespace, you may group the imports of those classes: + +```blade +@use('App\Models\{Flight, Airport}') +``` + +The `@use` directive also supports importing PHP functions and constants by prefixing the import path with the `function` or `const` modifiers: + +```blade +@use(function App\Helpers\format_currency) +@use(const App\Constants\MAX_ATTEMPTS) +``` + +Just like class imports, aliases are supported for functions and constants as well: + +```blade +@use(function App\Helpers\format_currency, 'formatMoney') +@use(const App\Constants\MAX_ATTEMPTS, 'MAX_TRIES') +``` + +Grouped imports are also supported with both function and const modifiers, allowing you to import multiple symbols from the same namespace in a single directive: + +```blade +@use(function App\Helpers\{format_currency, format_date}) +@use(const App\Constants\{MAX_ATTEMPTS, DEFAULT_TIMEOUT}) +``` + ### Comments @@ -575,9 +716,9 @@ Blade also allows you to define comments in your views. However, unlike HTML com ## Components -Components and slots provide similar benefits to sections, layouts, and includes; however, some may find the mental model of components and slots easier to understand. There are two approaches to writing components: class based components and anonymous components. +Components and slots provide similar benefits to sections, layouts, and includes; however, some may find the mental model of components and slots easier to understand. There are two approaches to writing components: class-based components and anonymous components. -To create a class based component, you may use the `make:component` Artisan command. To illustrate how to use components, we will create a simple `Alert` component. The `make:component` command will place the component in the `App\View\Components` directory: +To create a class-based component, you may use the `make:component` Artisan command. To illustrate how to use components, we will create a simple `Alert` component. The `make:component` command will place the component in the `app/View/Components` directory: ```shell php artisan make:component Alert @@ -591,15 +732,7 @@ You may also create components within subdirectories: php artisan make:component Forms/Input ``` -The command above will create an `Input` component in the `App\View\Components\Forms` directory and the view will be placed in the `resources/views/components/forms` directory. - -If you would like to create an anonymous component (a component with only a Blade template and no class), you may use the `--view` flag when invoking the `make:component` command: - -```shell -php artisan make:component forms.input --view -``` - -The command above will create a Blade file at `resources/views/components/forms/input.blade.php` which can be rendered as a component via ``. +The command above will create an `Input` component in the `app/View/Components/Forms` directory and the view will be placed in the `resources/views/components/forms` directory. #### Manually Registering Package Components @@ -608,15 +741,17 @@ When writing components for your own application, components are automatically d However, if you are building a package that utilizes Blade components, you will need to manually register your component class and its HTML tag alias. You should typically register your components in the `boot` method of your package's service provider: - use Illuminate\Support\Facades\Blade; +```php +use Illuminate\Support\Facades\Blade; - /** - * Bootstrap your package's services. - */ - public function boot() - { - Blade::component('package-alert', Alert::class); - } +/** + * Bootstrap your package's services. + */ +public function boot(): void +{ + Blade::component('package-alert', Alert::class); +} +``` Once your component has been registered, it may be rendered using its tag alias: @@ -626,17 +761,17 @@ Once your component has been registered, it may be rendered using its tag alias: Alternatively, you may use the `componentNamespace` method to autoload component classes by convention. For example, a `Nightshade` package might have `Calendar` and `ColorPicker` components that reside within the `Package\Views\Components` namespace: - use Illuminate\Support\Facades\Blade; +```php +use Illuminate\Support\Facades\Blade; - /** - * Bootstrap your package's services. - * - * @return void - */ - public function boot() - { - Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade'); - } +/** + * Bootstrap your package's services. + */ +public function boot(): void +{ + Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade'); +} +``` This will allow the usage of package components by their vendor namespace using the `package-name::` syntax: @@ -658,14 +793,48 @@ To display a component, you may use a Blade component tag within one of your Bla ``` -If the component class is nested deeper within the `App\View\Components` directory, you may use the `.` character to indicate directory nesting. For example, if we assume a component is located at `App\View\Components\Inputs\Button.php`, we may render it like so: +If the component class is nested deeper within the `app/View/Components` directory, you may use the `.` character to indicate directory nesting. For example, if we assume a component is located at `app/View/Components/Inputs/Button.php`, we may render it like so: ```blade ``` +If you would like to conditionally render your component, you may define a `shouldRender` method on your component class. If the `shouldRender` method returns `false` the component will not be rendered: + +```php +use Illuminate\Support\Str; + +/** + * Whether the component should be rendered + */ +public function shouldRender(): bool +{ + return Str::length($this->message) > 0; +} +``` + + +### Index Components + +Sometimes components are part of a component group and you may wish to group the related components within a single directory. For example, imagine a "card" component with the following class structure: + +```text +App\Views\Components\Card\Card +App\Views\Components\Card\Header +App\Views\Components\Card\Body +``` + +Since the root `Card` component is nested within a `Card` directory, you might expect that you would need to render the component via ``. However, when a component's file name matches the name of the component's directory, Laravel automatically assumes that component is the "root" component and allows you to render the component without repeating the directory name: + +```blade + + ... + ... + +``` + -### Passing Data To Components +### Passing Data to Components You may pass data to Blade components using HTML attributes. Hard-coded, primitive values may be passed to the component using simple HTML attribute strings. PHP expressions and variables should be passed to the component via attributes that use the `:` character as a prefix: @@ -673,53 +842,35 @@ You may pass data to Blade components using HTML attributes. Hard-coded, primiti ``` -You should define the component's required data in its class constructor. All public properties on a component will automatically be made available to the component's view. It is not necessary to pass the data to the view from the component's `render` method: +You should define all of the component's data attributes in its class constructor. All public properties on a component will automatically be made available to the component's view. It is not necessary to pass the data to the view from the component's `render` method: - type = $type; - $this->message = $message; - } - - /** - * Get the view / contents that represent the component. - * - * @return \Illuminate\View\View|\Closure|string - */ - public function render() - { - return view('components.alert'); - } + return view('components.alert'); } +} +``` When your component is rendered, you may display the contents of your component's public variables by echoing the variables by name: @@ -734,16 +885,14 @@ When your component is rendered, you may display the contents of your component' Component constructor arguments should be specified using `camelCase`, while `kebab-case` should be used when referencing the argument names in your HTML attributes. For example, given the following component constructor: - /** - * Create the component instance. - * - * @param string $alertType - * @return void - */ - public function __construct($alertType) - { - $this->alertType = $alertType; - } +```php +/** + * Create the component instance. + */ +public function __construct( + public string $alertType, +) {} +``` The `$alertType` argument may be provided to the component like so: @@ -751,6 +900,19 @@ The `$alertType` argument may be provided to the component like so: ``` + +#### Short Attribute Syntax + +When passing attributes to components, you may also use a "short attribute" syntax. This is often convenient since attribute names frequently match the variable names they correspond to: + +```blade +{{-- Short attribute syntax... --}} + + +{{-- Is equivalent to... --}} + +``` + #### Escaping Attribute Rendering @@ -775,45 +937,57 @@ The following HTML will be rendered by Blade: In addition to public variables being available to your component template, any public methods on the component may be invoked. For example, imagine a component that has an `isSelected` method: - /** - * Determine if the given option is the currently selected option. - * - * @param string $option - * @return bool - */ - public function isSelected($option) - { - return $option === $this->selected; - } +```php +/** + * Determine if the given option is the currently selected option. + */ +public function isSelected(string $option): bool +{ + return $option === $this->selected; +} +``` You may execute this method from your component template by invoking the variable matching the name of the method: ```blade - ``` -#### Accessing Attributes & Slots Within Component Classes +#### Accessing Attributes and Slots Within Component Classes -Blade components also allow you to access the component name, attributes, and slot inside the class's render method. However, in order to access this data, you should return a closure from your component's `render` method. The closure will receive a `$data` array as its only argument. This array will contain several elements that provide information about the component: +Blade components also allow you to access the component name, attributes, and slot inside the class's render method. However, in order to access this data, you should return a closure from your component's `render` method: - /** - * Get the view / contents that represent the component. - * - * @return \Illuminate\View\View|\Closure|string - */ - public function render() - { - return function (array $data) { - // $data['componentName']; - // $data['attributes']; - // $data['slot']; +```php +use Closure; - return '
Components content
'; - }; - } +/** + * Get the view / contents that represent the component. + */ +public function render(): Closure +{ + return function () { + return '
Components content
'; + }; +} +``` + +The closure returned by your component's `render` method may also receive a `$data` array as its only argument. This array will contain several elements that provide information about the component: + +```php +return function (array $data) { + // $data['componentName']; + // $data['attributes']; + // $data['slot']; + + return '
Components content
'; +} +``` + +> [!WARNING] +> The elements in the `$data` array should never be directly embedded into the Blade string returned by your `render` method, as doing so could allow remote code execution via malicious attribute content. The `componentName` is equal to the name used in the HTML tag after the `x-` prefix. So ``'s `componentName` will be `alert`. The `attributes` element will contain all of the attributes that were present on the HTML tag. The `slot` element is an `Illuminate\Support\HtmlString` instance with the contents of the component's slot. @@ -829,18 +1003,12 @@ use App\Services\AlertCreator; /** * Create the component instance. - * - * @param \App\Services\AlertCreator $creator - * @param string $type - * @param string $message - * @return void */ -public function __construct(AlertCreator $creator, $type, $message) -{ - $this->creator = $creator; - $this->type = $type; - $this->message = $message; -} +public function __construct( + public AlertCreator $creator, + public string $type, + public string $message, +) {} ``` @@ -848,28 +1016,30 @@ public function __construct(AlertCreator $creator, $type, $message) If you would like to prevent some public methods or properties from being exposed as variables to your component template, you may add them to an `$except` array property on your component: - ### Component Attributes @@ -888,7 +1058,8 @@ All of the attributes that are not part of the component's constructor will auto ``` -> {note} Using directives such as `@env` within component tags is not supported at this time. For example, `` will not be compiled. +> [!WARNING] +> Using directives such as `@env` within component tags is not supported at this time. For example, `` will not be compiled. #### Default / Merged Attributes @@ -934,7 +1105,8 @@ If you need to merge other attributes onto your component, you can chain the `me ``` -> {tip} If you need to conditionally compile classes on other HTML elements that shouldn't receive merged attributes, you can use the [`@class` directive](#conditional-classes). +> [!NOTE] +> If you need to conditionally compile classes on other HTML elements that shouldn't receive merged attributes, you can use the [@class directive](#conditional-classes). #### Non-Class Attribute Merging @@ -972,12 +1144,12 @@ If you would like an attribute other than `class` to have its default value and ``` -#### Retrieving & Filtering Attributes +#### Retrieving and Filtering Attributes You may filter attributes using the `filter` method. This method accepts a closure which should return `true` if you wish to retain the attribute in the attribute bag: ```blade -{{ $attributes->filter(fn ($value, $key) => $key == 'foo') }} +{{ $attributes->filter(fn (string $value, string $key) => $key == 'foo') }} ``` For convenience, you may use the `whereStartsWith` method to retrieve all attributes whose keys begin with a given string: @@ -1006,12 +1178,40 @@ If you would like to check if an attribute is present on the component, you may @endif ``` +If an array is passed to the `has` method, the method will determine if all of the given attributes are present on the component: + +```blade +@if ($attributes->has(['name', 'class'])) +
All of the attributes are present
+@endif +``` + +The `hasAny` method may be used to determine if any of the given attributes are present on the component: + +```blade +@if ($attributes->hasAny(['href', ':href', 'v-bind:href'])) +
One of the attributes is present
+@endif +``` + You may retrieve a specific attribute's value using the `get` method: ```blade {{ $attributes->get('class') }} ``` +The `only` method may be used to retrieve only the attributes with the given keys: + +```blade +{{ $attributes->only(['class']) }} +``` + +The `except` method may be used to retrieve all attributes except those with the given keys: + +```blade +{{ $attributes->except(['class']) }} +``` + ### Reserved Keywords @@ -1021,6 +1221,7 @@ By default, some keywords are reserved for Blade's internal use in order to rend - `data` - `render` +- `resolve` - `resolveView` - `shouldRender` - `view` @@ -1074,6 +1275,28 @@ You may define the content of the named slot using the `x-slot` tag. Any content
``` +You may invoke a slot's `isEmpty` method to determine if the slot contains content: + +```blade +{{ $title }} + +
+ @if ($slot->isEmpty()) + This is default content if the slot is empty. + @else + {{ $slot }} + @endif +
+``` + +Additionally, the `hasActualContent` method may be used to determine if the slot contains any "actual" content that is not an HTML comment: + +```blade +@if ($slot->hasActualContent()) + The scope has non-comment content. +@endif +``` + #### Scoped Slots @@ -1134,19 +1357,19 @@ To interact with slot attributes, you may access the `attributes` property of th For very small components, it may feel cumbersome to manage both the component class and the component's view template. For this reason, you may return the component's markup directly from the `render` method: - /** - * Get the view / contents that represent the component. - * - * @return \Illuminate\View\View|\Closure|string - */ - public function render() - { - return <<<'blade' -
- {{ $slot }} -
- blade; - } +```php +/** + * Get the view / contents that represent the component. + */ +public function render(): string +{ + return <<<'blade' +
+ {{ $slot }} +
+ blade; +} +``` #### Generating Inline View Components @@ -1157,8 +1380,73 @@ To create a component that renders an inline view, you may use the `inline` opti php artisan make:component Alert --inline ``` + +### Dynamic Components + +Sometimes you may need to render a component but not know which component should be rendered until runtime. In this situation, you may use Laravel's built-in `dynamic-component` component to render the component based on a runtime value or variable: + +```blade +// $componentName = "secondary-button"; + + +``` + + +### Manually Registering Components + +> [!WARNING] +> The following documentation on manually registering components is primarily applicable to those who are writing Laravel packages that include view components. If you are not writing a package, this portion of the component documentation may not be relevant to you. + +When writing components for your own application, components are automatically discovered within the `app/View/Components` directory and `resources/views/components` directory. + +However, if you are building a package that utilizes Blade components or placing components in non-conventional directories, you will need to manually register your component class and its HTML tag alias so that Laravel knows where to find the component. You should typically register your components in the `boot` method of your package's service provider: + +```php +use Illuminate\Support\Facades\Blade; +use VendorPackage\View\Components\AlertComponent; + +/** + * Bootstrap your package's services. + */ +public function boot(): void +{ + Blade::component('package-alert', AlertComponent::class); +} +``` + +Once your component has been registered, it may be rendered using its tag alias: + +```blade + +``` + +#### Autoloading Package Components + +Alternatively, you may use the `componentNamespace` method to autoload component classes by convention. For example, a `Nightshade` package might have `Calendar` and `ColorPicker` components that reside within the `Package\Views\Components` namespace: + +```php +use Illuminate\Support\Facades\Blade; + +/** + * Bootstrap your package's services. + */ +public function boot(): void +{ + Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade'); +} +``` + +This will allow the usage of package components by their vendor namespace using the `package-name::` syntax: + +```blade + + +``` + +Blade will automatically detect the class that's linked to this component by pascal-casing the component name. Subdirectories are also supported using "dot" notation. + -### Anonymous Components +## Anonymous Components Similar to inline components, anonymous components provide a mechanism for managing a component via a single file. However, anonymous components utilize a single view file and have no associated class. To define an anonymous component, you only need to place a Blade template within your `resources/views/components` directory. For example, assuming you have defined a component at `resources/views/components/alert.blade.php`, you may simply render it like so: @@ -1172,12 +1460,20 @@ You may use the `.` character to indicate if a component is nested deeper inside ``` +To create an anonymous component via Artisan, you may use the `--view` flag when invoking the `make:component` command: + +```shell +php artisan make:component forms.input --view +``` + +The command above will create a Blade file at `resources/views/components/forms/input.blade.php` which can be rendered as a component via ``. + -#### Anonymous Index Components +### Anonymous Index Components Sometimes, when a component is made up of many Blade templates, you may wish to group the given component's templates within a single directory. For example, imagine an "accordion" component with the following directory structure: -```none +```text /resources/views/components/accordion.blade.php /resources/views/components/accordion/item.blade.php ``` @@ -1194,15 +1490,15 @@ This directory structure allows you to render the accordion component and its it However, in order to render the accordion component via `x-accordion`, we were forced to place the "index" accordion component template in the `resources/views/components` directory instead of nesting it within the `accordion` directory with the other accordion related templates. -Thankfully, Blade allows you to place an `index.blade.php` file within a component's template directory. When an `index.blade.php` template exists for the component, it will be rendered as the "root" node of the component. So, we can continue to use the same Blade syntax given in the example above; however, we will adjust our directory structure like so: +Thankfully, Blade allows you to place a file matching the component's directory name within the component's directory itself. When this template exists, it can be rendered as the "root" element of the component even though it is nested within a directory. So, we can continue to use the same Blade syntax given in the example above; however, we will adjust our directory structure like so: -```none -/resources/views/components/accordion/index.blade.php +```text +/resources/views/components/accordion/accordion.blade.php /resources/views/components/accordion/item.blade.php ``` -#### Data Properties / Attributes +### Data Properties / Attributes Since anonymous components do not have any associated class, you may wonder how you may differentiate which data should be passed to the component as variables and which attributes should be placed in the component's [attribute bag](#component-attributes). @@ -1225,7 +1521,7 @@ Given the component definition above, we may render the component like so: ``` -#### Accessing Parent Data +### Accessing Parent Data Sometimes you may want to access data from a parent component inside a child component. In these cases, you may use the `@aware` directive. For example, imagine we are building a complex menu component consisting of a parent `` and child ``: @@ -1260,70 +1556,44 @@ Because the `color` prop was only passed into the parent (``), it won't ``` -> {note} The `@aware` directive can not access parent data that is not explicitly passed to the parent component via HTML attributes. Default `@props` values that are not explicitly passed to the parent component can not be accessed by the `@aware` directive. - - -### Dynamic Components - -Sometimes you may need to render a component but not know which component should be rendered until runtime. In this situation, you may use Laravel's built-in `dynamic-component` component to render the component based on a runtime value or variable: - -```blade - -``` - - -### Manually Registering Components +> [!WARNING] +> The `@aware` directive cannot access parent data that is not explicitly passed to the parent component via HTML attributes. Default `@props` values that are not explicitly passed to the parent component cannot be accessed by the `@aware` directive. -> {note} The following documentation on manually registering components is primarily applicable to those who are writing Laravel packages that include view components. If you are not writing a package, this portion of the component documentation may not be relevant to you. + +### Anonymous Component Paths -When writing components for your own application, components are automatically discovered within the `app/View/Components` directory and `resources/views/components` directory. +As previously discussed, anonymous components are typically defined by placing a Blade template within your `resources/views/components` directory. However, you may occasionally want to register other anonymous component paths with Laravel in addition to the default path. -However, if you are building a package that utilizes Blade components or placing components in non-conventional directories, you will need to manually register your component class and its HTML tag alias so that Laravel knows where to find the component. You should typically register your components in the `boot` method of your package's service provider: +The `anonymousComponentPath` method accepts the "path" to the anonymous component location as its first argument and an optional "namespace" that components should be placed under as its second argument. Typically, this method should be called from the `boot` method of one of your application's [service providers](/docs/{{version}}/providers): - use Illuminate\Support\Facades\Blade; - use VendorPackage\View\Components\AlertComponent; - - /** - * Bootstrap your package's services. - * - * @return void - */ - public function boot() - { - Blade::component('package-alert', AlertComponent::class); - } +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Blade::anonymousComponentPath(__DIR__.'/../components'); +} +``` -Once your component has been registered, it may be rendered using its tag alias: +When component paths are registered without a specified prefix as in the example above, they may be rendered in your Blade components without a corresponding prefix as well. For example, if a `panel.blade.php` component exists in the path registered above, it may be rendered like so: ```blade - + ``` -#### Autoloading Package Components - -Alternatively, you may use the `componentNamespace` method to autoload component classes by convention. For example, a `Nightshade` package might have `Calendar` and `ColorPicker` components that reside within the `Package\Views\Components` namespace: +Prefix "namespaces" may be provided as the second argument to the `anonymousComponentPath` method: - use Illuminate\Support\Facades\Blade; - - /** - * Bootstrap your package's services. - * - * @return void - */ - public function boot() - { - Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade'); - } +```php +Blade::anonymousComponentPath(__DIR__.'/../components', 'dashboard'); +``` -This will allow the usage of package components by their vendor namespace using the `package-name::` syntax: +When a prefix is provided, components within that "namespace" may be rendered by prefixing to the component's namespace to the component name when the component is rendered: ```blade - - + ``` -Blade will automatically detect the class that's linked to this component by pascal-casing the component name. Subdirectories are also supported using "dot" notation. - ## Building Layouts @@ -1333,7 +1603,7 @@ Blade will automatically detect the class that's linked to this component by pas Most web applications maintain the same general layout across various pages. It would be incredibly cumbersome and hard to maintain our application if we had to repeat the entire layout HTML in every view we create. Thankfully, it's convenient to define this layout as a single [Blade component](#components) and then use it throughout our application. -#### Defining The Layout Component +#### Defining the Layout Component For example, imagine we are building a "todo" list application. We might define a `layout` component that looks like the following: @@ -1353,7 +1623,7 @@ For example, imagine we are building a "todo" list application. We might define ``` -#### Applying The Layout Component +#### Applying the Layout Component Once the `layout` component has been defined, we may create a Blade view that utilizes the component. In this example, we will define a simple view that displays our task list: @@ -1362,7 +1632,7 @@ Once the `layout` component has been defined, we may create a Blade view that ut @foreach ($tasks as $task) - {{ $task }} +
{{ $task }}
@endforeach
``` @@ -1378,24 +1648,26 @@ Remember, content that is injected into a component will be supplied to the defa @foreach ($tasks as $task) - {{ $task }} +
{{ $task }}
@endforeach ``` Now that we have defined our layout and task list views, we just need to return the `task` view from a route: - use App\Models\Task; +```php +use App\Models\Task; - Route::get('/tasks', function () { - return view('tasks', ['tasks' => Task::all()]); - }); +Route::get('/tasks', function () { + return view('tasks', ['tasks' => Task::all()]); +}); +``` ### Layouts Using Template Inheritance -#### Defining A Layout +#### Defining a Layout Layouts may also be created via "template inheritance". This was the primary way of building applications prior to the introduction of [components](#components). @@ -1425,7 +1697,7 @@ As you can see, this file contains typical HTML mark-up. However, take note of t Now that we have defined a layout for our application, let's define a child page that inherits the layout. -#### Extending A Layout +#### Extending a Layout When defining a child view, use the `@extends` Blade directive to specify which layout the child view should "inherit". Views which extend a Blade layout may inject content into the layout's sections using `@section` directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using `@yield`: @@ -1449,7 +1721,8 @@ When defining a child view, use the `@extends` Blade directive to specify which In this example, the `sidebar` section is utilizing the `@@parent` directive to append (rather than overwriting) content to the layout's sidebar. The `@@parent` directive will be replaced by the content of the layout when the view is rendered. -> {tip} Contrary to the previous example, this `sidebar` section ends with `@endsection` instead of `@show`. The `@endsection` directive will only define a section while `@show` will define and **immediately yield** the section. +> [!NOTE] +> Contrary to the previous example, this `sidebar` section ends with `@endsection` instead of `@show`. The `@endsection` directive will only define a section while `@show` will define and **immediately yield** the section. The `@yield` directive also accepts a default value as its second parameter. This value will be rendered if the section being yielded is undefined: @@ -1496,9 +1769,11 @@ The `@error` directive may be used to quickly check if [validation error message - + class="@error('title') is-invalid @enderror" +/> @error('title')
{{ $message }}
@@ -1512,9 +1787,11 @@ Since the `@error` directive compiles to an "if" statement, you may use the `@el - + class="@error('email') is-invalid @else is-valid @enderror" +/> ``` You may pass [the name of a specific error bag](/docs/{{version}}/validation#named-error-bags) as the second parameter to the `@error` directive to retrieve validation error messages on pages containing multiple forms: @@ -1524,9 +1801,11 @@ You may pass [the name of a specific error bag](/docs/{{version}}/validation#nam - + class="@error('email', 'login') is-invalid @enderror" +/> @error('email', 'login')
{{ $message }}
@@ -1544,6 +1823,14 @@ Blade allows you to push to named stacks which can be rendered somewhere else in @endpush ``` +If you would like to `@push` content if a given boolean expression evaluates to `true`, you may use the `@pushIf` directive: + +```blade +@pushIf($shouldPush, 'scripts') + +@endPushIf +``` + You may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the `@stack` directive: ```blade @@ -1602,6 +1889,47 @@ return Blade::render( ); ``` + +## Rendering Blade Fragments + +When using frontend frameworks such as [Turbo](https://turbo.hotwired.dev/) and [htmx](https://htmx.org/), you may occasionally need to only return a portion of a Blade template within your HTTP response. Blade "fragments" allow you to do just that. To get started, place a portion of your Blade template within `@fragment` and `@endfragment` directives: + +```blade +@fragment('user-list') +
    + @foreach ($users as $user) +
  • {{ $user->name }}
  • + @endforeach +
+@endfragment +``` + +Then, when rendering the view that utilizes this template, you may invoke the `fragment` method to specify that only the specified fragment should be included in the outgoing HTTP response: + +```php +return view('dashboard', ['users' => $users])->fragment('user-list'); +``` + +The `fragmentIf` method allows you to conditionally return a fragment of a view based on a given condition. Otherwise, the entire view will be returned: + +```php +return view('dashboard', ['users' => $users]) + ->fragmentIf($request->hasHeader('HX-Request'), 'user-list'); +``` + +The `fragments` and `fragmentsIf` methods allow you to return multiple view fragments in the response. The fragments will be concatenated together: + +```php +view('dashboard', ['users' => $users]) + ->fragments(['user-list', 'comment-list']); + +view('dashboard', ['users' => $users]) + ->fragmentsIf( + $request->hasHeader('HX-Request'), + ['user-list', 'comment-list'] + ); +``` + ## Extending Blade @@ -1609,65 +1937,66 @@ Blade allows you to define your own custom directives using the `directive` meth The following example creates a `@datetime($var)` directive which formats a given `$var`, which should be an instance of `DateTime`: - format('m/d/Y H:i'); ?>"; - }); - } + // ... } + /** + * Bootstrap any application services. + */ + public function boot(): void + { + Blade::directive('datetime', function (string $expression) { + return "format('m/d/Y H:i'); ?>"; + }); + } +} +``` + As you can see, we will chain the `format` method onto whatever expression is passed into the directive. So, in this example, the final PHP generated by this directive will be: - format('m/d/Y H:i'); ?> +```php +format('m/d/Y H:i'); ?> +``` -> {note} After updating the logic of a Blade directive, you will need to delete all of the cached Blade views. The cached Blade views may be removed using the `view:clear` Artisan command. +> [!WARNING] +> After updating the logic of a Blade directive, you will need to delete all of the cached Blade views. The cached Blade views may be removed using the `view:clear` Artisan command. ### Custom Echo Handlers -If you attempt to "echo" an object using Blade, the object's `__toString` method will be invoked. The [`__toString`](https://www.php.net/manual/en/language.oop5.magic.php#object.tostring) method is one of PHP's built-in "magic methods". However, sometimes you may not have control over the `__toString` method of a given class, such as when the class that you are interacting with belongs to a third-party library. +If you attempt to "echo" an object using Blade, the object's `__toString` method will be invoked. The [__toString](https://www.php.net/manual/en/language.oop5.magic.php#object.tostring) method is one of PHP's built-in "magic methods". However, sometimes you may not have control over the `__toString` method of a given class, such as when the class that you are interacting with belongs to a third-party library. In these cases, Blade allows you to register a custom echo handler for that particular type of object. To accomplish this, you should invoke Blade's `stringable` method. The `stringable` method accepts a closure. This closure should type-hint the type of object that it is responsible for rendering. Typically, the `stringable` method should be invoked within the `boot` method of your application's `AppServiceProvider` class: - use Illuminate\Support\Facades\Blade; - use Money\Money; +```php +use Illuminate\Support\Facades\Blade; +use Money\Money; - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - Blade::stringable(function (Money $money) { - return $money->formatTo('en_GB'); - }); - } +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Blade::stringable(function (Money $money) { + return $money->formatTo('en_GB'); + }); +} +``` Once your custom echo handler has been defined, you may simply echo the object in your Blade template: @@ -1680,19 +2009,19 @@ Cost: {{ $money }} Programming a custom directive is sometimes more complex than necessary when defining simple, custom conditional statements. For that reason, Blade provides a `Blade::if` method which allows you to quickly define custom conditional directives using closures. For example, let's define a custom conditional that checks the configured default "disk" for the application. We may do this in the `boot` method of our `AppServiceProvider`: - use Illuminate\Support\Facades\Blade; +```php +use Illuminate\Support\Facades\Blade; - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - Blade::if('disk', function ($value) { - return config('filesystems.default') === $value; - }); - } +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Blade::if('disk', function (string $value) { + return config('filesystems.default') === $value; + }); +} +``` Once the custom conditional has been defined, you can use it within your templates: diff --git a/broadcasting.md b/broadcasting.md index a88db424701..1f22837e395 100644 --- a/broadcasting.md +++ b/broadcasting.md @@ -1,40 +1,43 @@ # Broadcasting - [Introduction](#introduction) +- [Quickstart](#quickstart) - [Server Side Installation](#server-side-installation) - - [Configuration](#configuration) + - [Reverb](#reverb) - [Pusher Channels](#pusher-channels) - [Ably](#ably) - - [Open Source Alternatives](#open-source-alternatives) - [Client Side Installation](#client-side-installation) + - [Reverb](#client-reverb) - [Pusher Channels](#client-pusher-channels) - [Ably](#client-ably) - [Concept Overview](#concept-overview) - - [Using An Example Application](#using-example-application) + - [Using an Example Application](#using-example-application) - [Defining Broadcast Events](#defining-broadcast-events) - [Broadcast Name](#broadcast-name) - [Broadcast Data](#broadcast-data) - [Broadcast Queue](#broadcast-queue) - [Broadcast Conditions](#broadcast-conditions) - - [Broadcasting & Database Transactions](#broadcasting-and-database-transactions) + - [Broadcasting and Database Transactions](#broadcasting-and-database-transactions) - [Authorizing Channels](#authorizing-channels) - - [Defining Authorization Routes](#defining-authorization-routes) - [Defining Authorization Callbacks](#defining-authorization-callbacks) - [Defining Channel Classes](#defining-channel-classes) - [Broadcasting Events](#broadcasting-events) - - [Only To Others](#only-to-others) - - [Customizing The Connection](#customizing-the-connection) + - [Only to Others](#only-to-others) + - [Customizing the Connection](#customizing-the-connection) + - [Anonymous Events](#anonymous-events) + - [Rescuing Broadcasts](#rescuing-broadcasts) - [Receiving Broadcasts](#receiving-broadcasts) - - [Listening For Events](#listening-for-events) - - [Leaving A Channel](#leaving-a-channel) + - [Listening for Events](#listening-for-events) + - [Leaving a Channel](#leaving-a-channel) - [Namespaces](#namespaces) + - [Using React or Vue](#using-react-or-vue) - [Presence Channels](#presence-channels) - [Authorizing Presence Channels](#authorizing-presence-channels) - [Joining Presence Channels](#joining-presence-channels) - - [Broadcasting To Presence Channels](#broadcasting-to-presence-channels) + - [Broadcasting to Presence Channels](#broadcasting-to-presence-channels) - [Model Broadcasting](#model-broadcasting) - [Model Broadcasting Conventions](#model-broadcasting-conventions) - - [Listening For Model Broadcasts](#listening-for-model-broadcasts) + - [Listening for Model Broadcasts](#listening-for-model-broadcasts) - [Client Events](#client-events) - [Notifications](#notifications) @@ -43,7 +46,7 @@ In many modern web applications, WebSockets are used to implement realtime, live-updating user interfaces. When some data is updated on the server, a message is typically sent over a WebSocket connection to be handled by the client. WebSockets provide a more efficient alternative to continually polling your application's server for data changes that should be reflected in your UI. -For example, imagine your application is able to export a user's data to a CSV file and email it to them. However, creating this CSV file takes several minutes so you choose to create and mail the CSV within a [queued job](/docs/{{version}}/queues). When the CSV has been created and mailed to the user, we can use event broadcasting to dispatch a `App\Events\UserDataExported` event that is received by our application's JavaScript. Once the event is received, we can display a message to the user that their CSV has been emailed to them without them ever needing to refresh the page. +For example, imagine your application is able to export a user's data to a CSV file and email it to them. However, creating this CSV file takes several minutes so you choose to create and mail the CSV within a [queued job](/docs/{{version}}/queues). When the CSV has been created and mailed to the user, we can use event broadcasting to dispatch an `App\Events\UserDataExported` event that is received by our application's JavaScript. Once the event is received, we can display a message to the user that their CSV has been emailed to them without them ever needing to refresh the page. To assist you in building these types of features, Laravel makes it easy to "broadcast" your server-side Laravel [events](/docs/{{version}}/events) over a WebSocket connection. Broadcasting your Laravel events allows you to share the same event names and data between your server-side Laravel application and your client-side JavaScript application. @@ -52,9 +55,33 @@ The core concepts behind broadcasting are simple: clients connect to named chann #### Supported Drivers -By default, Laravel includes two server-side broadcasting drivers for you to choose from: [Pusher Channels](https://pusher.com/channels) and [Ably](https://ably.io). However, community driven packages such as [laravel-websockets](https://beyondco.de/docs/laravel-websockets/getting-started/introduction) and [soketi](https://docs.soketi.app/) provide additional broadcasting drivers that do not require commercial broadcasting providers. +By default, Laravel includes three server-side broadcasting drivers for you to choose from: [Laravel Reverb](https://reverb.laravel.com), [Pusher Channels](https://pusher.com/channels), and [Ably](https://ably.com). -> {tip} Before diving into event broadcasting, make sure you have read Laravel's documentation on [events and listeners](/docs/{{version}}/events). +> [!NOTE] +> Before diving into event broadcasting, make sure you have read Laravel's documentation on [events and listeners](/docs/{{version}}/events). + + +## Quickstart + +By default, broadcasting is not enabled in new Laravel applications. You may enable broadcasting using the `install:broadcasting` Artisan command: + +```shell +php artisan install:broadcasting +``` + +The `install:broadcasting` command will prompt you for which event broadcasting service you would like to use. In addition, it will create the `config/broadcasting.php` configuration file and the `routes/channels.php` file where you may register your application's broadcast authorization routes and callbacks. + +Laravel supports several broadcast drivers out of the box: [Laravel Reverb](/docs/{{version}}/reverb), [Pusher Channels](https://pusher.com/channels), [Ably](https://ably.com), and a `log` driver for local development and debugging. Additionally, a `null` driver is included which allows you to disable broadcasting during testing. A configuration example is included for each of these drivers in the `config/broadcasting.php` configuration file. + +All of your application's event broadcasting configuration is stored in the `config/broadcasting.php` configuration file. Don't worry if this file does not exist in your application; it will be created when you run the `install:broadcasting` Artisan command. + + +#### Next Steps + +Once you have enabled event broadcasting, you're ready to learn more about [defining broadcast events](#defining-broadcast-events) and [listening for events](#listening-for-events). If you're using Laravel's React or Vue [starter kits](/docs/{{version}}/starter-kits), you may listen for events using Echo's [useEcho hook](#using-react-or-vue). + +> [!NOTE] +> Before broadcasting any events, you should first configure and run a [queue worker](/docs/{{version}}/queues). All event broadcasting is done via queued jobs so that the response time of your application is not seriously affected by events being broadcast. ## Server Side Installation @@ -63,58 +90,90 @@ To get started using Laravel's event broadcasting, we need to do some configurat Event broadcasting is accomplished by a server-side broadcasting driver that broadcasts your Laravel events so that Laravel Echo (a JavaScript library) can receive them within the browser client. Don't worry - we'll walk through each part of the installation process step-by-step. - -### Configuration + +### Reverb + +To quickly enable support for Laravel's broadcasting features while using Reverb as your event broadcaster, invoke the `install:broadcasting` Artisan command with the `--reverb` option. This Artisan command will install Reverb's required Composer and NPM packages and update your application's `.env` file with the appropriate variables: + +```shell +php artisan install:broadcasting --reverb +``` + + +#### Manual Installation -All of your application's event broadcasting configuration is stored in the `config/broadcasting.php` configuration file. Laravel supports several broadcast drivers out of the box: [Pusher Channels](https://pusher.com/channels), [Redis](/docs/{{version}}/redis), and a `log` driver for local development and debugging. Additionally, a `null` driver is included which allows you to totally disable broadcasting during testing. A configuration example is included for each of these drivers in the `config/broadcasting.php` configuration file. +When running the `install:broadcasting` command, you will be prompted to install [Laravel Reverb](/docs/{{version}}/reverb). Of course, you may also install Reverb manually using the Composer package manager: - -#### Broadcast Service Provider +```shell +composer require laravel/reverb +``` -Before broadcasting any events, you will first need to register the `App\Providers\BroadcastServiceProvider`. In new Laravel applications, you only need to uncomment this provider in the `providers` array of your `config/app.php` configuration file. This `BroadcastServiceProvider` contains the code necessary to register the broadcast authorization routes and callbacks. +Once the package is installed, you may run Reverb's installation command to publish the configuration, add Reverb's required environment variables, and enable event broadcasting in your application: - -#### Queue Configuration +```shell +php artisan reverb:install +``` -You will also need to configure and run a [queue worker](/docs/{{version}}/queues). All event broadcasting is done via queued jobs so that the response time of your application is not seriously affected by events being broadcast. +You can find detailed Reverb installation and usage instructions in the [Reverb documentation](/docs/{{version}}/reverb). ### Pusher Channels -If you plan to broadcast your events using [Pusher Channels](https://pusher.com/channels), you should install the Pusher Channels PHP SDK using the Composer package manager: +To quickly enable support for Laravel's broadcasting features while using Pusher as your event broadcaster, invoke the `install:broadcasting` Artisan command with the `--pusher` option. This Artisan command will prompt you for your Pusher credentials, install the Pusher PHP and JavaScript SDKs, and update your application's `.env` file with the appropriate variables: + +```shell +php artisan install:broadcasting --pusher +``` + + +#### Manual Installation + +To install Pusher support manually, you should install the Pusher Channels PHP SDK using the Composer package manager: ```shell composer require pusher/pusher-php-server ``` -Next, you should configure your Pusher Channels credentials in the `config/broadcasting.php` configuration file. An example Pusher Channels configuration is already included in this file, allowing you to quickly specify your key, secret, and application ID. Typically, these values should be set via the `PUSHER_APP_KEY`, `PUSHER_APP_SECRET`, and `PUSHER_APP_ID` [environment variables](/docs/{{version}}/configuration#environment-configuration): +Next, you should configure your Pusher Channels credentials in the `config/broadcasting.php` configuration file. An example Pusher Channels configuration is already included in this file, allowing you to quickly specify your key, secret, and application ID. Typically, you should configure your Pusher Channels credentials in your application's `.env` file: ```ini -PUSHER_APP_ID=your-pusher-app-id -PUSHER_APP_KEY=your-pusher-key -PUSHER_APP_SECRET=your-pusher-secret -PUSHER_APP_CLUSTER=mt1 +PUSHER_APP_ID="your-pusher-app-id" +PUSHER_APP_KEY="your-pusher-key" +PUSHER_APP_SECRET="your-pusher-secret" +PUSHER_HOST= +PUSHER_PORT=443 +PUSHER_SCHEME="https" +PUSHER_APP_CLUSTER="mt1" ``` The `config/broadcasting.php` file's `pusher` configuration also allows you to specify additional `options` that are supported by Channels, such as the cluster. -Next, you will need to change your broadcast driver to `pusher` in your `.env` file: +Then, set the `BROADCAST_CONNECTION` environment variable to `pusher` in your application's `.env` file: ```ini -BROADCAST_DRIVER=pusher +BROADCAST_CONNECTION=pusher ``` Finally, you are ready to install and configure [Laravel Echo](#client-side-installation), which will receive the broadcast events on the client-side. - -#### Open Source Pusher Alternatives - -The [laravel-websockets](https://github.com/beyondcode/laravel-websockets) and [soketi](https://docs.soketi.app/) packages provide Pusher compatible WebSocket servers for Laravel. These packages allow you to leverage the full power of Laravel broadcasting without a commercial WebSocket provider. For more information on installing and using these packages, please consult our documentation on [open source alternatives](#open-source-alternatives). - ### Ably -If you plan to broadcast your events using [Ably](https://ably.io), you should install the Ably PHP SDK using the Composer package manager: +> [!NOTE] +> The documentation below discusses how to use Ably in "Pusher compatibility" mode. However, the Ably team recommends and maintains a broadcaster and Echo client that is able to take advantage of the unique capabilities offered by Ably. For more information on using the Ably maintained drivers, please [consult Ably's Laravel broadcaster documentation](https://github.com/ably/laravel-broadcaster). + +To quickly enable support for Laravel's broadcasting features while using [Ably](https://ably.com) as your event broadcaster, invoke the `install:broadcasting` Artisan command with the `--ably` option. This Artisan command will prompt you for your Ably credentials, install the Ably PHP and JavaScript SDKs, and update your application's `.env` file with the appropriate variables: + +```shell +php artisan install:broadcasting --ably +``` + +**Before continuing, you should enable Pusher protocol support in your Ably application settings. You may enable this feature within the "Protocol Adapter Settings" portion of your Ably application's settings dashboard.** + + +#### Manual Installation + +To install Ably support manually, you should install the Ably PHP SDK using the Composer package manager: ```shell composer require ably/ably-php @@ -126,85 +185,213 @@ Next, you should configure your Ably credentials in the `config/broadcasting.php ABLY_KEY=your-ably-key ``` -Next, you will need to change your broadcast driver to `ably` in your `.env` file: +Then, set the `BROADCAST_CONNECTION` environment variable to `ably` in your application's `.env` file: ```ini -BROADCAST_DRIVER=ably +BROADCAST_CONNECTION=ably ``` Finally, you are ready to install and configure [Laravel Echo](#client-side-installation), which will receive the broadcast events on the client-side. - -### Open Source Alternatives + +## Client Side Installation + + +### Reverb - -#### PHP +[Laravel Echo](https://github.com/laravel/echo) is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by your server-side broadcasting driver. -The [laravel-websockets](https://github.com/beyondcode/laravel-websockets) package is a pure PHP, Pusher compatible WebSocket package for Laravel. This package allows you to leverage the full power of Laravel broadcasting without a commercial WebSocket provider. For more information on installing and using this package, please consult its [official documentation](https://beyondco.de/docs/laravel-websockets). +When installing Laravel Reverb via the `install:broadcasting` Artisan command, Reverb and Echo's scaffolding and configuration will be injected into your application automatically. However, if you wish to manually configure Laravel Echo, you may do so by following the instructions below. - -#### Node + +#### Manual Installation -[Soketi](https://github.com/soketi/soketi) is a Node based, Pusher compatible WebSocket server for Laravel. Under the hood, Soketi utilizes µWebSockets.js for extreme scalability and speed. This package allows you to leverage the full power of Laravel broadcasting without a commercial WebSocket provider. For more information on installing and using this package, please consult its [official documentation](https://docs.soketi.app/). +To manually configure Laravel Echo for your application's frontend, first install the `pusher-js` package since Reverb utilizes the Pusher protocol for WebSocket subscriptions, channels, and messages: - -## Client Side Installation +```shell +npm install --save-dev laravel-echo pusher-js +``` + +Once Echo is installed, you are ready to create a fresh Echo instance in your application's JavaScript. A great place to do this is at the bottom of the `resources/js/bootstrap.js` file that is included with the Laravel framework: + +```js tab=JavaScript +import Echo from 'laravel-echo'; + +import Pusher from 'pusher-js'; +window.Pusher = Pusher; + +window.Echo = new Echo({ + broadcaster: 'reverb', + key: import.meta.env.VITE_REVERB_APP_KEY, + wsHost: import.meta.env.VITE_REVERB_HOST, + wsPort: import.meta.env.VITE_REVERB_PORT ?? 80, + wssPort: import.meta.env.VITE_REVERB_PORT ?? 443, + forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https', + enabledTransports: ['ws', 'wss'], +}); +``` + +```js tab=React +import { configureEcho } from "@laravel/echo-react"; + +configureEcho({ + broadcaster: "reverb", + // key: import.meta.env.VITE_REVERB_APP_KEY, + // wsHost: import.meta.env.VITE_REVERB_HOST, + // wsPort: import.meta.env.VITE_REVERB_PORT, + // wssPort: import.meta.env.VITE_REVERB_PORT, + // forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https', + // enabledTransports: ['ws', 'wss'], +}); +``` + +```js tab=Vue +import { configureEcho } from "@laravel/echo-vue"; + +configureEcho({ + broadcaster: "reverb", + // key: import.meta.env.VITE_REVERB_APP_KEY, + // wsHost: import.meta.env.VITE_REVERB_HOST, + // wsPort: import.meta.env.VITE_REVERB_PORT, + // wssPort: import.meta.env.VITE_REVERB_PORT, + // forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https', + // enabledTransports: ['ws', 'wss'], +}); +``` + +Next, you should compile your application's assets: + +```shell +npm run build +``` + +> [!WARNING] +> The Laravel Echo `reverb` broadcaster requires laravel-echo v1.16.0+. ### Pusher Channels -[Laravel Echo](https://github.com/laravel/echo) is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by your server-side broadcasting driver. You may install Echo via the NPM package manager. In this example, we will also install the `pusher-js` package since we will be using the Pusher Channels broadcaster: +[Laravel Echo](https://github.com/laravel/echo) is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by your server-side broadcasting driver. + +When installing broadcasting support via the `install:broadcasting --pusher` Artisan command, Pusher and Echo's scaffolding and configuration will be injected into your application automatically. However, if you wish to manually configure Laravel Echo, you may do so by following the instructions below. + + +#### Manual Installation + +To manually configure Laravel Echo for your application's frontend, first install the `laravel-echo` and `pusher-js` packages which utilize the Pusher protocol for WebSocket subscriptions, channels, and messages: ```shell npm install --save-dev laravel-echo pusher-js ``` -Once Echo is installed, you are ready to create a fresh Echo instance in your application's JavaScript. A great place to do this is at the bottom of the `resources/js/bootstrap.js` file that is included with the Laravel framework. By default, an example Echo configuration is already included in this file - you simply need to uncomment it: +Once Echo is installed, you are ready to create a fresh Echo instance in your application's `resources/js/bootstrap.js` file: -```js +```js tab=JavaScript import Echo from 'laravel-echo'; -window.Pusher = require('pusher-js'); +import Pusher from 'pusher-js'; +window.Pusher = Pusher; window.Echo = new Echo({ broadcaster: 'pusher', - key: process.env.MIX_PUSHER_APP_KEY, - cluster: process.env.MIX_PUSHER_APP_CLUSTER, + key: import.meta.env.VITE_PUSHER_APP_KEY, + cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER, forceTLS: true }); ``` -Once you have uncommented and adjusted the Echo configuration according to your needs, you may compile your application's assets: +```js tab=React +import { configureEcho } from "@laravel/echo-react"; + +configureEcho({ + broadcaster: "pusher", + // key: import.meta.env.VITE_PUSHER_APP_KEY, + // cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER, + // forceTLS: true, + // wsHost: import.meta.env.VITE_PUSHER_HOST, + // wsPort: import.meta.env.VITE_PUSHER_PORT, + // wssPort: import.meta.env.VITE_PUSHER_PORT, + // enabledTransports: ["ws", "wss"], +}); +``` + +```js tab=Vue +import { configureEcho } from "@laravel/echo-vue"; + +configureEcho({ + broadcaster: "pusher", + // key: import.meta.env.VITE_PUSHER_APP_KEY, + // cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER, + // forceTLS: true, + // wsHost: import.meta.env.VITE_PUSHER_HOST, + // wsPort: import.meta.env.VITE_PUSHER_PORT, + // wssPort: import.meta.env.VITE_PUSHER_PORT, + // enabledTransports: ["ws", "wss"], +}); +``` + +Next, you should define the appropriate values for the Pusher environment variables in your application's `.env` file. If these variables do not already exist in your `.env` file, you should add them: + +```ini +PUSHER_APP_ID="your-pusher-app-id" +PUSHER_APP_KEY="your-pusher-key" +PUSHER_APP_SECRET="your-pusher-secret" +PUSHER_HOST= +PUSHER_PORT=443 +PUSHER_SCHEME="https" +PUSHER_APP_CLUSTER="mt1" + +VITE_APP_NAME="${APP_NAME}" +VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}" +VITE_PUSHER_HOST="${PUSHER_HOST}" +VITE_PUSHER_PORT="${PUSHER_PORT}" +VITE_PUSHER_SCHEME="${PUSHER_SCHEME}" +VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" +``` + +Once you have adjusted the Echo configuration according to your application's needs, you may compile your application's assets: ```shell -npm run dev +npm run build ``` -> {tip} To learn more about compiling your application's JavaScript assets, please consult the documentation on [Laravel Mix](/docs/{{version}}/mix). +> [!NOTE] +> To learn more about compiling your application's JavaScript assets, please consult the documentation on [Vite](/docs/{{version}}/vite). -#### Using An Existing Client Instance +#### Using an Existing Client Instance If you already have a pre-configured Pusher Channels client instance that you would like Echo to utilize, you may pass it to Echo via the `client` configuration option: ```js import Echo from 'laravel-echo'; +import Pusher from 'pusher-js'; -const client = require('pusher-js'); +const options = { + broadcaster: 'pusher', + key: import.meta.env.VITE_PUSHER_APP_KEY +} window.Echo = new Echo({ - broadcaster: 'pusher', - key: 'your-pusher-channels-key', - client: client + ...options, + client: new Pusher(options.key, options) }); ``` ### Ably -[Laravel Echo](https://github.com/laravel/echo) is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by your server-side broadcasting driver. You may install Echo via the NPM package manager. In this example, we will also install the `pusher-js` package. +> [!NOTE] +> The documentation below discusses how to use Ably in "Pusher compatibility" mode. However, the Ably team recommends and maintains a broadcaster and Echo client that is able to take advantage of the unique capabilities offered by Ably. For more information on using the Ably maintained drivers, please [consult Ably's Laravel broadcaster documentation](https://github.com/ably/laravel-broadcaster). + +[Laravel Echo](https://github.com/laravel/echo) is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by your server-side broadcasting driver. + +When installing broadcasting support via the `install:broadcasting --ably` Artisan command, Ably and Echo's scaffolding and configuration will be injected into your application automatically. However, if you wish to manually configure Laravel Echo, you may do so by following the instructions below. + + +#### Manual Installation -You may wonder why we would install the `pusher-js` JavaScript library even though we are using Ably to broadcast our events. Thankfully, Ably includes a Pusher compatibility mode which lets us use the Pusher protocol when listening for events in our client-side application: +To manually configure Laravel Echo for your application's frontend, first install the `laravel-echo` and `pusher-js` packages which utilize the Pusher protocol for WebSocket subscriptions, channels, and messages: ```shell npm install --save-dev laravel-echo pusher-js @@ -212,16 +399,17 @@ npm install --save-dev laravel-echo pusher-js **Before continuing, you should enable Pusher protocol support in your Ably application settings. You may enable this feature within the "Protocol Adapter Settings" portion of your Ably application's settings dashboard.** -Once Echo is installed, you are ready to create a fresh Echo instance in your application's JavaScript. A great place to do this is at the bottom of the `resources/js/bootstrap.js` file that is included with the Laravel framework. By default, an example Echo configuration is already included in this file; however, the default configuration in the `bootstrap.js` file is intended for Pusher. You may copy the configuration below to transition your configuration to Ably: +Once Echo is installed, you are ready to create a fresh Echo instance in your application's `resources/js/bootstrap.js` file: -```js +```js tab=JavaScript import Echo from 'laravel-echo'; -window.Pusher = require('pusher-js'); +import Pusher from 'pusher-js'; +window.Pusher = Pusher; window.Echo = new Echo({ broadcaster: 'pusher', - key: process.env.MIX_ABLY_PUBLIC_KEY, + key: import.meta.env.VITE_ABLY_PUBLIC_KEY, wsHost: 'realtime-pusher.ably.io', wsPort: 443, disableStats: true, @@ -229,100 +417,172 @@ window.Echo = new Echo({ }); ``` -Note that our Ably Echo configuration references a `MIX_ABLY_PUBLIC_KEY` environment variable. This variable's value should be your Ably public key. Your public key is the portion of your Ably key that occurs before the `:` character. +```js tab=React +import { configureEcho } from "@laravel/echo-react"; + +configureEcho({ + broadcaster: "ably", + // key: import.meta.env.VITE_ABLY_PUBLIC_KEY, + // wsHost: "realtime-pusher.ably.io", + // wsPort: 443, + // disableStats: true, + // encrypted: true, +}); +``` + +```js tab=Vue +import { configureEcho } from "@laravel/echo-vue"; + +configureEcho({ + broadcaster: "ably", + // key: import.meta.env.VITE_ABLY_PUBLIC_KEY, + // wsHost: "realtime-pusher.ably.io", + // wsPort: 443, + // disableStats: true, + // encrypted: true, +}); +``` + +You may have noticed our Ably Echo configuration references a `VITE_ABLY_PUBLIC_KEY` environment variable. This variable's value should be your Ably public key. Your public key is the portion of your Ably key that occurs before the `:` character. -Once you have uncommented and adjusted the Echo configuration according to your needs, you may compile your application's assets: +Once you have adjusted the Echo configuration according to your needs, you may compile your application's assets: ```shell npm run dev ``` -> {tip} To learn more about compiling your application's JavaScript assets, please consult the documentation on [Laravel Mix](/docs/{{version}}/mix). +> [!NOTE] +> To learn more about compiling your application's JavaScript assets, please consult the documentation on [Vite](/docs/{{version}}/vite). ## Concept Overview -Laravel's event broadcasting allows you to broadcast your server-side Laravel events to your client-side JavaScript application using a driver-based approach to WebSockets. Currently, Laravel ships with [Pusher Channels](https://pusher.com/channels) and [Ably](https://ably.io) drivers. The events may be easily consumed on the client-side using the [Laravel Echo](#client-side-installation) JavaScript package. +Laravel's event broadcasting allows you to broadcast your server-side Laravel events to your client-side JavaScript application using a driver-based approach to WebSockets. Currently, Laravel ships with [Laravel Reverb](https://reverb.laravel.com), [Pusher Channels](https://pusher.com/channels), and [Ably](https://ably.com) drivers. The events may be easily consumed on the client-side using the [Laravel Echo](#client-side-installation) JavaScript package. Events are broadcast over "channels", which may be specified as public or private. Any visitor to your application may subscribe to a public channel without any authentication or authorization; however, in order to subscribe to a private channel, a user must be authenticated and authorized to listen on that channel. -> {tip} If you would like to explore open source alternatives to Pusher, check out the [open source alternatives](#open-source-alternatives). - -### Using An Example Application +### Using an Example Application Before diving into each component of event broadcasting, let's take a high level overview using an e-commerce store as an example. -In our application, let's assume we have a page that allows users to view the shipping status for their orders. Let's also assume that a `OrderShipmentStatusUpdated` event is fired when a shipping status update is processed by the application: +In our application, let's assume we have a page that allows users to view the shipping status for their orders. Let's also assume that an `OrderShipmentStatusUpdated` event is fired when a shipping status update is processed by the application: - use App\Events\OrderShipmentStatusUpdated; +```php +use App\Events\OrderShipmentStatusUpdated; - OrderShipmentStatusUpdated::dispatch($order); +OrderShipmentStatusUpdated::dispatch($order); +``` #### The `ShouldBroadcast` Interface When a user is viewing one of their orders, we don't want them to have to refresh the page to view status updates. Instead, we want to broadcast the updates to the application as they are created. So, we need to mark the `OrderShipmentStatusUpdated` event with the `ShouldBroadcast` interface. This will instruct Laravel to broadcast the event when it is fired: - order->id); - } + public $order; +} +``` + +The `ShouldBroadcast` interface requires our event to define a `broadcastOn` method. This method is responsible for returning the channels that the event should broadcast on. An empty stub of this method is already defined on generated event classes, so we only need to fill in its details. We only want the creator of the order to be able to view status updates, so we will broadcast the event on a private channel that is tied to the order: + +```php +use Illuminate\Broadcasting\Channel; +use Illuminate\Broadcasting\PrivateChannel; + +/** + * Get the channel the event should broadcast on. + */ +public function broadcastOn(): Channel +{ + return new PrivateChannel('orders.'.$this->order->id); +} +``` + +If you wish the event to broadcast on multiple channels, you may return an `array` instead: + +```php +use Illuminate\Broadcasting\PrivateChannel; + +/** + * Get the channels the event should broadcast on. + * + * @return array + */ +public function broadcastOn(): array +{ + return [ + new PrivateChannel('orders.'.$this->order->id), + // ... + ]; +} +``` #### Authorizing Channels Remember, users must be authorized to listen on private channels. We may define our channel authorization rules in our application's `routes/channels.php` file. In this example, we need to verify that any user attempting to listen on the private `orders.1` channel is actually the creator of the order: - use App\Models\Order; +```php +use App\Models\Order; +use App\Models\User; - Broadcast::channel('orders.{orderId}', function ($user, $orderId) { - return $user->id === Order::findOrNew($orderId)->user_id; - }); +Broadcast::channel('orders.{orderId}', function (User $user, int $orderId) { + return $user->id === Order::findOrNew($orderId)->user_id; +}); +``` The `channel` method accepts two arguments: the name of the channel and a callback which returns `true` or `false` indicating whether the user is authorized to listen on the channel. All authorization callbacks receive the currently authenticated user as their first argument and any additional wildcard parameters as their subsequent arguments. In this example, we are using the `{orderId}` placeholder to indicate that the "ID" portion of the channel name is a wildcard. -#### Listening For Event Broadcasts +#### Listening for Event Broadcasts -Next, all that remains is to listen for the event in our JavaScript application. We can do this using [Laravel Echo](#client-side-installation). First, we'll use the `private` method to subscribe to the private channel. Then, we may use the `listen` method to listen for the `OrderShipmentStatusUpdated` event. By default, all of the event's public properties will be included on the broadcast event: +Next, all that remains is to listen for the event in our JavaScript application. We can do this using [Laravel Echo](#client-side-installation). Laravel Echo's built-in React and Vue hooks make it simple to get started, and, by default, all of the event's public properties will be included on the broadcast event: -```js -Echo.private(`orders.${orderId}`) - .listen('OrderShipmentStatusUpdated', (e) => { +```js tab=React +import { useEcho } from "@laravel/echo-react"; + +useEcho( + `orders.${orderId}`, + "OrderShipmentStatusUpdated", + (e) => { console.log(e.order); - }); + }, +); +``` + +```vue tab=Vue + ``` @@ -332,50 +592,43 @@ To inform Laravel that a given event should be broadcast, you must implement the The `ShouldBroadcast` interface requires you to implement a single method: `broadcastOn`. The `broadcastOn` method should return a channel or array of channels that the event should broadcast on. The channels should be instances of `Channel`, `PrivateChannel`, or `PresenceChannel`. Instances of `Channel` represent public channels that any user may subscribe to, while `PrivateChannels` and `PresenceChannels` represent private channels that require [channel authorization](#authorizing-channels): - + */ + public function broadcastOn(): array { - use SerializesModels; - - /** - * The user that created the server. - * - * @var \App\Models\User - */ - public $user; - - /** - * Create a new event instance. - * - * @param \App\Models\User $user - * @return void - */ - public function __construct(User $user) - { - $this->user = $user; - } - - /** - * Get the channels the event should broadcast on. - * - * @return Channel|array - */ - public function broadcastOn() - { - return new PrivateChannel('user.'.$this->user->id); - } + return [ + new PrivateChannel('user.'.$this->user->id), + ]; } +} +``` After implementing the `ShouldBroadcast` interface, you only need to [fire the event](/docs/{{version}}/events) as you normally would. Once the event has been fired, a [queued job](/docs/{{version}}/queues) will automatically broadcast the event using your specified broadcast driver. @@ -384,21 +637,23 @@ After implementing the `ShouldBroadcast` interface, you only need to [fire the e By default, Laravel will broadcast the event using the event's class name. However, you may customize the broadcast name by defining a `broadcastAs` method on the event: - /** - * The event's broadcast name. - * - * @return string - */ - public function broadcastAs() - { - return 'server.created'; - } +```php +/** + * The event's broadcast name. + */ +public function broadcastAs(): string +{ + return 'server.created'; +} +``` If you customize the broadcast name using the `broadcastAs` method, you should make sure to register your listener with a leading `.` character. This will instruct Echo to not prepend the application's namespace to the event: - .listen('.server.created', function (e) { - .... - }); +```javascript +.listen('.server.created', function (e) { + // ... +}); +``` ### Broadcast Data @@ -417,186 +672,163 @@ When an event is broadcast, all of its `public` properties are automatically ser However, if you wish to have more fine-grained control over your broadcast payload, you may add a `broadcastWith` method to your event. This method should return the array of data that you wish to broadcast as the event payload: - /** - * Get the data to broadcast. - * - * @return array - */ - public function broadcastWith() - { - return ['id' => $this->user->id]; - } +```php +/** + * Get the data to broadcast. + * + * @return array + */ +public function broadcastWith(): array +{ + return ['id' => $this->user->id]; +} +``` ### Broadcast Queue By default, each broadcast event is placed on the default queue for the default queue connection specified in your `queue.php` configuration file. You may customize the queue connection and name used by the broadcaster by defining `connection` and `queue` properties on your event class: - /** - * The name of the queue connection to use when broadcasting the event. - * - * @var string - */ - public $connection = 'redis'; +```php +/** + * The name of the queue connection to use when broadcasting the event. + * + * @var string + */ +public $connection = 'redis'; - /** - * The name of the queue on which to place the broadcasting job. - * - * @var string - */ - public $queue = 'default'; +/** + * The name of the queue on which to place the broadcasting job. + * + * @var string + */ +public $queue = 'default'; +``` Alternatively, you may customize the queue name by defining a `broadcastQueue` method on your event: - /** - * The name of the queue on which to place the broadcasting job. - * - * @return string - */ - public function broadcastQueue() - { - return 'default'; - } +```php +/** + * The name of the queue on which to place the broadcasting job. + */ +public function broadcastQueue(): string +{ + return 'default'; +} +``` If you would like to broadcast your event using the `sync` queue instead of the default queue driver, you can implement the `ShouldBroadcastNow` interface instead of `ShouldBroadcast`: - ### Broadcast Conditions Sometimes you want to broadcast your event only if a given condition is true. You may define these conditions by adding a `broadcastWhen` method to your event class: - /** - * Determine if this event should broadcast. - * - * @return bool - */ - public function broadcastWhen() - { - return $this->order->value > 100; - } +```php +/** + * Determine if this event should broadcast. + */ +public function broadcastWhen(): bool +{ + return $this->order->value > 100; +} +``` -#### Broadcasting & Database Transactions +#### Broadcasting and Database Transactions When broadcast events are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your event depends on these models, unexpected errors can occur when the job that broadcasts the event is processed. -If your queue connection's `after_commit` configuration option is set to `false`, you may still indicate that a particular broadcast event should be dispatched after all open database transactions have been committed by defining an `$afterCommit` property on the event class: - - {tip} To learn more about working around these issues, please review the documentation regarding [queued jobs and database transactions](/docs/{{version}}/queues#jobs-and-database-transactions). +> [!NOTE] +> To learn more about working around these issues, please review the documentation regarding [queued jobs and database transactions](/docs/{{version}}/queues#jobs-and-database-transactions). ## Authorizing Channels -Private channels require you to authorize that the currently authenticated user can actually listen on the channel. This is accomplished by making an HTTP request to your Laravel application with the channel name and allowing your application to determine if the user can listen on that channel. When using [Laravel Echo](#client-side-installation), the HTTP request to authorize subscriptions to private channels will be made automatically; however, you do need to define the proper routes to respond to these requests. - - -### Defining Authorization Routes +Private channels require you to authorize that the currently authenticated user can actually listen on the channel. This is accomplished by making an HTTP request to your Laravel application with the channel name and allowing your application to determine if the user can listen on that channel. When using [Laravel Echo](#client-side-installation), the HTTP request to authorize subscriptions to private channels will be made automatically. -Thankfully, Laravel makes it easy to define the routes to respond to channel authorization requests. In the `App\Providers\BroadcastServiceProvider` included with your Laravel application, you will see a call to the `Broadcast::routes` method. This method will register the `/broadcasting/auth` route to handle authorization requests: +When broadcasting is enabled, Laravel automatically registers the `/broadcasting/auth` route to handle authorization requests. The `/broadcasting/auth` route is automatically placed within the `web` middleware group. - Broadcast::routes(); - -The `Broadcast::routes` method will automatically place its routes within the `web` middleware group; however, you may pass an array of route attributes to the method if you would like to customize the assigned attributes: - - Broadcast::routes($attributes); + +### Defining Authorization Callbacks - -#### Customizing The Authorization Endpoint +Next, we need to define the logic that will actually determine if the currently authenticated user can listen to a given channel. This is done in the `routes/channels.php` file that was created by the `install:broadcasting` Artisan command. In this file, you may use the `Broadcast::channel` method to register channel authorization callbacks: -By default, Echo will use the `/broadcasting/auth` endpoint to authorize channel access. However, you may specify your own authorization endpoint by passing the `authEndpoint` configuration option to your Echo instance: +```php +use App\Models\User; -```js -window.Echo = new Echo({ - broadcaster: 'pusher', - // ... - authEndpoint: '/custom/endpoint/auth' +Broadcast::channel('orders.{orderId}', function (User $user, int $orderId) { + return $user->id === Order::findOrNew($orderId)->user_id; }); ``` - -#### Customizing The Authorization Request - -You can customize how Laravel Echo performs authorization requests by providing a custom authorizer when initializing Echo: - -```js -window.Echo = new Echo({ - // ... - authorizer: (channel, options) => { - return { - authorize: (socketId, callback) => { - axios.post('/api/broadcasting/auth', { - socket_id: socketId, - channel_name: channel.name - }) - .then(response => { - callback(false, response.data); - }) - .catch(error => { - callback(true, error); - }); - } - }; - }, -}) -``` - - -### Defining Authorization Callbacks - -Next, we need to define the logic that will actually determine if the currently authenticated user can listen to a given channel. This is done in the `routes/channels.php` file that is included with your application. In this file, you may use the `Broadcast::channel` method to register channel authorization callbacks: - - Broadcast::channel('orders.{orderId}', function ($user, $orderId) { - return $user->id === Order::findOrNew($orderId)->user_id; - }); - The `channel` method accepts two arguments: the name of the channel and a callback which returns `true` or `false` indicating whether the user is authorized to listen on the channel. All authorization callbacks receive the currently authenticated user as their first argument and any additional wildcard parameters as their subsequent arguments. In this example, we are using the `{orderId}` placeholder to indicate that the "ID" portion of the channel name is a wildcard. +You may view a list of your application's broadcast authorization callbacks using the `channel:list` Artisan command: + +```shell +php artisan channel:list +``` + #### Authorization Callback Model Binding Just like HTTP routes, channel routes may also take advantage of implicit and explicit [route model binding](/docs/{{version}}/routing#route-model-binding). For example, instead of receiving a string or numeric order ID, you may request an actual `Order` model instance: - use App\Models\Order; +```php +use App\Models\Order; +use App\Models\User; - Broadcast::channel('orders.{order}', function ($user, Order $order) { - return $user->id === $order->user_id; - }); +Broadcast::channel('orders.{order}', function (User $user, Order $order) { + return $user->id === $order->user_id; +}); +``` -> {note} Unlike HTTP route model binding, channel model binding does not support automatic [implicit model binding scoping](/docs/{{version}}/routing#implicit-model-binding-scoping). However, this is rarely a problem because most channels can be scoped based on a single model's unique, primary key. +> [!WARNING] +> Unlike HTTP route model binding, channel model binding does not support automatic [implicit model binding scoping](/docs/{{version}}/routing#implicit-model-binding-scoping). However, this is rarely a problem because most channels can be scoped based on a single model's unique, primary key. #### Authorization Callback Authentication Private and presence broadcast channels authenticate the current user via your application's default authentication guard. If the user is not authenticated, channel authorization is automatically denied and the authorization callback is never executed. However, you may assign multiple, custom guards that should authenticate the incoming request if necessary: - Broadcast::channel('channel', function () { - // ... - }, ['guards' => ['web', 'admin']]); +```php +Broadcast::channel('channel', function () { + // ... +}, ['guards' => ['web', 'admin']]); +``` ### Defining Channel Classes @@ -609,63 +841,63 @@ php artisan make:channel OrderChannel Next, register your channel in your `routes/channels.php` file: - use App\Broadcasting\OrderChannel; +```php +use App\Broadcasting\OrderChannel; - Broadcast::channel('orders.{order}', OrderChannel::class); +Broadcast::channel('orders.{order}', OrderChannel::class); +``` Finally, you may place the authorization logic for your channel in the channel class' `join` method. This `join` method will house the same logic you would have typically placed in your channel authorization closure. You may also take advantage of channel model binding: - id === $order->user_id; - } + return $user->id === $order->user_id; } +} +``` -> {tip} Like many other classes in Laravel, channel classes will automatically be resolved by the [service container](/docs/{{version}}/container). So, you may type-hint any dependencies required by your channel in its constructor. +> [!NOTE] +> Like many other classes in Laravel, channel classes will automatically be resolved by the [service container](/docs/{{version}}/container). So, you may type-hint any dependencies required by your channel in its constructor. ## Broadcasting Events Once you have defined an event and marked it with the `ShouldBroadcast` interface, you only need to fire the event using the event's dispatch method. The event dispatcher will notice that the event is marked with the `ShouldBroadcast` interface and will queue the event for broadcasting: - use App\Events\OrderShipmentStatusUpdated; +```php +use App\Events\OrderShipmentStatusUpdated; - OrderShipmentStatusUpdated::dispatch($order); +OrderShipmentStatusUpdated::dispatch($order); +``` -### Only To Others +### Only to Others When building an application that utilizes event broadcasting, you may occasionally need to broadcast an event to all subscribers to a given channel except for the current user. You may accomplish this using the `broadcast` helper and the `toOthers` method: - use App\Events\OrderShipmentStatusUpdated; +```php +use App\Events\OrderShipmentStatusUpdated; - broadcast(new OrderShipmentStatusUpdated($update))->toOthers(); +broadcast(new OrderShipmentStatusUpdated($update))->toOthers(); +``` To better understand when you may want to use the `toOthers` method, let's imagine a task list application where a user may create a new task by entering a task name. To create a task, your application might make a request to a `/task` URL which broadcasts the task's creation and returns a JSON representation of the new task. When your JavaScript application receives the response from the end-point, it might directly insert the new task into its task list like so: @@ -678,12 +910,13 @@ axios.post('/task', task) However, remember that we also broadcast the task's creation. If your JavaScript application is also listening for this event in order to add tasks to the task list, you will have duplicate tasks in your list: one from the end-point and one from the broadcast. You may solve this by using the `toOthers` method to instruct the broadcaster to not broadcast the event to the current user. -> {note} Your event must use the `Illuminate\Broadcasting\InteractsWithSockets` trait in order to call the `toOthers` method. +> [!WARNING] +> Your event must use the `Illuminate\Broadcasting\InteractsWithSockets` trait in order to call the `toOthers` method. #### Configuration -When you initialize a Laravel Echo instance, a socket ID is assigned to the connection. If you are using a global [Axios](https://github.com/mzabriskie/axios) instance to make HTTP requests from your JavaScript application, the socket ID will automatically be attached to every outgoing request as a `X-Socket-ID` header. Then, when you call the `toOthers` method, Laravel will extract the socket ID from the header and instruct the broadcaster to not broadcast to any connections with that socket ID. +When you initialize a Laravel Echo instance, a socket ID is assigned to the connection. If you are using a global [Axios](https://github.com/axios/axios) instance to make HTTP requests from your JavaScript application, the socket ID will automatically be attached to every outgoing request as an `X-Socket-ID` header. Then, when you call the `toOthers` method, Laravel will extract the socket ID from the header and instruct the broadcaster to not broadcast to any connections with that socket ID. If you are not using a global Axios instance, you will need to manually configure your JavaScript application to send the `X-Socket-ID` header with all outgoing requests. You may retrieve the socket ID using the `Echo.socketId` method: @@ -692,48 +925,130 @@ var socketId = Echo.socketId(); ``` -### Customizing The Connection +### Customizing the Connection If your application interacts with multiple broadcast connections and you want to broadcast an event using a broadcaster other than your default, you may specify which connection to push an event to using the `via` method: - use App\Events\OrderShipmentStatusUpdated; +```php +use App\Events\OrderShipmentStatusUpdated; - broadcast(new OrderShipmentStatusUpdated($update))->via('pusher'); +broadcast(new OrderShipmentStatusUpdated($update))->via('pusher'); +``` Alternatively, you may specify the event's broadcast connection by calling the `broadcastVia` method within the event's constructor. However, before doing so, you should ensure that the event class uses the `InteractsWithBroadcasting` trait: - broadcastVia('pusher'); - } + $this->broadcastVia('pusher'); } +} +``` + + +### Anonymous Events + +Sometimes, you may want to broadcast a simple event to your application's frontend without creating a dedicated event class. To accommodate this, the `Broadcast` facade allows you to broadcast "anonymous events": + +```php +Broadcast::on('orders.'.$order->id)->send(); +``` + +The example above will broadcast the following event: + +```json +{ + "event": "AnonymousEvent", + "data": "[]", + "channel": "orders.1" +} +``` + +Using the `as` and `with` methods, you may customize the event's name and data: + +```php +Broadcast::on('orders.'.$order->id) + ->as('OrderPlaced') + ->with($order) + ->send(); +``` + +The example above will broadcast an event like the following: + +```json +{ + "event": "OrderPlaced", + "data": "{ id: 1, total: 100 }", + "channel": "orders.1" +} +``` + +If you would like to broadcast the anonymous event on a private or presence channel, you may utilize the `private` and `presence` methods: + +```php +Broadcast::private('orders.'.$order->id)->send(); +Broadcast::presence('channels.'.$channel->id)->send(); +``` + +Broadcasting an anonymous event using the `send` method dispatches the event to your application's [queue](/docs/{{version}}/queues) for processing. However, if you would like to broadcast the event immediately, you may use the `sendNow` method: + +```php +Broadcast::on('orders.'.$order->id)->sendNow(); +``` + +To broadcast the event to all channel subscribers except the currently authenticated user, you can invoke the `toOthers` method: + +```php +Broadcast::on('orders.'.$order->id) + ->toOthers() + ->send(); +``` + + +### Rescuing Broadcasts + +When your application's queue server is unavailable or Laravel encounters an error while broadcasting an event, an exception is thrown that typically causes the end user to see an application error. Since event broadcasting is often supplementary to your application's core functionality, you can prevent these exceptions from disrupting the user experience by implementing the `ShouldRescue` interface on your events. + +Events that implement the `ShouldRescue` interface automatically utilize Laravel's [rescue helper function](/docs/{{version}}/helpers#method-rescue) during broadcast attempts. This helper catches any exceptions, reports them to your application's exception handler for logging, and allows the application to continue executing normally without interrupting the user's workflow: + +```php + ## Receiving Broadcasts -### Listening For Events +### Listening for Events Once you have [installed and instantiated Laravel Echo](#client-side-installation), you are ready to start listening for events that are broadcast from your Laravel application. First, use the `channel` method to retrieve an instance of a channel, then call the `listen` method to listen for a specified event: @@ -748,23 +1063,23 @@ If you would like to listen for events on a private channel, use the `private` m ```js Echo.private(`orders.${this.order.id}`) - .listen(...) - .listen(...) - .listen(...); + .listen(/* ... */) + .listen(/* ... */) + .listen(/* ... */); ``` -#### Stop Listening For Events +#### Stop Listening for Events If you would like to stop listening to a given event without [leaving the channel](#leaving-a-channel), you may use the `stopListening` method: ```js Echo.private(`orders.${this.order.id}`) - .stopListening('OrderShipmentStatusUpdated') + .stopListening('OrderShipmentStatusUpdated'); ``` -### Leaving A Channel +### Leaving a Channel To leave a channel, you may call the `leaveChannel` method on your Echo instance: @@ -795,10 +1110,171 @@ Alternatively, you may prefix event classes with a `.` when subscribing to them ```js Echo.channel('orders') .listen('.Namespace\\Event\\Class', (e) => { - // + // ... }); ``` + +### Using React or Vue + +Laravel Echo includes React and Vue hooks that make it painless to listen for events. To get started, invoke the `useEcho` hook, which is used to listen for private events. The `useEcho` hook will automatically leave channels when the consuming component is unmounted: + +```js tab=React +import { useEcho } from "@laravel/echo-react"; + +useEcho( + `orders.${orderId}`, + "OrderShipmentStatusUpdated", + (e) => { + console.log(e.order); + }, +); +``` + +```vue tab=Vue + +``` + +You may listen to multiple events by providing an array of events to `useEcho`: + +```js +useEcho( + `orders.${orderId}`, + ["OrderShipmentStatusUpdated", "OrderShipped"], + (e) => { + console.log(e.order); + }, +); +``` + +You may also specify the shape of the broadcast event payload data, providing greater type safety and editing convenience: + +```ts +type OrderData = { + order: { + id: number; + user: { + id: number; + name: string; + }; + created_at: string; + }; +}; + +useEcho(`orders.${orderId}`, "OrderShipmentStatusUpdated", (e) => { + console.log(e.order.id); + console.log(e.order.user.id); +}); +``` + +The `useEcho` hook will automatically leave channels when the consuming component is unmounted; however, you may utilize the returned functions to manually stop / start listening to channels programmatically when necessary: + +```js tab=React +import { useEcho } from "@laravel/echo-react"; + +const { leaveChannel, leave, stopListening, listen } = useEcho( + `orders.${orderId}`, + "OrderShipmentStatusUpdated", + (e) => { + console.log(e.order); + }, +); + +// Stop listening without leaving channel... +stopListening(); + +// Start listening again... +listen(); + +// Leave channel... +leaveChannel(); + +// Leave a channel and also its associated private and presence channels... +leave(); +``` + +```vue tab=Vue + +``` + + +#### Connecting to Public Channels + +To connect to a public channel, you may use the `useEchoPublic` hook: + +```js tab=React +import { useEchoPublic } from "@laravel/echo-react"; + +useEchoPublic("posts", "PostPublished", (e) => { + console.log(e.post); +}); +``` + +```vue tab=Vue + +``` + + +#### Connecting to Presence Channels + +To connect to a presence channel, you may use the `useEchoPresence` hook: + +```js tab=React +import { useEchoPresence } from "@laravel/echo-react"; + +useEchoPresence("posts", "PostPublished", (e) => { + console.log(e.post); +}); +``` + +```vue tab=Vue + +``` + ## Presence Channels @@ -811,11 +1287,15 @@ All presence channels are also private channels; therefore, users must be [autho The data returned by the authorization callback will be made available to the presence channel event listeners in your JavaScript application. If the user is not authorized to join the presence channel, you should return `false` or `null`: - Broadcast::channel('chat.{roomId}', function ($user, $roomId) { - if ($user->canJoinRoom($roomId)) { - return ['id' => $user->id, 'name' => $user->name]; - } - }); +```php +use App\Models\User; + +Broadcast::channel('chat.{roomId}', function (User $user, int $roomId) { + if ($user->canJoinRoom($roomId)) { + return ['id' => $user->id, 'name' => $user->name]; + } +}); +``` ### Joining Presence Channels @@ -825,7 +1305,7 @@ To join a presence channel, you may use Echo's `join` method. The `join` method ```js Echo.join(`chat.${roomId}`) .here((users) => { - // + // ... }) .joining((user) => { console.log(user.name); @@ -838,61 +1318,70 @@ Echo.join(`chat.${roomId}`) }); ``` -The `here` callback will be executed immediately once the channel is joined successfully, and will receive an array containing the user information for all of the other users currently subscribed to the channel. The `joining` method will be executed when a new user joins a channel, while the `leaving` method will be executed when a user leaves the channel. The `error` method will be executed when the authentication endpoint returns a HTTP status code other than 200 or if there is a problem parsing the returned JSON. +The `here` callback will be executed immediately once the channel is joined successfully, and will receive an array containing the user information for all of the other users currently subscribed to the channel. The `joining` method will be executed when a new user joins a channel, while the `leaving` method will be executed when a user leaves the channel. The `error` method will be executed when the authentication endpoint returns an HTTP status code other than 200 or if there is a problem parsing the returned JSON. -### Broadcasting To Presence Channels +### Broadcasting to Presence Channels Presence channels may receive events just like public or private channels. Using the example of a chatroom, we may want to broadcast `NewMessage` events to the room's presence channel. To do so, we'll return an instance of `PresenceChannel` from the event's `broadcastOn` method: - /** - * Get the channels the event should broadcast on. - * - * @return Channel|array - */ - public function broadcastOn() - { - return new PresenceChannel('room.'.$this->message->room_id); - } +```php +/** + * Get the channels the event should broadcast on. + * + * @return array + */ +public function broadcastOn(): array +{ + return [ + new PresenceChannel('chat.'.$this->message->room_id), + ]; +} +``` As with other events, you may use the `broadcast` helper and the `toOthers` method to exclude the current user from receiving the broadcast: - broadcast(new NewMessage($message)); +```php +broadcast(new NewMessage($message)); - broadcast(new NewMessage($message))->toOthers(); +broadcast(new NewMessage($message))->toOthers(); +``` As typical of other types of events, you may listen for events sent to presence channels using Echo's `listen` method: ```js Echo.join(`chat.${roomId}`) - .here(...) - .joining(...) - .leaving(...) + .here(/* ... */) + .joining(/* ... */) + .leaving(/* ... */) .listen('NewMessage', (e) => { - // + // ... }); ``` ## Model Broadcasting -> {note} Before reading the following documentation about model broadcasting, we recommend you become familiar with the general concepts of Laravel's model broadcasting services as well as how to manually create and listen to broadcast events. +> [!WARNING] +> Before reading the following documentation about model broadcasting, we recommend you become familiar with the general concepts of Laravel's model broadcasting services as well as how to manually create and listen to broadcast events. It is common to broadcast events when your application's [Eloquent models](/docs/{{version}}/eloquent) are created, updated, or deleted. Of course, this can easily be accomplished by manually [defining custom events for Eloquent model state changes](/docs/{{version}}/eloquent#events) and marking those events with the `ShouldBroadcast` interface. However, if you are not using these events for any other purposes in your application, it can be cumbersome to create event classes for the sole purpose of broadcasting them. To remedy this, Laravel allows you to indicate that an Eloquent model should automatically broadcast its state changes. -To get started, your Eloquent model should use the `Illuminate\Database\Eloquent\BroadcastsEvents` trait. In addition, the model should define a `broadcastsOn` method, which will return an array of channels that the model's events should broadcast on: +To get started, your Eloquent model should use the `Illuminate\Database\Eloquent\BroadcastsEvents` trait. In addition, the model should define a `broadcastOn` method, which will return an array of channels that the model's events should broadcast on: ```php belongsTo(User::class); } @@ -909,10 +1398,9 @@ class Post extends Model /** * Get the channels that model events should broadcast on. * - * @param string $event - * @return \Illuminate\Broadcasting\Channel|array + * @return array */ - public function broadcastOn($event) + public function broadcastOn(string $event): array { return [$this, $this->user]; } @@ -927,10 +1415,9 @@ In addition, you may have noticed that the `broadcastOn` method receives a strin /** * Get the channels that model events should broadcast on. * - * @param string $event - * @return \Illuminate\Broadcasting\Channel|array + * @return array> */ -public function broadcastOn($event) +public function broadcastOn(string $event): array { return match ($event) { 'deleted' => [], @@ -949,11 +1436,8 @@ use Illuminate\Database\Eloquent\BroadcastableModelEventOccurred; /** * Create a new broadcastable model event for the model. - * - * @param string $event - * @return \Illuminate\Database\Eloquent\BroadcastableModelEventOccurred */ -protected function newBroadcastableEvent($event) +protected function newBroadcastableEvent(string $event): BroadcastableModelEventOccurred { return (new BroadcastableModelEventOccurred( $this, $event @@ -969,7 +1453,7 @@ protected function newBroadcastableEvent($event) As you may have noticed, the `broadcastOn` method in the model example above did not return `Channel` instances. Instead, Eloquent models were returned directly. If an Eloquent model instance is returned by your model's `broadcastOn` method (or is contained in an array returned by the method), Laravel will automatically instantiate a private channel instance for the model using the model's class name and primary key identifier as the channel name. -So, an `App\Models\User` model with an `id` of `1` would be converted into a `Illuminate\Broadcasting\PrivateChannel` instance with a name of `App.Models.User.1`. Of course, in addition to returning Eloquent model instances from your model's `broadcastOn` method, you may return complete `Channel` instances in order to have full control over the model's channel names: +So, an `App\Models\User` model with an `id` of `1` would be converted into an `Illuminate\Broadcasting\PrivateChannel` instance with a name of `App.Models.User.1`. Of course, in addition to returning Eloquent model instances from your model's `broadcastOn` method, you may return complete `Channel` instances in order to have full control over the model's channel names: ```php use Illuminate\Broadcasting\PrivateChannel; @@ -977,12 +1461,13 @@ use Illuminate\Broadcasting\PrivateChannel; /** * Get the channels that model events should broadcast on. * - * @param string $event - * @return \Illuminate\Broadcasting\Channel|array + * @return array */ -public function broadcastOn($event) +public function broadcastOn(string $event): array { - return [new PrivateChannel('user.'.$this->id)]; + return [ + new PrivateChannel('user.'.$this->id) + ]; } ``` @@ -992,10 +1477,10 @@ If you plan to explicitly return a channel instance from your model's `broadcast return [new Channel($this->user)]; ``` -If you need to determine the channel name of a model, you may call the `broadcastChannel` method on any model instance. For example, this method returns the string `App.Models.User.1` for a `App\Models\User` model with an `id` of `1`: +If you need to determine the channel name of a model, you may call the `broadcastChannel` method on any model instance. For example, this method returns the string `App.Models.User.1` for an `App\Models\User` model with an `id` of `1`: ```php -$user->broadcastChannel() +$user->broadcastChannel(); ``` @@ -1013,7 +1498,7 @@ So, for example, an update to the `App\Models\Post` model would broadcast an eve ... }, ... - "socket": "someSocketId", + "socket": "someSocketId" } ``` @@ -1024,11 +1509,8 @@ If you would like, you may define a custom broadcast name and payload by adding ```php /** * The model event's broadcast name. - * - * @param string $event - * @return string|null */ -public function broadcastAs($event) +public function broadcastAs(string $event): string|null { return match ($event) { 'created' => 'post.created', @@ -1039,10 +1521,9 @@ public function broadcastAs($event) /** * Get the data to broadcast for the model. * - * @param string $event - * @return array + * @return array */ -public function broadcastWith($event) +public function broadcastWith(string $event): array { return match ($event) { 'created' => ['title' => $this->title], @@ -1052,7 +1533,7 @@ public function broadcastWith($event) ``` -### Listening For Model Broadcasts +### Listening for Model Broadcasts Once you have added the `BroadcastsEvents` trait to your model and defined your model's `broadcastOn` method, you are ready to start listening for broadcasted model events within your client-side application. Before getting started, you may wish to consult the complete documentation on [listening for events](#listening-for-events). @@ -1062,36 +1543,123 @@ Once you have obtained a channel instance, you may use the `listen` method to li ```js Echo.private(`App.Models.User.${this.user.id}`) - .listen('.PostUpdated', (e) => { + .listen('.UserUpdated', (e) => { console.log(e.model); }); ``` + +#### Using React or Vue + +If you are using React or Vue, you may use Laravel Echo's included `useEchoModel` hook to easily listen for model broadcasts: + +```js tab=React +import { useEchoModel } from "@laravel/echo-react"; + +useEchoModel("App.Models.User", userId, ["UserUpdated"], (e) => { + console.log(e.model); +}); +``` + +```vue tab=Vue + +``` + +You may also specify the shape of the model event payload data, providing greater type safety and editing convenience: + +```ts +type User = { + id: number; + name: string; + email: string; +}; + +useEchoModel("App.Models.User", userId, ["UserUpdated"], (e) => { + console.log(e.model.id); + console.log(e.model.name); +}); +``` + ## Client Events -> {tip} When using [Pusher Channels](https://pusher.com/channels), you must enable the "Client Events" option in the "App Settings" section of your [application dashboard](https://dashboard.pusher.com/) in order to send client events. +> [!NOTE] +> When using [Pusher Channels](https://pusher.com/channels), you must enable the "Client Events" option in the "App Settings" section of your [application dashboard](https://dashboard.pusher.com/) in order to send client events. Sometimes you may wish to broadcast an event to other connected clients without hitting your Laravel application at all. This can be particularly useful for things like "typing" notifications, where you want to alert users of your application that another user is typing a message on a given screen. To broadcast client events, you may use Echo's `whisper` method: -```js +```js tab=JavaScript Echo.private(`chat.${roomId}`) .whisper('typing', { name: this.user.name }); ``` +```js tab=React +import { useEcho } from "@laravel/echo-react"; + +const { channel } = useEcho(`chat.${roomId}`, ['update'], (e) => { + console.log('Chat event received:', e); +}); + +channel().whisper('typing', { name: user.name }); +``` + +```vue tab=Vue + +``` + To listen for client events, you may use the `listenForWhisper` method: -```js +```js tab=JavaScript Echo.private(`chat.${roomId}`) .listenForWhisper('typing', (e) => { console.log(e.name); }); ``` +```js tab=React +import { useEcho } from "@laravel/echo-react"; + +const { channel } = useEcho(`chat.${roomId}`, ['update'], (e) => { + console.log('Chat event received:', e); +}); + +channel().listenForWhisper('typing', (e) => { + console.log(e.name); +}); +``` + +```vue tab=Vue + +``` + ## Notifications @@ -1099,11 +1667,52 @@ By pairing event broadcasting with [notifications](/docs/{{version}}/notificatio Once you have configured a notification to use the broadcast channel, you may listen for the broadcast events using Echo's `notification` method. Remember, the channel name should match the class name of the entity receiving the notifications: -```js +```js tab=JavaScript Echo.private(`App.Models.User.${userId}`) .notification((notification) => { console.log(notification.type); }); ``` -In this example, all notifications sent to `App\Models\User` instances via the `broadcast` channel would be received by the callback. A channel authorization callback for the `App.Models.User.{id}` channel is included in the default `BroadcastServiceProvider` that ships with the Laravel framework. +```js tab=React +import { useEchoModel } from "@laravel/echo-react"; + +const { channel } = useEchoModel('App.Models.User', userId); + +channel().notification((notification) => { + console.log(notification.type); +}); +``` + +```vue tab=Vue + +``` + +In this example, all notifications sent to `App\Models\User` instances via the `broadcast` channel would be received by the callback. A channel authorization callback for the `App.Models.User.{id}` channel is included in your application's `routes/channels.php` file. + + +#### Stop Listening for Notifications + +If you would like to stop listening to notifications without [leaving the channel](#leaving-a-channel), you may use the `stopListeningForNotification` method: + +```js +const callback = (notification) => { + console.log(notification.type); +} + +// Start listening... +Echo.private(`App.Models.User.${userId}`) + .notification(callback); + +// Stop listening (callback must be the same)... +Echo.private(`App.Models.User.${userId}`) + .stopListeningForNotification(callback); +``` diff --git a/cache.md b/cache.md index 6848361b9f6..c6de8be83c3 100644 --- a/cache.md +++ b/cache.md @@ -4,22 +4,20 @@ - [Configuration](#configuration) - [Driver Prerequisites](#driver-prerequisites) - [Cache Usage](#cache-usage) - - [Obtaining A Cache Instance](#obtaining-a-cache-instance) - - [Retrieving Items From The Cache](#retrieving-items-from-the-cache) - - [Storing Items In The Cache](#storing-items-in-the-cache) - - [Removing Items From The Cache](#removing-items-from-the-cache) + - [Obtaining a Cache Instance](#obtaining-a-cache-instance) + - [Retrieving Items From the Cache](#retrieving-items-from-the-cache) + - [Storing Items in the Cache](#storing-items-in-the-cache) + - [Removing Items From the Cache](#removing-items-from-the-cache) + - [Cache Memoization](#cache-memoization) - [The Cache Helper](#the-cache-helper) - [Cache Tags](#cache-tags) - - [Storing Tagged Cache Items](#storing-tagged-cache-items) - - [Accessing Tagged Cache Items](#accessing-tagged-cache-items) - - [Removing Tagged Cache Items](#removing-tagged-cache-items) - [Atomic Locks](#atomic-locks) - - [Driver Prerequisites](#lock-driver-prerequisites) - [Managing Locks](#managing-locks) - [Managing Locks Across Processes](#managing-locks-across-processes) +- [Cache Failover](#cache-failover) - [Adding Custom Cache Drivers](#adding-custom-cache-drivers) - - [Writing The Driver](#writing-the-driver) - - [Registering The Driver](#registering-the-driver) + - [Writing the Driver](#writing-the-driver) + - [Registering the Driver](#registering-the-driver) - [Events](#events) @@ -32,9 +30,9 @@ Thankfully, Laravel provides an expressive, unified API for various cache backen ## Configuration -Your application's cache configuration file is located at `config/cache.php`. In this file, you may specify which cache driver you would like to be used by default throughout your application. Laravel supports popular caching backends like [Memcached](https://memcached.org), [Redis](https://redis.io), [DynamoDB](https://aws.amazon.com/dynamodb), and relational databases out of the box. In addition, a file based cache driver is available, while `array` and "null" cache drivers provide convenient cache backends for your automated tests. +Your application's cache configuration file is located at `config/cache.php`. In this file, you may specify which cache store you would like to be used by default throughout your application. Laravel supports popular caching backends like [Memcached](https://memcached.org), [Redis](https://redis.io), [DynamoDB](https://aws.amazon.com/dynamodb), and relational databases out of the box. In addition, a file based cache driver is available, while `array` and `null` cache drivers provide convenient cache backends for your automated tests. -The cache configuration file also contains various other options, which are documented within the file, so make sure to read over these options. By default, Laravel is configured to use the `file` cache driver, which stores the serialized, cached objects on the server's filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver. +The cache configuration file also contains a variety of other options that you may review. By default, Laravel is configured to use the `database` cache driver, which stores the serialized, cached objects in your application's database. ### Driver Prerequisites @@ -42,317 +40,466 @@ The cache configuration file also contains various other options, which are docu #### Database -When using the `database` cache driver, you will need to setup a table to contain the cache items. You'll find an example `Schema` declaration for the table below: +When using the `database` cache driver, you will need a database table to contain the cache data. Typically, this is included in Laravel's default `0001_01_01_000001_create_cache_table.php` [database migration](/docs/{{version}}/migrations); however, if your application does not contain this migration, you may use the `make:cache-table` Artisan command to create it: - Schema::create('cache', function ($table) { - $table->string('key')->unique(); - $table->text('value'); - $table->integer('expiration'); - }); +```shell +php artisan make:cache-table -> {tip} You may also use the `php artisan cache:table` Artisan command to generate a migration with the proper schema. +php artisan migrate +``` #### Memcached Using the Memcached driver requires the [Memcached PECL package](https://pecl.php.net/package/memcached) to be installed. You may list all of your Memcached servers in the `config/cache.php` configuration file. This file already contains a `memcached.servers` entry to get you started: - 'memcached' => [ - 'servers' => [ - [ - 'host' => env('MEMCACHED_HOST', '127.0.0.1'), - 'port' => env('MEMCACHED_PORT', 11211), - 'weight' => 100, - ], +```php +'memcached' => [ + // ... + + 'servers' => [ + [ + 'host' => env('MEMCACHED_HOST', '127.0.0.1'), + 'port' => env('MEMCACHED_PORT', 11211), + 'weight' => 100, ], ], +], +``` If needed, you may set the `host` option to a UNIX socket path. If you do this, the `port` option should be set to `0`: - 'memcached' => [ +```php +'memcached' => [ + // ... + + 'servers' => [ [ 'host' => '/var/run/memcached/memcached.sock', 'port' => 0, 'weight' => 100 ], ], +], +``` #### Redis -Before using a Redis cache with Laravel, you will need to either install the PhpRedis PHP extension via PECL or install the `predis/predis` package (~1.0) via Composer. [Laravel Sail](/docs/{{version}}/sail) already includes this extension. In addition, official Laravel deployment platforms such as [Laravel Forge](https://forge.laravel.com) and [Laravel Vapor](https://vapor.laravel.com) have the PhpRedis extension installed by default. +Before using a Redis cache with Laravel, you will need to either install the PhpRedis PHP extension via PECL or install the `predis/predis` package (~2.0) via Composer. [Laravel Sail](/docs/{{version}}/sail) already includes this extension. In addition, official Laravel application platforms such as [Laravel Cloud](https://cloud.laravel.com) and [Laravel Forge](https://forge.laravel.com) have the PhpRedis extension installed by default. For more information on configuring Redis, consult its [Laravel documentation page](/docs/{{version}}/redis#configuration). #### DynamoDB -Before using the [DynamoDB](https://aws.amazon.com/dynamodb) cache driver, you must create a DynamoDB table to store all of the cached data. Typically, this table should be named `cache`. However, you should name the table based on the value of the `stores.dynamodb.table` configuration value within your application's `cache` configuration file. +Before using the [DynamoDB](https://aws.amazon.com/dynamodb) cache driver, you must create a DynamoDB table to store all of the cached data. Typically, this table should be named `cache`. However, you should name the table based on the value of the `stores.dynamodb.table` configuration value within the `cache` configuration file. The table name may also be set via the `DYNAMODB_CACHE_TABLE` environment variable. This table should also have a string partition key with a name that corresponds to the value of the `stores.dynamodb.attributes.key` configuration item within your application's `cache` configuration file. By default, the partition key should be named `key`. +Typically, DynamoDB will not proactively remove expired items from a table. Therefore, you should [enable Time to Live (TTL)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html) on the table. When configuring the table's TTL settings, you should set the TTL attribute name to `expires_at`. + +Next, install the AWS SDK so that your Laravel application can communicate with DynamoDB: + +```shell +composer require aws/aws-sdk-php +``` + +In addition, you should ensure that values are provided for the DynamoDB cache store configuration options. Typically these options, such as `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, should be defined in your application's `.env` configuration file: + +```php +'dynamodb' => [ + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'endpoint' => env('DYNAMODB_ENDPOINT'), +], +``` + + +#### MongoDB + +If you are using MongoDB, a `mongodb` cache driver is provided by the official `mongodb/laravel-mongodb` package and can be configured using a `mongodb` database connection. MongoDB supports TTL indexes, which can be used to automatically clear expired cache items. + +For more information on configuring MongoDB, please refer to the MongoDB [Cache and Locks documentation](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/cache/). + ## Cache Usage -### Obtaining A Cache Instance +### Obtaining a Cache Instance To obtain a cache store instance, you may use the `Cache` facade, which is what we will use throughout this documentation. The `Cache` facade provides convenient, terse access to the underlying implementations of the Laravel cache contracts: - #### Accessing Multiple Cache Stores Using the `Cache` facade, you may access various cache stores via the `store` method. The key passed to the `store` method should correspond to one of the stores listed in the `stores` configuration array in your `cache` configuration file: - $value = Cache::store('file')->get('foo'); +```php +$value = Cache::store('file')->get('foo'); - Cache::store('redis')->put('bar', 'baz', 600); // 10 Minutes +Cache::store('redis')->put('bar', 'baz', 600); // 10 Minutes +``` -### Retrieving Items From The Cache +### Retrieving Items From the Cache The `Cache` facade's `get` method is used to retrieve items from the cache. If the item does not exist in the cache, `null` will be returned. If you wish, you may pass a second argument to the `get` method specifying the default value you wish to be returned if the item doesn't exist: - $value = Cache::get('key'); +```php +$value = Cache::get('key'); - $value = Cache::get('key', 'default'); +$value = Cache::get('key', 'default'); +``` You may even pass a closure as the default value. The result of the closure will be returned if the specified item does not exist in the cache. Passing a closure allows you to defer the retrieval of default values from a database or other external service: - $value = Cache::get('key', function () { - return DB::table(...)->get(); - }); +```php +$value = Cache::get('key', function () { + return DB::table(/* ... */)->get(); +}); +``` - -#### Checking For Item Existence + +#### Determining Item Existence The `has` method may be used to determine if an item exists in the cache. This method will also return `false` if the item exists but its value is `null`: - if (Cache::has('key')) { - // - } +```php +if (Cache::has('key')) { + // ... +} +``` #### Incrementing / Decrementing Values The `increment` and `decrement` methods may be used to adjust the value of integer items in the cache. Both of these methods accept an optional second argument indicating the amount by which to increment or decrement the item's value: - Cache::increment('key'); - Cache::increment('key', $amount); - Cache::decrement('key'); - Cache::decrement('key', $amount); +```php +// Initialize the value if it does not exist... +Cache::add('key', 0, now()->addHours(4)); + +// Increment or decrement the value... +Cache::increment('key'); +Cache::increment('key', $amount); +Cache::decrement('key'); +Cache::decrement('key', $amount); +``` -#### Retrieve & Store +#### Retrieve and Store Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn't exist. For example, you may wish to retrieve all users from the cache or, if they don't exist, retrieve them from the database and add them to the cache. You may do this using the `Cache::remember` method: - $value = Cache::remember('users', $seconds, function () { - return DB::table('users')->get(); - }); +```php +$value = Cache::remember('users', $seconds, function () { + return DB::table('users')->get(); +}); +``` If the item does not exist in the cache, the closure passed to the `remember` method will be executed and its result will be placed in the cache. You may use the `rememberForever` method to retrieve an item from the cache or store it forever if it does not exist: - $value = Cache::rememberForever('users', function () { - return DB::table('users')->get(); - }); +```php +$value = Cache::rememberForever('users', function () { + return DB::table('users')->get(); +}); +``` + + +#### Stale While Revalidate + +When using the `Cache::remember` method, some users may experience slow response times if the cached value has expired. For certain types of data, it can be useful to allow partially stale data to be served while the cached value is recalculated in the background, preventing some users from experiencing slow response times while cached values are calculated. This is often referred to as the "stale-while-revalidate" pattern, and the `Cache::flexible` method provides an implementation of this pattern. + +The flexible method accepts an array that specifies how long the cached value is considered "fresh" and when it becomes "stale". The first value in the array represents the number of seconds the cache is considered fresh, while the second value defines how long it can be served as stale data before recalculation is necessary. + +If a request is made within the fresh period (before the first value), the cache is returned immediately without recalculation. If a request is made during the stale period (between the two values), the stale value is served to the user, and a [deferred function](/docs/{{version}}/helpers#deferred-functions) is registered to refresh the cached value after the response is sent to the user. If a request is made after the second value, the cache is considered expired, and the value is recalculated immediately, which may result in a slower response for the user: + +```php +$value = Cache::flexible('users', [5, 10], function () { + return DB::table('users')->get(); +}); +``` -#### Retrieve & Delete +#### Retrieve and Delete If you need to retrieve an item from the cache and then delete the item, you may use the `pull` method. Like the `get` method, `null` will be returned if the item does not exist in the cache: - $value = Cache::pull('key'); +```php +$value = Cache::pull('key'); + +$value = Cache::pull('key', 'default'); +``` -### Storing Items In The Cache +### Storing Items in the Cache You may use the `put` method on the `Cache` facade to store items in the cache: - Cache::put('key', 'value', $seconds = 10); +```php +Cache::put('key', 'value', $seconds = 10); +``` If the storage time is not passed to the `put` method, the item will be stored indefinitely: - Cache::put('key', 'value'); +```php +Cache::put('key', 'value'); +``` Instead of passing the number of seconds as an integer, you may also pass a `DateTime` instance representing the desired expiration time of the cached item: - Cache::put('key', 'value', now()->addMinutes(10)); +```php +Cache::put('key', 'value', now()->addMinutes(10)); +``` -#### Store If Not Present +#### Store if Not Present The `add` method will only add the item to the cache if it does not already exist in the cache store. The method will return `true` if the item is actually added to the cache. Otherwise, the method will return `false`. The `add` method is an atomic operation: - Cache::add('key', 'value', $seconds); +```php +Cache::add('key', 'value', $seconds); +``` #### Storing Items Forever The `forever` method may be used to store an item in the cache permanently. Since these items will not expire, they must be manually removed from the cache using the `forget` method: - Cache::forever('key', 'value'); +```php +Cache::forever('key', 'value'); +``` -> {tip} If you are using the Memcached driver, items that are stored "forever" may be removed when the cache reaches its size limit. +> [!NOTE] +> If you are using the Memcached driver, items that are stored "forever" may be removed when the cache reaches its size limit. -### Removing Items From The Cache +### Removing Items From the Cache You may remove items from the cache using the `forget` method: - Cache::forget('key'); +```php +Cache::forget('key'); +``` You may also remove items by providing a zero or negative number of expiration seconds: - Cache::put('key', 'value', 0); +```php +Cache::put('key', 'value', 0); - Cache::put('key', 'value', -5); +Cache::put('key', 'value', -5); +``` You may clear the entire cache using the `flush` method: - Cache::flush(); +```php +Cache::flush(); +``` + +> [!WARNING] +> Flushing the cache does not respect your configured cache "prefix" and will remove all entries from the cache. Consider this carefully when clearing a cache which is shared by other applications. + + +### Cache Memoization + +Laravel's `memo` cache driver allows you to temporarily store resolved cache values in memory during a single request or job execution. This prevents repeated cache hits within the same execution, significantly improving performance. + +To use the memoized cache, invoke the `memo` method: + +```php +use Illuminate\Support\Facades\Cache; + +$value = Cache::memo()->get('key'); +``` + +The `memo` method optionally accepts the name of a cache store, which specifies the underlying cache store the memoized driver will decorate: + +```php +// Using the default cache store... +$value = Cache::memo()->get('key'); + +// Using the Redis cache store... +$value = Cache::memo('redis')->get('key'); +``` + +The first `get` call for a given key retrieves the value from your cache store, but subsequent calls within the same request or job will retrieve the value from memory: + +```php +// Hits the cache... +$value = Cache::memo()->get('key'); + +// Does not hit the cache, returns memoized value... +$value = Cache::memo()->get('key'); +``` + +When calling methods that modify cache values (such as `put`, `increment`, `remember`, etc.), the memoized cache automatically forgets the memoized value and delegates the mutating method call to the underlying cache store: + +```php +Cache::memo()->put('name', 'Taylor'); // Writes to underlying cache... +Cache::memo()->get('name'); // Hits underlying cache... +Cache::memo()->get('name'); // Memoized, does not hit cache... -> {note} Flushing the cache does not respect your configured cache "prefix" and will remove all entries from the cache. Consider this carefully when clearing a cache which is shared by other applications. +Cache::memo()->put('name', 'Tim'); // Forgets memoized value, writes new value... +Cache::memo()->get('name'); // Hits underlying cache again... +``` ### The Cache Helper In addition to using the `Cache` facade, you may also use the global `cache` function to retrieve and store data via the cache. When the `cache` function is called with a single, string argument, it will return the value of the given key: - $value = cache('key'); +```php +$value = cache('key'); +``` If you provide an array of key / value pairs and an expiration time to the function, it will store values in the cache for the specified duration: - cache(['key' => 'value'], $seconds); +```php +cache(['key' => 'value'], $seconds); - cache(['key' => 'value'], now()->addMinutes(10)); +cache(['key' => 'value'], now()->addMinutes(10)); +``` When the `cache` function is called without any arguments, it returns an instance of the `Illuminate\Contracts\Cache\Factory` implementation, allowing you to call other caching methods: - cache()->remember('users', $seconds, function () { - return DB::table('users')->get(); - }); +```php +cache()->remember('users', $seconds, function () { + return DB::table('users')->get(); +}); +``` -> {tip} When testing call to the global `cache` function, you may use the `Cache::shouldReceive` method just as if you were [testing the facade](/docs/{{version}}/mocking#mocking-facades). +> [!NOTE] +> When testing calls to the global `cache` function, you may use the `Cache::shouldReceive` method just as if you were [testing the facade](/docs/{{version}}/mocking#mocking-facades). ## Cache Tags -> {note} Cache tags are not supported when using the `file`, `dynamodb`, or `database` cache drivers. Furthermore, when using multiple tags with caches that are stored "forever", performance will be best with a driver such as `memcached`, which automatically purges stale records. +> [!WARNING] +> Cache tags are not supported when using the `file`, `dynamodb`, or `database` cache drivers. ### Storing Tagged Cache Items Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let's access a tagged cache and `put` a value into the cache: - Cache::tags(['people', 'artists'])->put('John', $john, $seconds); +```php +use Illuminate\Support\Facades\Cache; - Cache::tags(['people', 'authors'])->put('Anne', $anne, $seconds); +Cache::tags(['people', 'artists'])->put('John', $john, $seconds); +Cache::tags(['people', 'authors'])->put('Anne', $anne, $seconds); +``` ### Accessing Tagged Cache Items -To retrieve a tagged cache item, pass the same ordered list of tags to the `tags` method and then call the `get` method with the key you wish to retrieve: +Items stored via tags may not be accessed without also providing the tags that were used to store the value. To retrieve a tagged cache item, pass the same ordered list of tags to the `tags` method, then call the `get` method with the key you wish to retrieve: - $john = Cache::tags(['people', 'artists'])->get('John'); +```php +$john = Cache::tags(['people', 'artists'])->get('John'); - $anne = Cache::tags(['people', 'authors'])->get('Anne'); +$anne = Cache::tags(['people', 'authors'])->get('Anne'); +``` ### Removing Tagged Cache Items -You may flush all items that are assigned a tag or list of tags. For example, this statement would remove all caches tagged with either `people`, `authors`, or both. So, both `Anne` and `John` would be removed from the cache: +You may flush all items that are assigned a tag or list of tags. For example, the following code would remove all caches tagged with either `people`, `authors`, or both. So, both `Anne` and `John` would be removed from the cache: - Cache::tags(['people', 'authors'])->flush(); +```php +Cache::tags(['people', 'authors'])->flush(); +``` -In contrast, this statement would remove only cached values tagged with `authors`, so `Anne` would be removed, but not `John`: +In contrast, the code below would remove only cached values tagged with `authors`, so `Anne` would be removed, but not `John`: - Cache::tags('authors')->flush(); +```php +Cache::tags('authors')->flush(); +``` ## Atomic Locks -> {note} To utilize this feature, your application must be using the `memcached`, `redis`, `dynamodb`, `database`, `file`, or `array` cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server. - - -### Driver Prerequisites - - -#### Database - -When using the `database` cache driver, you will need to setup a table to contain your application's cache locks. You'll find an example `Schema` declaration for the table below: - - Schema::create('cache_locks', function ($table) { - $table->string('key')->primary(); - $table->string('owner'); - $table->integer('expiration'); - }); +> [!WARNING] +> To utilize this feature, your application must be using the `memcached`, `redis`, `dynamodb`, `database`, `file`, or `array` cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server. ### Managing Locks -Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. For example, [Laravel Forge](https://forge.laravel.com) uses atomic locks to ensure that only one remote task is being executed on a server at a time. You may create and manage locks using the `Cache::lock` method: +Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. For example, [Laravel Cloud](https://cloud.laravel.com) uses atomic locks to ensure that only one remote task is being executed on a server at a time. You may create and manage locks using the `Cache::lock` method: - use Illuminate\Support\Facades\Cache; +```php +use Illuminate\Support\Facades\Cache; - $lock = Cache::lock('foo', 10); +$lock = Cache::lock('foo', 10); - if ($lock->get()) { - // Lock acquired for 10 seconds... +if ($lock->get()) { + // Lock acquired for 10 seconds... - $lock->release(); - } + $lock->release(); +} +``` The `get` method also accepts a closure. After the closure is executed, Laravel will automatically release the lock: - Cache::lock('foo')->get(function () { - // Lock acquired indefinitely and automatically released... - }); +```php +Cache::lock('foo', 10)->get(function () { + // Lock acquired for 10 seconds and automatically released... +}); +``` -If the lock is not available at the moment you request it, you may instruct Laravel to wait for a specified number of seconds. If the lock can not be acquired within the specified time limit, an `Illuminate\Contracts\Cache\LockTimeoutException` will be thrown: +If the lock is not available at the moment you request it, you may instruct Laravel to wait for a specified number of seconds. If the lock cannot be acquired within the specified time limit, an `Illuminate\Contracts\Cache\LockTimeoutException` will be thrown: - use Illuminate\Contracts\Cache\LockTimeoutException; +```php +use Illuminate\Contracts\Cache\LockTimeoutException; - $lock = Cache::lock('foo', 10); +$lock = Cache::lock('foo', 10); - try { - $lock->block(5); +try { + $lock->block(5); - // Lock acquired after waiting a maximum of 5 seconds... - } catch (LockTimeoutException $e) { - // Unable to acquire lock... - } finally { - optional($lock)->release(); - } + // Lock acquired after waiting a maximum of 5 seconds... +} catch (LockTimeoutException $e) { + // Unable to acquire lock... +} finally { + $lock->release(); +} +``` The example above may be simplified by passing a closure to the `block` method. When a closure is passed to this method, Laravel will attempt to acquire the lock for the specified number of seconds and will automatically release the lock once the closure has been executed: - Cache::lock('foo', 10)->block(5, function () { - // Lock acquired after waiting a maximum of 5 seconds... - }); +```php +Cache::lock('foo', 10)->block(5, function () { + // Lock acquired for 10 seconds after waiting a maximum of 5 seconds... +}); +``` ### Managing Locks Across Processes @@ -361,126 +508,168 @@ Sometimes, you may wish to acquire a lock in one process and release it in anoth In the example below, we will dispatch a queued job if a lock is successfully acquired. In addition, we will pass the lock's owner token to the queued job via the lock's `owner` method: - $podcast = Podcast::find($id); +```php +$podcast = Podcast::find($id); - $lock = Cache::lock('processing', 120); +$lock = Cache::lock('processing', 120); - if ($lock->get()) { - ProcessPodcast::dispatch($podcast, $lock->owner()); - } +if ($lock->get()) { + ProcessPodcast::dispatch($podcast, $lock->owner()); +} +``` Within our application's `ProcessPodcast` job, we can restore and release the lock using the owner token: - Cache::restoreLock('processing', $this->owner)->release(); +```php +Cache::restoreLock('processing', $this->owner)->release(); +``` If you would like to release a lock without respecting its current owner, you may use the `forceRelease` method: - Cache::lock('processing')->forceRelease(); +```php +Cache::lock('processing')->forceRelease(); +``` + + +## Cache Failover + +The `failover` cache driver provides automatic failover functionality when interacting with the cache. If the primary cache store fails for any reason, Laravel will automatically attempt to use the next configured store in the list. This is particularly useful for ensuring high availability in production environments where cache reliability is critical. + +To configure a failover cache store, specify the `failover` driver and provide an array of store names to attempt in order. By default, Laravel includes an example failover configuration in your application's `config/cache.php` configuration file: + +```php +'failover' => [ + 'driver' => 'failover', + 'stores' => [ + 'database', + 'array', + ], +], +``` + +Once you have configured a store that uses the `failover` driver, you will probably want to set the failover store as your default cache store in your application's `.env` file: + +```ini +CACHE_STORE=failover +``` + +When a cache store operation fails and failover is activated, Laravel will dispatch the `Illuminate\Cache\Events\CacheFailedOver` event, allowing you to report or log that a cache store has failed. ## Adding Custom Cache Drivers -### Writing The Driver +### Writing the Driver To create our custom cache driver, we first need to implement the `Illuminate\Contracts\Cache\Store` [contract](/docs/{{version}}/contracts). So, a MongoDB cache implementation might look something like this: - {tip} If you're wondering where to put your custom cache driver code, you could create an `Extensions` namespace within your `app` directory. However, keep in mind that Laravel does not have a rigid application structure and you are free to organize your application according to your preferences. +> [!NOTE] +> If you're wondering where to put your custom cache driver code, you could create an `Extensions` namespace within your `app` directory. However, keep in mind that Laravel does not have a rigid application structure and you are free to organize your application according to your preferences. -### Registering The Driver +### Registering the Driver To register the custom cache driver with Laravel, we will use the `extend` method on the `Cache` facade. Since other service providers may attempt to read cached values within their `boot` method, we will register our custom driver within a `booting` callback. By using the `booting` callback, we can ensure that the custom driver is registered just before the `boot` method is called on our application's service providers but after the `register` method is called on all of the service providers. We will register our `booting` callback within the `register` method of our application's `App\Providers\AppServiceProvider` class: - app->booting(function () { - Cache::extend('mongo', function ($app) { - return Cache::repository(new MongoStore); - }); + $this->app->booting(function () { + Cache::extend('mongo', function (Application $app) { + return Cache::repository(new MongoStore); }); - } - - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - // - } + }); } + /** + * Bootstrap any application services. + */ + public function boot(): void + { + // ... + } +} +``` + The first argument passed to the `extend` method is the name of the driver. This will correspond to your `driver` option in the `config/cache.php` configuration file. The second argument is a closure that should return an `Illuminate\Cache\Repository` instance. The closure will be passed an `$app` instance, which is an instance of the [service container](/docs/{{version}}/container). -Once your extension is registered, update your `config/cache.php` configuration file's `driver` option to the name of your extension. +Once your extension is registered, update the `CACHE_STORE` environment variable or `default` option within your application's `config/cache.php` configuration file to the name of your extension. ## Events -To execute code on every cache operation, you may listen for the [events](/docs/{{version}}/events) fired by the cache. Typically, you should place these event listeners within your application's `App\Providers\EventServiceProvider` class: - - /** - * The event listener mappings for the application. - * - * @var array - */ - protected $listen = [ - 'Illuminate\Cache\Events\CacheHit' => [ - 'App\Listeners\LogCacheHit', - ], - - 'Illuminate\Cache\Events\CacheMissed' => [ - 'App\Listeners\LogCacheMissed', - ], - - 'Illuminate\Cache\Events\KeyForgotten' => [ - 'App\Listeners\LogKeyForgotten', - ], - - 'Illuminate\Cache\Events\KeyWritten' => [ - 'App\Listeners\LogKeyWritten', - ], - ]; +To execute code on every cache operation, you may listen for various [events](/docs/{{version}}/events) dispatched by the cache: + +
+ +| Event Name | +|----------------------------------------------| +| `Illuminate\Cache\Events\CacheFlushed` | +| `Illuminate\Cache\Events\CacheFlushing` | +| `Illuminate\Cache\Events\CacheHit` | +| `Illuminate\Cache\Events\CacheMissed` | +| `Illuminate\Cache\Events\ForgettingKey` | +| `Illuminate\Cache\Events\KeyForgetFailed` | +| `Illuminate\Cache\Events\KeyForgotten` | +| `Illuminate\Cache\Events\KeyWriteFailed` | +| `Illuminate\Cache\Events\KeyWritten` | +| `Illuminate\Cache\Events\RetrievingKey` | +| `Illuminate\Cache\Events\RetrievingManyKeys` | +| `Illuminate\Cache\Events\WritingKey` | +| `Illuminate\Cache\Events\WritingManyKeys` | + +
+ +To increase performance, you may disable cache events by setting the `events` configuration option to `false` for a given cache store in your application's `config/cache.php` configuration file: + +```php +'database' => [ + 'driver' => 'database', + // ... + 'events' => false, +], +``` diff --git a/cashier-paddle.md b/cashier-paddle.md index 939276c8da5..d0df4c60774 100644 --- a/cashier-paddle.md +++ b/cashier-paddle.md @@ -4,20 +4,26 @@ - [Upgrading Cashier](#upgrading-cashier) - [Installation](#installation) - [Paddle Sandbox](#paddle-sandbox) - - [Database Migrations](#database-migrations) - [Configuration](#configuration) - [Billable Model](#billable-model) - [API Keys](#api-keys) - [Paddle JS](#paddle-js) - [Currency Configuration](#currency-configuration) - [Overriding Default Models](#overriding-default-models) -- [Core Concepts](#core-concepts) - - [Pay Links](#pay-links) +- [Quickstart](#quickstart) + - [Selling Products](#quickstart-selling-products) + - [Selling Subscriptions](#quickstart-selling-subscriptions) +- [Checkout Sessions](#checkout-sessions) + - [Overlay Checkout](#overlay-checkout) - [Inline Checkout](#inline-checkout) - - [User Identification](#user-identification) -- [Prices](#prices) + - [Guest Checkouts](#guest-checkouts) +- [Price Previews](#price-previews) + - [Customer Price Previews](#customer-price-previews) + - [Discounts](#price-discounts) - [Customers](#customers) - [Customer Defaults](#customer-defaults) + - [Retrieving Customers](#retrieving-customers) + - [Creating Customers](#creating-customers) - [Subscriptions](#subscriptions) - [Creating Subscriptions](#creating-subscriptions) - [Checking Subscription Status](#checking-subscription-status) @@ -25,30 +31,34 @@ - [Updating Payment Information](#updating-payment-information) - [Changing Plans](#changing-plans) - [Subscription Quantity](#subscription-quantity) - - [Subscription Modifiers](#subscription-modifiers) + - [Subscriptions With Multiple Products](#subscriptions-with-multiple-products) + - [Multiple Subscriptions](#multiple-subscriptions) - [Pausing Subscriptions](#pausing-subscriptions) - - [Cancelling Subscriptions](#cancelling-subscriptions) + - [Canceling Subscriptions](#canceling-subscriptions) - [Subscription Trials](#subscription-trials) - [With Payment Method Up Front](#with-payment-method-up-front) - [Without Payment Method Up Front](#without-payment-method-up-front) + - [Extend or Activate a Trial](#extend-or-activate-a-trial) - [Handling Paddle Webhooks](#handling-paddle-webhooks) - [Defining Webhook Event Handlers](#defining-webhook-event-handlers) - [Verifying Webhook Signatures](#verifying-webhook-signatures) - [Single Charges](#single-charges) - - [Simple Charge](#simple-charge) - - [Charging Products](#charging-products) - - [Refunding Orders](#refunding-orders) -- [Receipts](#receipts) - - [Past & Upcoming Payments](#past-and-upcoming-payments) -- [Handling Failed Payments](#handling-failed-payments) + - [Charging for Products](#charging-for-products) + - [Refunding Transactions](#refunding-transactions) + - [Crediting Transactions](#crediting-transactions) +- [Transactions](#transactions) + - [Past and Upcoming Payments](#past-and-upcoming-payments) - [Testing](#testing) ## Introduction -[Laravel Cashier Paddle](https://github.com/laravel/cashier-paddle) provides an expressive, fluent interface to [Paddle's](https://paddle.com) subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading. In addition to basic subscription management, Cashier can handle: coupons, swapping subscription, subscription "quantities", cancellation grace periods, and more. +> [!WARNING] +> This documentation is for Cashier Paddle 2.x's integration with Paddle Billing. If you're still using Paddle Classic, you should use [Cashier Paddle 1.x](https://github.com/laravel/cashier-paddle/tree/1.x). -While working with Cashier we recommend you also review Paddle's [user guides](https://developer.paddle.com/guides) and [API documentation](https://developer.paddle.com/api-reference/intro). +[Laravel Cashier Paddle](https://github.com/laravel/cashier-paddle) provides an expressive, fluent interface to [Paddle's](https://paddle.com) subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading. In addition to basic subscription management, Cashier can handle: swapping subscriptions, subscription "quantities", subscription pausing, cancelation grace periods, and more. + +Before digging into Cashier Paddle, we recommend you also review Paddle's [concept guides](https://developer.paddle.com/concepts/overview) and [API documentation](https://developer.paddle.com/api-reference/overview). ## Upgrading Cashier @@ -64,49 +74,33 @@ First, install the Cashier package for Paddle using the Composer package manager composer require laravel/cashier-paddle ``` -> {note} To ensure Cashier properly handles all Paddle events, remember to [set up Cashier's webhook handling](#handling-paddle-webhooks). - - -### Paddle Sandbox - -During local and staging development, you should [register a Paddle Sandbox account](https://developer.paddle.com/getting-started/sandbox). This account will give you a sandboxed environment to test and develop your applications without making actual payments. You may use Paddle's [test card numbers](https://developer.paddle.com/getting-started/sandbox#test-cards) to simulate various payment scenarios. - -When using the Paddle Sandbox environment, you should set the `PADDLE_SANDBOX` environment variable to `true` within your application's `.env` file: +Next, you should publish the Cashier migration files using the `vendor:publish` Artisan command: -```ini -PADDLE_SANDBOX=true +```shell +php artisan vendor:publish --tag="cashier-migrations" ``` -After you have finished developing your application you may [apply for a Paddle vendor account](https://paddle.com). Before your application is placed into production, Paddle will need to approve your application's domain. - - -### Database Migrations - -The Cashier service provider registers its own database migration directory, so remember to migrate your database after installing the package. The Cashier migrations will create a new `customers` table. In addition, a new `subscriptions` table will be created to store all of your customer's subscriptions. Finally, a new `receipts` table will be created to store all of your application's receipt information: +Then, you should run your application's database migrations. The Cashier migrations will create a new `customers` table. In addition, new `subscriptions` and `subscription_items` tables will be created to store all of your customer's subscriptions. Lastly, a new `transactions` table will be created to store all of the Paddle transactions associated with your customers: ```shell php artisan migrate ``` -If you need to overwrite the migrations that are included with Cashier, you can publish them using the `vendor:publish` Artisan command: +> [!WARNING] +> To ensure Cashier properly handles all Paddle events, remember to [set up Cashier's webhook handling](#handling-paddle-webhooks). -```shell -php artisan vendor:publish --tag="cashier-migrations" -``` + +### Paddle Sandbox -If you would like to prevent Cashier's migrations from running entirely, you may use the `ignoreMigrations` provided by Cashier. Typically, this method should be called in the `register` method of your `AppServiceProvider`: +During local and staging development, you should [register a Paddle Sandbox account](https://sandbox-login.paddle.com/signup). This account will give you a sandboxed environment to test and develop your applications without making actual payments. You may use Paddle's [test card numbers](https://developer.paddle.com/concepts/payment-methods/credit-debit-card#test-payment-method) to simulate various payment scenarios. - use Laravel\Paddle\Cashier; +When using the Paddle Sandbox environment, you should set the `PADDLE_SANDBOX` environment variable to `true` within your application's `.env` file: - /** - * Register any application services. - * - * @return void - */ - public function register() - { - Cashier::ignoreMigrations(); - } +```ini +PADDLE_SANDBOX=true +``` + +After you have finished developing your application you may [apply for a Paddle vendor account](https://paddle.com). Before your application is placed into production, Paddle will need to approve your application's domain. ## Configuration @@ -114,24 +108,28 @@ If you would like to prevent Cashier's migrations from running entirely, you may ### Billable Model -Before using Cashier, you must add the `Billable` trait to your user model definition. This trait provides various methods to allow you to perform common billing tasks, such as creating subscriptions, applying coupons and updating payment method information: +Before using Cashier, you must add the `Billable` trait to your user model definition. This trait provides various methods to allow you to perform common billing tasks, such as creating subscriptions and updating payment method information: - use Laravel\Paddle\Billable; +```php +use Laravel\Paddle\Billable; - class User extends Authenticatable - { - use Billable; - } +class User extends Authenticatable +{ + use Billable; +} +``` If you have billable entities that are not users, you may also add the trait to those classes: - use Illuminate\Database\Eloquent\Model; - use Laravel\Paddle\Billable; +```php +use Illuminate\Database\Eloquent\Model; +use Laravel\Paddle\Billable; - class Team extends Model - { - use Billable; - } +class Team extends Model +{ + use Billable; +} +``` ### API Keys @@ -139,14 +137,17 @@ If you have billable entities that are not users, you may also add the trait to Next, you should configure your Paddle keys in your application's `.env` file. You can retrieve your Paddle API keys from the Paddle control panel: ```ini -PADDLE_VENDOR_ID=your-paddle-vendor-id -PADDLE_VENDOR_AUTH_CODE=your-paddle-vendor-auth-code -PADDLE_PUBLIC_KEY="your-paddle-public-key" +PADDLE_CLIENT_SIDE_TOKEN=your-paddle-client-side-token +PADDLE_API_KEY=your-paddle-api-key +PADDLE_RETAIN_KEY=your-paddle-retain-key +PADDLE_WEBHOOK_SECRET="your-paddle-webhook-secret" PADDLE_SANDBOX=true ``` The `PADDLE_SANDBOX` environment variable should be set to `true` when you are using [Paddle's Sandbox environment](#paddle-sandbox). The `PADDLE_SANDBOX` variable should be set to `false` if you are deploying your application to production and are using Paddle's live vendor environment. +The `PADDLE_RETAIN_KEY` is optional and should only be set if you're using Paddle with [Retain](https://developer.paddle.com/concepts/retain/overview). + ### Paddle JS @@ -163,321 +164,577 @@ Paddle relies on its own JavaScript library to initiate the Paddle checkout widg ### Currency Configuration -The default Cashier currency is United States Dollars (USD). You can change the default currency by defining a `CASHIER_CURRENCY` environment variable within your application's `.env` file: - -```ini -CASHIER_CURRENCY=EUR -``` - -In addition to configuring Cashier's currency, you may also specify a locale to be used when formatting money values for display on invoices. Internally, Cashier utilizes [PHP's `NumberFormatter` class](https://www.php.net/manual/en/class.numberformatter.php) to set the currency locale: +You can specify a locale to be used when formatting money values for display on invoices. Internally, Cashier utilizes [PHP's `NumberFormatter` class](https://www.php.net/manual/en/class.numberformatter.php) to set the currency locale: ```ini CASHIER_CURRENCY_LOCALE=nl_BE ``` -> {note} In order to use locales other than `en`, ensure the `ext-intl` PHP extension is installed and configured on your server. +> [!WARNING] +> In order to use locales other than `en`, ensure the `ext-intl` PHP extension is installed and configured on your server. ### Overriding Default Models You are free to extend the models used internally by Cashier by defining your own model and extending the corresponding Cashier model: - use Laravel\Paddle\Subscription as CashierSubscription; +```php +use Laravel\Paddle\Subscription as CashierSubscription; - class Subscription extends CashierSubscription - { - // ... - } +class Subscription extends CashierSubscription +{ + // ... +} +``` After defining your model, you may instruct Cashier to use your custom model via the `Laravel\Paddle\Cashier` class. Typically, you should inform Cashier about your custom models in the `boot` method of your application's `App\Providers\AppServiceProvider` class: - use App\Models\Cashier\Receipt; - use App\Models\Cashier\Subscription; +```php +use App\Models\Cashier\Subscription; +use App\Models\Cashier\Transaction; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Cashier::useSubscriptionModel(Subscription::class); + Cashier::useTransactionModel(Transaction::class); +} +``` + + +## Quickstart + + +### Selling Products + +> [!NOTE] +> Before utilizing Paddle Checkout, you should define Products with fixed prices in your Paddle dashboard. In addition, you should [configure Paddle's webhook handling](#handling-paddle-webhooks). + +Offering product and subscription billing via your application can be intimidating. However, thanks to Cashier and [Paddle's Checkout Overlay](https://developer.paddle.com/concepts/sell/overlay-checkout), you can easily build modern, robust payment integrations. +To charge customers for non-recurring, single-charge products, we'll utilize Cashier to charge customers with Paddle's Checkout Overlay, where they will provide their payment details and confirm their purchase. Once the payment has been made via the Checkout Overlay, the customer will be redirected to a success URL of your choosing within your application: + +```php +use Illuminate\Http\Request; + +Route::get('/buy', function (Request $request) { + $checkout = $request->user()->checkout('pri_deluxe_album') + ->returnTo(route('dashboard')); + + return view('buy', ['checkout' => $checkout]); +})->name('checkout'); +``` + +As you can see in the example above, we will utilize Cashier's provided `checkout` method to create a checkout object to present the customer the Paddle Checkout Overlay for a given "price identifier". When using Paddle, "prices" refer to [defined prices for specific products](https://developer.paddle.com/build/products/create-products-prices). + +If necessary, the `checkout` method will automatically create a customer in Paddle and connect that Paddle customer record to the corresponding user in your application's database. After completing the checkout session, the customer will be redirected to a dedicated success page where you can display an informational message to the customer. + +In the `buy` view, we will include a button to display the Checkout Overlay. The `paddle-button` Blade component is included with Cashier Paddle; however, you may also [manually render an overlay checkout](#manually-rendering-an-overlay-checkout): + +```html + + Buy Product + +``` + + +#### Providing Meta Data to Paddle Checkout + +When selling products, it's common to keep track of completed orders and purchased products via `Cart` and `Order` models defined by your own application. When redirecting customers to Paddle's Checkout Overlay to complete a purchase, you may need to provide an existing order identifier so that you can associate the completed purchase with the corresponding order when the customer is redirected back to your application. + +To accomplish this, you may provide an array of custom data to the `checkout` method. Let's imagine that a pending `Order` is created within our application when a user begins the checkout process. Remember, the `Cart` and `Order` models in this example are illustrative and not provided by Cashier. You are free to implement these concepts based on the needs of your own application: + +```php +use App\Models\Cart; +use App\Models\Order; +use Illuminate\Http\Request; + +Route::get('/cart/{cart}/checkout', function (Request $request, Cart $cart) { + $order = Order::create([ + 'cart_id' => $cart->id, + 'price_ids' => $cart->price_ids, + 'status' => 'incomplete', + ]); + + $checkout = $request->user()->checkout($order->price_ids) + ->customData(['order_id' => $order->id]); + + return view('billing', ['checkout' => $checkout]); +})->name('checkout'); +``` + +As you can see in the example above, when a user begins the checkout process, we will provide all of the cart / order's associated Paddle price identifiers to the `checkout` method. Of course, your application is responsible for associating these items with the "shopping cart" or order as a customer adds them. We also provide the order's ID to the Paddle Checkout Overlay via the `customData` method. + +Of course, you will likely want to mark the order as "complete" once the customer has finished the checkout process. To accomplish this, you may listen to the webhooks dispatched by Paddle and raised via events by Cashier to store order information in your database. + +To get started, listen for the `TransactionCompleted` event dispatched by Cashier. Typically, you should register the event listener in the `boot` method of your application's `AppServiceProvider`: + +```php +use App\Listeners\CompleteOrder; +use Illuminate\Support\Facades\Event; +use Laravel\Paddle\Events\TransactionCompleted; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Event::listen(TransactionCompleted::class, CompleteOrder::class); +} +``` + +In this example, the `CompleteOrder` listener might look like the following: + +```php +namespace App\Listeners; + +use App\Models\Order; +use Laravel\Paddle\Cashier; +use Laravel\Paddle\Events\TransactionCompleted; + +class CompleteOrder +{ /** - * Bootstrap any application services. - * - * @return void + * Handle the incoming Cashier webhook event. */ - public function boot() + public function handle(TransactionCompleted $event): void { - Cashier::useReceiptModel(Receipt::class); - Cashier::useSubscriptionModel(Subscription::class); + $orderId = $event->payload['data']['custom_data']['order_id'] ?? null; + + $order = Order::findOrFail($orderId); + + $order->update(['status' => 'completed']); } +} +``` + +Please refer to Paddle's documentation for more information on the [data contained by the `transaction.completed` event](https://developer.paddle.com/webhooks/transactions/transaction-completed). + + +### Selling Subscriptions - -## Core Concepts +> [!NOTE] +> Before utilizing Paddle Checkout, you should define Products with fixed prices in your Paddle dashboard. In addition, you should [configure Paddle's webhook handling](#handling-paddle-webhooks). - -### Pay Links +Offering product and subscription billing via your application can be intimidating. However, thanks to Cashier and [Paddle's Checkout Overlay](https://developer.paddle.com/concepts/sell/overlay-checkout), you can easily build modern, robust payment integrations. -Paddle lacks an extensive CRUD API to perform subscription state changes. Therefore, most interactions with Paddle are done through its [checkout widget](https://developer.paddle.com/guides/how-tos/checkout/paddle-checkout). Before we can display the checkout widget, we must generate a "pay link" using Cashier. A "pay link" will inform the checkout widget of the billing operation we wish to perform: +To learn how to sell subscriptions using Cashier and Paddle's Checkout Overlay, let's consider the simple scenario of a subscription service with a basic monthly (`price_basic_monthly`) and yearly (`price_basic_yearly`) plan. These two prices could be grouped under a "Basic" product (`pro_basic`) in our Paddle dashboard. In addition, our subscription service might offer an "Expert" plan as `pro_expert`. - use App\Models\User; - use Illuminate\Http\Request; +First, let's discover how a customer can subscribe to our services. Of course, you can imagine the customer might click a "subscribe" button for the Basic plan on our application's pricing page. This button will invoke a Paddle Checkout Overlay for their chosen plan. To get started, let's initiate a checkout session via the `checkout` method: - Route::get('/user/subscribe', function (Request $request) { - $payLink = $request->user()->newSubscription('default', $premium = 34567) - ->returnTo(route('home')) - ->create(); +```php +use Illuminate\Http\Request; - return view('billing', ['payLink' => $payLink]); - }); +Route::get('/subscribe', function (Request $request) { + $checkout = $request->user()->checkout('price_basic_monthly') + ->returnTo(route('dashboard')); -Cashier includes a `paddle-button` [Blade component](/docs/{{version}}/blade#components). We may pass the pay link URL to this component as a "prop". When this button is clicked, Paddle's checkout widget will be displayed: + return view('subscribe', ['checkout' => $checkout]); +})->name('subscribe'); +``` + +In the `subscribe` view, we will include a button to display the Checkout Overlay. The `paddle-button` Blade component is included with Cashier Paddle; however, you may also [manually render an overlay checkout](#manually-rendering-an-overlay-checkout): ```html - + Subscribe ``` -By default, this will display a button with the standard Paddle styling. You can remove all Paddle styling by adding the `data-theme="none"` attribute to the component: +Now, when the Subscribe button is clicked, the customer will be able to enter their payment details and initiate their subscription. To know when their subscription has actually started (since some payment methods require a few seconds to process), you should also [configure Cashier's webhook handling](#handling-paddle-webhooks). + +Now that customers can start subscriptions, we need to restrict certain portions of our application so that only subscribed users can access them. Of course, we can always determine a user's current subscription status via the `subscribed` method provided by Cashier's `Billable` trait: + +```blade +@if ($user->subscribed()) +

You are subscribed.

+@endif +``` + +We can even easily determine if a user is subscribed to specific product or price: + +```blade +@if ($user->subscribedToProduct('pro_basic')) +

You are subscribed to our Basic product.

+@endif + +@if ($user->subscribedToPrice('price_basic_monthly')) +

You are subscribed to our monthly Basic plan.

+@endif +``` + + +#### Building a Subscribed Middleware + +For convenience, you may wish to create a [middleware](/docs/{{version}}/middleware) which determines if the incoming request is from a subscribed user. Once this middleware has been defined, you may easily assign it to a route to prevent users that are not subscribed from accessing the route: + +```php +user()?->subscribed()) { + // Redirect user to billing page and ask them to subscribe... + return redirect('/subscribe'); + } + + return $next($request); + } +} +``` + +Once the middleware has been defined, you may assign it to a route: + +```php +use App\Http\Middleware\Subscribed; + +Route::get('/dashboard', function () { + // ... +})->middleware([Subscribed::class]); +``` + + +#### Allowing Customers to Manage Their Billing Plan + +Of course, customers may want to change their subscription plan to another product or "tier". In our example from above, we'd want to allow the customer to change their plan from a monthly subscription to a yearly subscription. For this you'll need to implement something like a button that leads to the below route: + +```php +use Illuminate\Http\Request; + +Route::put('/subscription/{price}/swap', function (Request $request, $price) { + $user->subscription()->swap($price); // With "$price" being "price_basic_yearly" for this example. + + return redirect()->route('dashboard'); +})->name('subscription.swap'); +``` + +Besides swapping plans you'll also need to allow your customers to cancel their subscription. Like swapping plans, provide a button that leads to the following route: + +```php +use Illuminate\Http\Request; + +Route::put('/subscription/cancel', function (Request $request, $price) { + $user->subscription()->cancel(); + + return redirect()->route('dashboard'); +})->name('subscription.cancel'); +``` + +And now your subscription will get canceled at the end of its billing period. + +> [!NOTE] +> As long as you have configured Cashier's webhook handling, Cashier will automatically keep your application's Cashier-related database tables in sync by inspecting the incoming webhooks from Paddle. So, for example, when you cancel a customer's subscription via Paddle's dashboard, Cashier will receive the corresponding webhook and mark the subscription as "canceled" in your application's database. + + +## Checkout Sessions + +Most operations to bill customers are performed using "checkouts" via Paddle's [Checkout Overlay widget](https://developer.paddle.com/build/checkout/build-overlay-checkout) or by utilizing [inline checkout](https://developer.paddle.com/build/checkout/build-branded-inline-checkout). + +Before processing checkout payments using Paddle, you should define your application's [default payment link](https://developer.paddle.com/build/transactions/default-payment-link#set-default-link) in your Paddle checkout settings dashboard. + + +### Overlay Checkout + +Before displaying the Checkout Overlay widget, you must generate a checkout session using Cashier. A checkout session will inform the checkout widget of the billing operation that should be performed: + +```php +use Illuminate\Http\Request; + +Route::get('/buy', function (Request $request) { + $checkout = $user->checkout('pri_34567') + ->returnTo(route('dashboard')); + + return view('billing', ['checkout' => $checkout]); +}); +``` + +Cashier includes a `paddle-button` [Blade component](/docs/{{version}}/blade#components). You may pass the checkout session to this component as a "prop". Then, when this button is clicked, Paddle's checkout widget will be displayed: ```html - + Subscribe ``` -The Paddle checkout widget is asynchronous. Once the user creates or updates a subscription within the widget, Paddle will send your application webhooks so that you may properly update the subscription state in our own database. Therefore, it's important that you properly [set up webhooks](#handling-paddle-webhooks) to accommodate for state changes from Paddle. +By default, this will display the widget using Paddle's default styling. You can customize the widget by adding [Paddle supported attributes](https://developer.paddle.com/paddlejs/html-data-attributes) like the `data-theme='light'` attribute to the component: + +```html + + Subscribe + +``` -For more information on pay links, you may review [the Paddle API documentation on pay link generation](https://developer.paddle.com/api-reference/product-api/pay-links/createpaylink). +The Paddle checkout widget is asynchronous. Once the user creates a subscription within the widget, Paddle will send your application a webhook so that you may properly update the subscription state in your application's database. Therefore, it's important that you properly [set up webhooks](#handling-paddle-webhooks) to accommodate for state changes from Paddle. -> {note} After a subscription state change, the delay for receiving the corresponding webhook is typically minimal but you should account for this in your application by considering that your user's subscription might not be immediately available after completing the checkout. +> [!WARNING] +> After a subscription state change, the delay for receiving the corresponding webhook is typically minimal but you should account for this in your application by considering that your user's subscription might not be immediately available after completing the checkout. - -#### Manually Rendering Pay Links + +#### Manually Rendering an Overlay Checkout -You may also manually render a pay link without using Laravel's built-in Blade components. To get started, generate the pay link URL as demonstrated in previous examples: +You may also manually render an overlay checkout without using Laravel's built-in Blade components. To get started, generate the checkout session [as demonstrated in previous examples](#overlay-checkout): - $payLink = $request->user()->newSubscription('default', $premium = 34567) - ->returnTo(route('home')) - ->create(); +```php +use Illuminate\Http\Request; -Next, simply attach the pay link URL to an `a` element in your HTML: +Route::get('/buy', function (Request $request) { + $checkout = $user->checkout('pri_34567') + ->returnTo(route('dashboard')); - - Paddle Checkout - + return view('billing', ['checkout' => $checkout]); +}); +``` - -#### Payments Requiring Additional Confirmation +Next, you may use Paddle.js to initialize the checkout. In this example, we will create a link that is assigned the `paddle_button` class. Paddle.js will detect this class and display the overlay checkout when the link is clicked: -Sometimes additional verification is required in order to confirm and process a payment. When this happens, Paddle will present a payment confirmation screen. Payment confirmation screens presented by Paddle or Cashier may be tailored to a specific bank or card issuer's payment flow and can include additional card confirmation, a temporary small charge, separate device authentication, or other forms of verification. +```blade +getItems(); +$customer = $checkout->getCustomer(); +$custom = $checkout->getCustomData(); +?> + +getReturnUrl()) data-success-url='{{ $returnUrl }}' @endif +> + Buy Product + +``` ### Inline Checkout If you don't want to make use of Paddle's "overlay" style checkout widget, Paddle also provides the option to display the widget inline. While this approach does not allow you to adjust any of the checkout's HTML fields, it allows you to embed the widget within your application. -To make it easy for you to get started with inline checkout, Cashier includes a `paddle-checkout` Blade component. To get started, you should [generate a pay link](#pay-links) and pass the pay link to the component's `override` attribute: +To make it easy for you to get started with inline checkout, Cashier includes a `paddle-checkout` Blade component. To get started, you should [generate a checkout session](#overlay-checkout): + +```php +use Illuminate\Http\Request; + +Route::get('/buy', function (Request $request) { + $checkout = $user->checkout('pri_34567') + ->returnTo(route('dashboard')); + + return view('billing', ['checkout' => $checkout]); +}); +``` + +Then, you may pass the checkout session to the component's `checkout` attribute: ```blade - + ``` To adjust the height of the inline checkout component, you may pass the `height` attribute to the Blade component: ```blade - + ``` - -#### Inline Checkout Without Pay Links +Please consult Paddle's [guide on Inline Checkout](https://developer.paddle.com/build/checkout/build-branded-inline-checkout) and [available checkout settings](https://developer.paddle.com/build/checkout/set-up-checkout-default-settings) for further details on the inline checkout's customization options. -Alternatively, you may customize the widget with custom options instead of using a pay link: + +#### Manually Rendering an Inline Checkout -```blade -@php -$options = [ - 'product' => $productId, - 'title' => 'Product Title', -]; -@endphp +You may also manually render an inline checkout without using Laravel's built-in Blade components. To get started, generate the checkout session [as demonstrated in previous examples](#inline-checkout): - -``` +```php +use Illuminate\Http\Request; -Please consult Paddle's [guide on Inline Checkout](https://developer.paddle.com/guides/how-tos/checkout/inline-checkout) as well as their [parameter reference](https://developer.paddle.com/reference/paddle-js/parameters) for further details on the inline checkout's available options. +Route::get('/buy', function (Request $request) { + $checkout = $user->checkout('pri_34567') + ->returnTo(route('dashboard')); -> {note} If you would like to also use the `passthrough` option when specifying custom options, you should provide a key / value array as its value. Cashier will automatically handle converting the array to a JSON string. In addition, the `customer_id` passthrough option is reserved for internal Cashier usage. + return view('billing', ['checkout' => $checkout]); +}); +``` - -#### Manually Rendering An Inline Checkout +Next, you may use Paddle.js to initialize the checkout. In this example, we will demonstrate this using [Alpine.js](https://github.com/alpinejs/alpine); however, you are free to modify this example for your own frontend stack: -You may also manually render an inline checkout without using Laravel's built-in Blade components. To get started, generate the pay link URL [as demonstrated in previous examples](#pay-links). +```blade +options(); -Next, you may use Paddle.js to initialize the checkout. To keep this example simple, we will demonstrate this using [Alpine.js](https://github.com/alpinejs/alpine); however, you are free to translate this example to your own frontend stack: +$options['settings']['frameTarget'] = 'paddle-checkout'; +$options['settings']['frameInitialHeight'] = 366; +?> -```alpine
``` - -### User Identification - -In contrast to Stripe, Paddle users are unique across all of Paddle, not unique per Paddle account. Because of this, Paddle's API's do not currently provide a method to update a user's details such as their email address. When generating pay links, Paddle identifies users using the `customer_email` parameter. When creating a subscription, Paddle will try to match the user provided email to an existing Paddle user. + +### Guest Checkouts -In light of this behavior, there are some important things to keep in mind when using Cashier and Paddle. First, you should be aware that even though subscriptions in Cashier are tied to the same application user, **they could be tied to different users within Paddle's internal systems**. Secondly, each subscription has its own connected payment method information and could also have different email addresses within Paddle's internal systems (depending on which email was assigned to the user when the subscription was created). +Sometimes, you may need to create a checkout session for users that do not need an account with your application. To do so, you may use the `guest` method: -Therefore, when displaying subscriptions you should always inform the user which email address or payment method information is connected to the subscription on a per-subscription basis. Retrieving this information can be done with the following methods provided by the `Laravel\Paddle\Subscription` model: +```php +use Illuminate\Http\Request; +use Laravel\Paddle\Checkout; - $subscription = $user->subscription('default'); +Route::get('/buy', function (Request $request) { + $checkout = Checkout::guest(['pri_34567']) + ->returnTo(route('home')); - $subscription->paddleEmail(); - $subscription->paymentMethod(); - $subscription->cardBrand(); - $subscription->cardLastFour(); - $subscription->cardExpirationDate(); + return view('billing', ['checkout' => $checkout]); +}); +``` -There is currently no way to modify a user's email address through the Paddle API. When a user wants to update their email address within Paddle, the only way for them to do so is to contact Paddle customer support. When communicating with Paddle, they need to provide the `paddleEmail` value of the subscription to assist Paddle in updating the correct user. +Then, you may provide the checkout session to the [Paddle button](#overlay-checkout) or [inline checkout](#inline-checkout) Blade components. - -## Prices + +## Price Previews -Paddle allows you to customize prices per currency, essentially allowing you to configure different prices for different countries. Cashier Paddle allows you to retrieve all of the prices for a given product using the `productPrices` method. This method accepts the product IDs of the products you wish to retrieve prices for: +Paddle allows you to customize prices per currency, essentially allowing you to configure different prices for different countries. Cashier Paddle allows you to retrieve all of these prices using the `previewPrices` method. This method accepts the price IDs you wish to retrieve prices for: - use Laravel\Paddle\Cashier; +```php +use Laravel\Paddle\Cashier; - $prices = Cashier::productPrices([123, 456]); +$prices = Cashier::previewPrices(['pri_123', 'pri_456']); +``` The currency will be determined based on the IP address of the request; however, you may optionally provide a specific country to retrieve prices for: - use Laravel\Paddle\Cashier; - - $prices = Cashier::productPrices([123, 456], ['customer_country' => 'BE']); - -After retrieving the prices you may display them however you wish: +```php +use Laravel\Paddle\Cashier; -```blade -
    - @foreach ($prices as $price) -
  • {{ $price->product_title }} - {{ $price->price()->gross() }}
  • - @endforeach -
+$prices = Cashier::previewPrices(['pri_123', 'pri_456'], ['address' => [ + 'country_code' => 'BE', + 'postal_code' => '1234', +]]); ``` -You may also display the net price (excludes tax) and display the tax amount separately: +After retrieving the prices you may display them however you wish: ```blade
    @foreach ($prices as $price) -
  • {{ $price->product_title }} - {{ $price->price()->net() }} (+ {{ $price->price()->tax() }} tax)
  • +
  • {{ $price->product['name'] }} - {{ $price->total() }}
  • @endforeach
``` -If you retrieved prices for subscription plans you can display their initial and recurring price separately: +You may also display the subtotal price and tax amount separately: ```blade
    @foreach ($prices as $price) -
  • {{ $price->product_title }} - Initial: {{ $price->initialPrice()->gross() }} - Recurring: {{ $price->recurringPrice()->gross() }}
  • +
  • {{ $price->product['name'] }} - {{ $price->subtotal() }} (+ {{ $price->tax() }} tax)
  • @endforeach
``` -For more information, [check Paddle's API documentation on prices](https://developer.paddle.com/api-reference/checkout-api/prices/getprices). +For more information, [checkout Paddle's API documentation regarding price previews](https://developer.paddle.com/api-reference/pricing-preview/preview-prices). - -#### Customers + +### Customer Price Previews If a user is already a customer and you would like to display the prices that apply to that customer, you may do so by retrieving the prices directly from the customer instance: - use App\Models\User; - - $prices = User::find(1)->productPrices([123, 456]); - -Internally, Cashier will use the user's [`paddleCountry` method](#customer-defaults) to retrieve the prices in their currency. So, for example, a user living in the United States will see prices in USD while a user in Belgium will see prices in EUR. If no matching currency can be found the default currency of the product will be used. You can customize all prices of a product or subscription plan in the Paddle control panel. +```php +use App\Models\User; - -#### Coupons +$prices = User::find(1)->previewPrices(['pri_123', 'pri_456']); +``` -You may also choose to display prices after a coupon reduction. When calling the `productPrices` method, coupons may be passed as a comma delimited string: +Internally, Cashier will use the user's customer ID to retrieve the prices in their currency. So, for example, a user living in the United States will see prices in US dollars while a user in Belgium will see prices in Euros. If no matching currency can be found, the default currency of the product will be used. You can customize all prices of a product or subscription plan in the Paddle control panel. - use Laravel\Paddle\Cashier; + +### Discounts - $prices = Cashier::productPrices([123, 456], [ - 'coupons' => 'SUMMERSALE,20PERCENTOFF' - ]); +You may also choose to display prices after a discount. When calling the `previewPrices` method, you provide the discount ID via the `discount_id` option: -Then, display the calculated prices using the `price` method: +```php +use Laravel\Paddle\Cashier; -```blade -
    - @foreach ($prices as $price) -
  • {{ $price->product_title }} - {{ $price->price()->gross() }}
  • - @endforeach -
+$prices = Cashier::previewPrices(['pri_123', 'pri_456'], [ + 'discount_id' => 'dsc_123' +]); ``` -You may display the original listed prices (without coupon discounts) using the `listPrice` method: +Then, display the calculated prices: ```blade
    @foreach ($prices as $price) -
  • {{ $price->product_title }} - {{ $price->listPrice()->gross() }}
  • +
  • {{ $price->product['name'] }} - {{ $price->total() }}
  • @endforeach
``` -> {note} When using the prices API, Paddle only allows applying coupons to one-time purchase products and not to subscription plans. - ## Customers ### Customer Defaults -Cashier allows you to define some useful defaults for your customers when creating pay links. Setting these defaults allow you to pre-fill a customer's email address, country, and postal code so that they can immediately move on to the payment portion of the checkout widget. You can set these defaults by overriding the following methods on your billable model: +Cashier allows you to define some useful defaults for your customers when creating checkout sessions. Setting these defaults allow you to pre-fill a customer's email address and name so that they can immediately move on to the payment portion of the checkout widget. You can set these defaults by overriding the following methods on your billable model: + +```php +/** + * Get the customer's name to associate with Paddle. + */ +public function paddleName(): string|null +{ + return $this->name; +} + +/** + * Get the customer's email address to associate with Paddle. + */ +public function paddleEmail(): string|null +{ + return $this->email; +} +``` - /** - * Get the customer's email address to associate with Paddle. - * - * @return string|null - */ - public function paddleEmail() - { - return $this->email; - } +These defaults will be used for every action in Cashier that generates a [checkout session](#checkout-sessions). - /** - * Get the customer's country to associate with Paddle. - * - * This needs to be a 2 letter code. See the link below for supported countries. - * - * @return string|null - * @link https://developer.paddle.com/reference/platform-parameters/supported-countries - */ - public function paddleCountry() - { - // - } + +### Retrieving Customers - /** - * Get the customer's postal code to associate with Paddle. - * - * See the link below for countries which require this. - * - * @return string|null - * @link https://developer.paddle.com/reference/platform-parameters/supported-countries#countries-requiring-postcode - */ - public function paddlePostcode() - { - // - } +You can retrieve a customer by their Paddle Customer ID using the `Cashier::findBillable` method. This method will return an instance of the billable model: -These defaults will be used for every action in Cashier that generates a [pay link](#pay-links). +```php +use Laravel\Paddle\Cashier; + +$user = Cashier::findBillable($customerId); +``` + + +### Creating Customers + +Occasionally, you may wish to create a Paddle customer without beginning a subscription. You may accomplish this using the `createAsCustomer` method: + +```php +$customer = $user->createAsCustomer(); +``` + +An instance of `Laravel\Paddle\Customer` is returned. Once the customer has been created in Paddle, you may begin a subscription at a later date. You may provide an optional `$options` array to pass in any additional [customer creation parameters that are supported by the Paddle API](https://developer.paddle.com/api-reference/customers/create-customer): + +```php +$customer = $user->createAsCustomer($options); +``` ## Subscriptions @@ -485,226 +742,226 @@ These defaults will be used for every action in Cashier that generates a [pay li ### Creating Subscriptions -To create a subscription, first retrieve an instance of your billable model from your database, which typically will be an instance of `App\Models\User`. Once you have retrieved the model instance, you may use the `newSubscription` method to create the model's subscription pay link: +To create a subscription, first retrieve an instance of your billable model from your database, which will typically be an instance of `App\Models\User`. Once you have retrieved the model instance, you may use the `subscribe` method to create the model's checkout session: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/user/subscribe', function (Request $request) { - $payLink = $request->user()->newSubscription('default', $premium = 12345) - ->returnTo(route('home')) - ->create(); +Route::get('/user/subscribe', function (Request $request) { + $checkout = $request->user()->subscribe($premium = 'pri_123', 'default') + ->returnTo(route('home')); - return view('billing', ['payLink' => $payLink]); - }); + return view('billing', ['checkout' => $checkout]); +}); +``` -The first argument passed to the `newSubscription` method should be the internal name of the subscription. If your application only offers a single subscription, you might call this `default` or `primary`. This subscription name is only for internal application usage and is not meant to be shown to users. In addition, it should not contain spaces and it should never be changed after creating the subscription. The second argument given to the `newSubscription` method is the specific plan the user is subscribing to. This value should correspond to the plan's identifier in Paddle. The `returnTo` method accepts a URL that your user will be redirected to after they successfully complete the checkout. +The first argument given to the `subscribe` method is the specific price the user is subscribing to. This value should correspond to the price's identifier in Paddle. The `returnTo` method accepts a URL that your user will be redirected to after they successfully complete the checkout. The second argument passed to the `subscribe` method should be the internal "type" of the subscription. If your application only offers a single subscription, you might call this `default` or `primary`. This subscription type is only for internal application usage and is not meant to be displayed to users. In addition, it should not contain spaces and it should never be changed after creating the subscription. -The `create` method will create a pay link which you can use to generate a payment button. The payment button can be generated using the `paddle-button` [Blade component](/docs/{{version}}/blade#components) that is included with Cashier Paddle: +You may also provide an array of custom metadata regarding the subscription using the `customData` method: + +```php +$checkout = $request->user()->subscribe($premium = 'pri_123', 'default') + ->customData(['key' => 'value']) + ->returnTo(route('home')); +``` + +Once a subscription checkout session has been created, the checkout session may be provided to the `paddle-button` [Blade component](#overlay-checkout) that is included with Cashier Paddle: ```blade - + Subscribe ``` After the user has finished their checkout, a `subscription_created` webhook will be dispatched from Paddle. Cashier will receive this webhook and setup the subscription for your customer. In order to make sure all webhooks are properly received and handled by your application, ensure you have properly [setup webhook handling](#handling-paddle-webhooks). - -#### Additional Details - -If you would like to specify additional customer or subscription details, you may do so by passing them as an array of key / value pairs to the `create` method. To learn more about the additional fields supported by Paddle, check out Paddle's documentation on [generating pay links](https://developer.paddle.com/api-reference/product-api/pay-links/createpaylink): - - $payLink = $user->newSubscription('default', $monthly = 12345) - ->returnTo(route('home')) - ->create([ - 'vat_number' => $vatNumber, - ]); - - -#### Coupons - -If you would like to apply a coupon when creating the subscription, you may use the `withCoupon` method: - - $payLink = $user->newSubscription('default', $monthly = 12345) - ->returnTo(route('home')) - ->withCoupon('code') - ->create(); - - -#### Metadata - -You can also pass an array of metadata using the `withMetadata` method: - - $payLink = $user->newSubscription('default', $monthly = 12345) - ->returnTo(route('home')) - ->withMetadata(['key' => 'value']) - ->create(); - -> {note} When providing metadata, please avoid using `subscription_name` as a metadata key. This key is reserved for internal use by Cashier. - ### Checking Subscription Status -Once a user is subscribed to your application, you may check their subscription status using a variety of convenient methods. First, the `subscribed` method returns `true` if the user has an active subscription, even if the subscription is currently within its trial period: +Once a user is subscribed to your application, you may check their subscription status using a variety of convenient methods. First, the `subscribed` method returns `true` if the user has a valid subscription, even if the subscription is currently within its trial period: - if ($user->subscribed('default')) { - // - } +```php +if ($user->subscribed()) { + // ... +} +``` + +If your application offers multiple subscriptions, you may specify the subscription when invoking the `subscribed` method: + +```php +if ($user->subscribed('default')) { + // ... +} +``` The `subscribed` method also makes a great candidate for a [route middleware](/docs/{{version}}/middleware), allowing you to filter access to routes and controllers based on the user's subscription status: - user() && ! $request->user()->subscribed('default')) { - // This user is not a paying customer... - return redirect('billing'); - } - - return $next($request); + if ($request->user() && ! $request->user()->subscribed()) { + // This user is not a paying customer... + return redirect('/billing'); } - } - -If you would like to determine if a user is still within their trial period, you may use the `onTrial` method. This method can be useful for determining if you should display a warning to the user that they are still on their trial period: - - if ($user->subscription('default')->onTrial()) { - // - } - -The `subscribedToPlan` method may be used to determine if the user is subscribed to a given plan based on a given Paddle plan ID. In this example, we will determine if the user's `default` subscription is actively subscribed to the monthly plan: - if ($user->subscribedToPlan($monthly = 12345, 'default')) { - // + return $next($request); } +} +``` -By passing an array to the `subscribedToPlan` method, you may determine if the user's `default` subscription is actively subscribed to the monthly or the yearly plan: +If you would like to determine if a user is still within their trial period, you may use the `onTrial` method. This method can be useful for determining if you should display a warning to the user that they are still on their trial period: - if ($user->subscribedToPlan([$monthly = 12345, $yearly = 54321], 'default')) { - // - } +```php +if ($user->subscription()->onTrial()) { + // ... +} +``` -The `recurring` method may be used to determine if the user is currently subscribed and is no longer within their trial period: +The `subscribedToPrice` method may be used to determine if the user is subscribed to a given plan based on a given Paddle price ID. In this example, we will determine if the user's `default` subscription is actively subscribed to the monthly price: - if ($user->subscription('default')->recurring()) { - // - } +```php +if ($user->subscribedToPrice($monthly = 'pri_123', 'default')) { + // ... +} +``` - -#### Cancelled Subscription Status +The `recurring` method may be used to determine if the user is currently on an active subscription and is no longer within their trial period or on a grace period: -To determine if the user was once an active subscriber but has cancelled their subscription, you may use the `cancelled` method: +```php +if ($user->subscription()->recurring()) { + // ... +} +``` - if ($user->subscription('default')->cancelled()) { - // - } + +#### Canceled Subscription Status -You may also determine if a user has cancelled their subscription, but are still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was originally scheduled to expire on March 10th, the user is on their "grace period" until March 10th. Note that the `subscribed` method still returns `true` during this time: +To determine if the user was once an active subscriber but has canceled their subscription, you may use the `canceled` method: - if ($user->subscription('default')->onGracePeriod()) { - // - } +```php +if ($user->subscription()->canceled()) { + // ... +} +``` -To determine if the user has cancelled their subscription and is no longer within their "grace period", you may use the `ended` method: +You may also determine if a user has canceled their subscription, but are still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was originally scheduled to expire on March 10th, the user is on their "grace period" until March 10th. In addition, the `subscribed` method will still return `true` during this time: - if ($user->subscription('default')->ended()) { - // - } +```php +if ($user->subscription()->onGracePeriod()) { + // ... +} +``` #### Past Due Status If a payment fails for a subscription, it will be marked as `past_due`. When your subscription is in this state it will not be active until the customer has updated their payment information. You may determine if a subscription is past due using the `pastDue` method on the subscription instance: - if ($user->subscription('default')->pastDue()) { - // - } +```php +if ($user->subscription()->pastDue()) { + // ... +} +``` -When a subscription is past due, you should instruct the user to [update their payment information](#updating-payment-information). You may configure how past due subscriptions are handled in your [Paddle subscription settings](https://vendors.paddle.com/subscription-settings). +When a subscription is past due, you should instruct the user to [update their payment information](#updating-payment-information). -If you would like subscriptions to still be considered active when they are `past_due`, you may use the `keepPastDueSubscriptionsActive` method provided by Cashier. Typically, this method should be called in the `register` method of your `AppServiceProvider`: +If you would like subscriptions to still be considered valid when they are `past_due`, you may use the `keepPastDueSubscriptionsActive` method provided by Cashier. Typically, this method should be called in the `register` method of your `AppServiceProvider`: - use Laravel\Paddle\Cashier; +```php +use Laravel\Paddle\Cashier; - /** - * Register any application services. - * - * @return void - */ - public function register() - { - Cashier::keepPastDueSubscriptionsActive(); - } +/** + * Register any application services. + */ +public function register(): void +{ + Cashier::keepPastDueSubscriptionsActive(); +} +``` -> {note} When a subscription is in a `past_due` state it cannot be changed until payment information has been updated. Therefore, the `swap` and `updateQuantity` methods will throw an exception when the subscription is in a `past_due` state. +> [!WARNING] +> When a subscription is in a `past_due` state it cannot be changed until payment information has been updated. Therefore, the `swap` and `updateQuantity` methods will throw an exception when the subscription is in a `past_due` state. #### Subscription Scopes Most subscription states are also available as query scopes so that you may easily query your database for subscriptions that are in a given state: - // Get all active subscriptions... - $subscriptions = Subscription::query()->active()->get(); +```php +// Get all valid subscriptions... +$subscriptions = Subscription::query()->valid()->get(); - // Get all of the cancelled subscriptions for a user... - $subscriptions = $user->subscriptions()->cancelled()->get(); +// Get all of the canceled subscriptions for a user... +$subscriptions = $user->subscriptions()->canceled()->get(); +``` A complete list of available scopes is available below: - Subscription::query()->active(); - Subscription::query()->onTrial(); - Subscription::query()->notOnTrial(); - Subscription::query()->pastDue(); - Subscription::query()->recurring(); - Subscription::query()->ended(); - Subscription::query()->paused(); - Subscription::query()->notPaused(); - Subscription::query()->onPausedGracePeriod(); - Subscription::query()->notOnPausedGracePeriod(); - Subscription::query()->cancelled(); - Subscription::query()->notCancelled(); - Subscription::query()->onGracePeriod(); - Subscription::query()->notOnGracePeriod(); +```php +Subscription::query()->valid(); +Subscription::query()->onTrial(); +Subscription::query()->expiredTrial(); +Subscription::query()->notOnTrial(); +Subscription::query()->active(); +Subscription::query()->recurring(); +Subscription::query()->pastDue(); +Subscription::query()->paused(); +Subscription::query()->notPaused(); +Subscription::query()->onPausedGracePeriod(); +Subscription::query()->notOnPausedGracePeriod(); +Subscription::query()->canceled(); +Subscription::query()->notCanceled(); +Subscription::query()->onGracePeriod(); +Subscription::query()->notOnGracePeriod(); +``` ### Subscription Single Charges -Subscription single charges allow you to charge subscribers with a one-time charge on top of their subscriptions: +Subscription single charges allow you to charge subscribers with a one-time charge on top of their subscriptions. You must provide one or multiple price ID's when invoking the `charge` method: - $response = $user->subscription('default')->charge(12.99, 'Support Add-on'); +```php +// Charge a single price... +$response = $user->subscription()->charge('pri_123'); -In contrast to [single charges](#single-charges), this method will immediately charge the customer's stored payment method for the subscription. The charge amount should always be defined in the currency of the subscription. +// Charge multiple prices at once... +$response = $user->subscription()->charge(['pri_123', 'pri_456']); +``` - -### Updating Payment Information +The `charge` method will not actually charge the customer until the next billing interval of their subscription. If you would like to bill the customer immediately, you may use the `chargeAndInvoice` method instead: -Paddle always saves a payment method per subscription. If you want to update the default payment method for a subscription, you should first generate a subscription "update URL" using the `updateUrl` method on the subscription model: +```php +$response = $user->subscription()->chargeAndInvoice('pri_123'); +``` - use App\Models\User; + +### Updating Payment Information - $user = User::find(1); +Paddle always saves a payment method per subscription. If you want to update the default payment method for a subscription, you should redirect your customer to Paddle's hosted payment method update page using the `redirectToUpdatePaymentMethod` method on the subscription model: - $updateUrl = $user->subscription('default')->updateUrl(); +```php +use Illuminate\Http\Request; -Then, you may use the generated URL in combination with Cashier's provided `paddle-button` Blade component to allow the user to initiate the Paddle widget and update their payment information: +Route::get('/update-payment-method', function (Request $request) { + $user = $request->user(); -```html - - Update Card - + return $user->subscription()->redirectToUpdatePaymentMethod(); +}); ``` When a user has finished updating their information, a `subscription_updated` webhook will be dispatched by Paddle and the subscription details will be updated in your application's database. @@ -712,138 +969,246 @@ When a user has finished updating their information, a `subscription_updated` we ### Changing Plans -After a user has subscribed to your application, they may occasionally want to change to a new subscription plan. To update the subscription plan for a user, you should pass the Paddle plan's identifier to the subscription's `swap` method: +After a user has subscribed to your application, they may occasionally want to change to a new subscription plan. To update the subscription plan for a user, you should pass the Paddle price's identifier to the subscription's `swap` method: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $user->subscription('default')->swap($premium = 34567); +$user->subscription()->swap($premium = 'pri_456'); +``` If you would like to swap plans and immediately invoice the user instead of waiting for their next billing cycle, you may use the `swapAndInvoice` method: - $user = User::find(1); +```php +$user = User::find(1); - $user->subscription('default')->swapAndInvoice($premium = 34567); - -> {note} Plans may not be swapped when a trial is active. For additional information regarding this limitation, please see the [Paddle documentation](https://developer.paddle.com/api-reference/subscription-api/users/updateuser#usage-notes). +$user->subscription()->swapAndInvoice($premium = 'pri_456'); +``` #### Prorations -By default, Paddle prorates charges when swapping between plans. The `noProrate` method may be used to update the subscription's without prorating the charges: +By default, Paddle prorates charges when swapping between plans. The `noProrate` method may be used to update the subscriptions without prorating the charges: + +```php +$user->subscription('default')->noProrate()->swap($premium = 'pri_456'); +``` + +If you would like to disable proration and invoice customers immediately, you may use the `swapAndInvoice` method in combination with `noProrate`: + +```php +$user->subscription('default')->noProrate()->swapAndInvoice($premium = 'pri_456'); +``` + +Or, to not bill your customer for a subscription change, you may utilize the `doNotBill` method: + +```php +$user->subscription('default')->doNotBill()->swap($premium = 'pri_456'); +``` - $user->subscription('default')->noProrate()->swap($premium = 34567); +For more information on Paddle's proration policies, please consult Paddle's [proration documentation](https://developer.paddle.com/concepts/subscriptions/proration). ### Subscription Quantity Sometimes subscriptions are affected by "quantity". For example, a project management application might charge $10 per month per project. To easily increment or decrement your subscription's quantity, use the `incrementQuantity` and `decrementQuantity` methods: - $user = User::find(1); +```php +$user = User::find(1); - $user->subscription('default')->incrementQuantity(); +$user->subscription()->incrementQuantity(); - // Add five to the subscription's current quantity... - $user->subscription('default')->incrementQuantity(5); +// Add five to the subscription's current quantity... +$user->subscription()->incrementQuantity(5); - $user->subscription('default')->decrementQuantity(); +$user->subscription()->decrementQuantity(); - // Subtract five from the subscription's current quantity... - $user->subscription('default')->decrementQuantity(5); +// Subtract five from the subscription's current quantity... +$user->subscription()->decrementQuantity(5); +``` Alternatively, you may set a specific quantity using the `updateQuantity` method: - $user->subscription('default')->updateQuantity(10); +```php +$user->subscription()->updateQuantity(10); +``` The `noProrate` method may be used to update the subscription's quantity without prorating the charges: - $user->subscription('default')->noProrate()->updateQuantity(10); +```php +$user->subscription()->noProrate()->updateQuantity(10); +``` + + +#### Quantities for Subscriptions With Multiple Products + +If your subscription is a [subscription with multiple products](#subscriptions-with-multiple-products), you should pass the ID of the price whose quantity you wish to increment or decrement as the second argument to the increment / decrement methods: - -### Subscription Modifiers +```php +$user->subscription()->incrementQuantity(1, 'price_chat'); +``` -Subscription modifiers allow you to implement [metered billing](https://developer.paddle.com/guides/how-tos/subscriptions/metered-billing#using-subscription-price-modifiers) or extend subscriptions with add-ons. + +### Subscriptions With Multiple Products -For example, you might want to offer a "Premium Support" add-on with your standard subscription. You can create this modifier like so: +[Subscription with multiple products](https://developer.paddle.com/build/subscriptions/add-remove-products-prices-addons) allow you to assign multiple billing products to a single subscription. For example, imagine you are building a customer service "helpdesk" application that has a base subscription price of $10 per month but offers a live chat add-on product for an additional $15 per month. - $modifier = $user->subscription('default')->newModifier(12.99)->create(); +When creating subscription checkout sessions, you may specify multiple products for a given subscription by passing an array of prices as the first argument to the `subscribe` method: -The example above will add a $12.99 add-on to the subscription. By default, this charge will recur on every interval you have configured for the subscription. If you would like, you can add a readable description to the modifier using the modifier's `description` method: +```php +use Illuminate\Http\Request; - $modifier = $user->subscription('default')->newModifier(12.99) - ->description('Premium Support') - ->create(); +Route::post('/user/subscribe', function (Request $request) { + $checkout = $request->user()->subscribe([ + 'price_monthly', + 'price_chat', + ]); -To illustrate how to implement metered billing using modifiers, imagine your application charges per SMS message sent by the user. First, you should create a $0 plan in your Paddle dashboard. Once the user has been subscribed to this plan, you can add modifiers representing each individual charge to the subscription: + return view('billing', ['checkout' => $checkout]); +}); +``` - $modifier = $user->subscription('default')->newModifier(0.99) - ->description('New text message') - ->oneTime() - ->create(); +In the example above, the customer will have two prices attached to their `default` subscription. Both prices will be charged on their respective billing intervals. If necessary, you may pass an associative array of key / value pairs to indicate a specific quantity for each price: -As you can see, we invoked the `oneTime` method when creating this modifier. This method will ensure the modifier is only charged once and does not recur every billing interval. +```php +$user = User::find(1); - -#### Retrieving Modifiers +$checkout = $user->subscribe('default', ['price_monthly', 'price_chat' => 5]); +``` -You may retrieve a list of all modifiers for a subscription via the `modifiers` method: +If you would like to add another price to an existing subscription, you must use the subscription's `swap` method. When invoking the `swap` method, you should also include the subscription's current prices and quantities as well: - $modifiers = $user->subscription('default')->modifiers(); +```php +$user = User::find(1); - foreach ($modifiers as $modifier) { - $modifier->amount(); // $0.99 - $modifier->description; // New text message. - } +$user->subscription()->swap(['price_chat', 'price_original' => 2]); +``` + +The example above will add the new price, but the customer will not be billed for it until their next billing cycle. If you would like to bill the customer immediately you may use the `swapAndInvoice` method: + +```php +$user->subscription()->swapAndInvoice(['price_chat', 'price_original' => 2]); +``` + +You may remove prices from subscriptions using the `swap` method and omitting the price you want to remove: + +```php +$user->subscription()->swap(['price_original' => 2]); +``` - -#### Deleting Modifiers +> [!WARNING] +> You may not remove the last price on a subscription. Instead, you should simply cancel the subscription. -Modifiers may be deleted by invoking the `delete` method on a `Laravel\Paddle\Modifier` instance: + +### Multiple Subscriptions - $modifier->delete(); +Paddle allows your customers to have multiple subscriptions simultaneously. For example, you may run a gym that offers a swimming subscription and a weight-lifting subscription, and each subscription may have different pricing. Of course, customers should be able to subscribe to either or both plans. + +When your application creates subscriptions, you may provide the type of the subscription to the `subscribe` method as the second argument. The type may be any string that represents the type of subscription the user is initiating: + +```php +use Illuminate\Http\Request; + +Route::post('/swimming/subscribe', function (Request $request) { + $checkout = $request->user()->subscribe($swimmingMonthly = 'pri_123', 'swimming'); + + return view('billing', ['checkout' => $checkout]); +}); +``` + +In this example, we initiated a monthly swimming subscription for the customer. However, they may want to swap to a yearly subscription at a later time. When adjusting the customer's subscription, we can simply swap the price on the `swimming` subscription: + +```php +$user->subscription('swimming')->swap($swimmingYearly = 'pri_456'); +``` + +Of course, you may also cancel the subscription entirely: + +```php +$user->subscription('swimming')->cancel(); +``` ### Pausing Subscriptions To pause a subscription, call the `pause` method on the user's subscription: - $user->subscription('default')->pause(); +```php +$user->subscription()->pause(); +``` + +When a subscription is paused, Cashier will automatically set the `paused_at` column in your database. This column is used to determine when the `paused` method should begin returning `true`. For example, if a customer pauses a subscription on March 1st, but the subscription was not scheduled to recur until March 5th, the `paused` method will continue to return `false` until March 5th. This is because a user is typically allowed to continue using an application until the end of their billing cycle. + +By default, pausing happens at the next billing interval so the customer can use the remainder of the period they paid for. If you want to pause a subscription immediately, you may use the `pauseNow` method: + +```php +$user->subscription()->pauseNow(); +``` + +Using the `pauseUntil` method, you can pause the subscription until a specific moment in time: + +```php +$user->subscription()->pauseUntil(now()->addMonth()); +``` + +Or, you may use the `pauseNowUntil` method to immediately pause the subscription until a given point in time: -When a subscription is paused, Cashier will automatically set the `paused_from` column in your database. This column is used to know when the `paused` method should begin returning `true`. For example, if a customer pauses a subscription on March 1st, but the subscription was not scheduled to recur until March 5th, the `paused` method will continue to return `false` until March 5th. This is done because a user is typically allowed to continue using an application until the end of their billing cycle. +```php +$user->subscription()->pauseNowUntil(now()->addMonth()); +``` You may determine if a user has paused their subscription but are still on their "grace period" using the `onPausedGracePeriod` method: - if ($user->subscription('default')->onPausedGracePeriod()) { - // - } +```php +if ($user->subscription()->onPausedGracePeriod()) { + // ... +} +``` -To resume a paused a subscription, you may call the `unpause` method on the user's subscription: +To resume a paused subscription, you may invoke the `resume` method on the subscription: - $user->subscription('default')->unpause(); +```php +$user->subscription()->resume(); +``` -> {note} A subscription cannot be modified while it is paused. If you want to swap to a different plan or update quantities you must resume the subscription first. +> [!WARNING] +> A subscription cannot be modified while it is paused. If you want to swap to a different plan or update quantities you must resume the subscription first. - -### Cancelling Subscriptions + +### Canceling Subscriptions To cancel a subscription, call the `cancel` method on the user's subscription: - $user->subscription('default')->cancel(); +```php +$user->subscription()->cancel(); +``` -When a subscription is cancelled, Cashier will automatically set the `ends_at` column in your database. This column is used to know when the `subscribed` method should begin returning `false`. For example, if a customer cancels a subscription on March 1st, but the subscription was not scheduled to end until March 5th, the `subscribed` method will continue to return `true` until March 5th. This is done because a user is typically allowed to continue using an application until the end of their billing cycle. +When a subscription is canceled, Cashier will automatically set the `ends_at` column in your database. This column is used to determine when the `subscribed` method should begin returning `false`. For example, if a customer cancels a subscription on March 1st, but the subscription was not scheduled to end until March 5th, the `subscribed` method will continue to return `true` until March 5th. This is done because a user is typically allowed to continue using an application until the end of their billing cycle. -You may determine if a user has cancelled their subscription but are still on their "grace period" using the `onGracePeriod` method: +You may determine if a user has canceled their subscription but are still on their "grace period" using the `onGracePeriod` method: - if ($user->subscription('default')->onGracePeriod()) { - // - } +```php +if ($user->subscription()->onGracePeriod()) { + // ... +} +``` + +If you wish to cancel a subscription immediately, you may call the `cancelNow` method on the subscription: + +```php +$user->subscription()->cancelNow(); +``` -If you wish to cancel a subscription immediately, you may call the `cancelNow` method on the user's subscription: +To stop a subscription on its grace period from canceling, you may invoke the `stopCancelation` method: - $user->subscription('default')->cancelNow(); +```php +$user->subscription()->stopCancelation(); +``` -> {note} Paddle's subscriptions cannot be resumed after cancellation. If your customer wishes to resume their subscription, they will have to subscribe to a new subscription. +> [!WARNING] +> Paddle's subscriptions cannot be resumed after cancelation. If your customer wishes to resume their subscription, they will have to create a new subscription. ## Subscription Trials @@ -851,178 +1216,203 @@ If you wish to cancel a subscription immediately, you may call the `cancelNow` m ### With Payment Method Up Front -> {note} While trialing and collecting payment method details up front, Paddle prevents any subscription changes such as swapping plans or updating quantities. If you want to allow a customer to swap plans during a trial the subscription must be cancelled and recreated. +If you would like to offer trial periods to your customers while still collecting payment method information up front, you should use set a trial time in the Paddle dashboard on the price your customer is subscribing to. Then, initiate the checkout session as normal: -If you would like to offer trial periods to your customers while still collecting payment method information up front, you should use the `trialDays` method when creating your subscription pay links: +```php +use Illuminate\Http\Request; - use Illuminate\Http\Request; +Route::get('/user/subscribe', function (Request $request) { + $checkout = $request->user() + ->subscribe('pri_monthly') + ->returnTo(route('home')); - Route::get('/user/subscribe', function (Request $request) { - $payLink = $request->user()->newSubscription('default', $monthly = 12345) - ->returnTo(route('home')) - ->trialDays(10) - ->create(); + return view('billing', ['checkout' => $checkout]); +}); +``` - return view('billing', ['payLink' => $payLink]); - }); +When your application receives the `subscription_created` event, Cashier will set the trial period ending date on the subscription record within your application's database as well as instruct Paddle to not begin billing the customer until after this date. -This method will set the trial period ending date on the subscription record within your application's database, as well as instruct Paddle to not begin billing the customer until after this date. +> [!WARNING] +> If the customer's subscription is not canceled before the trial ending date they will be charged as soon as the trial expires, so you should be sure to notify your users of their trial ending date. -> {note} If the customer's subscription is not cancelled before the trial ending date they will be charged as soon as the trial expires, so you should be sure to notify your users of their trial ending date. +You may determine if the user is within their trial period using either the `onTrial` method of the user instance: -You may determine if the user is within their trial period using either the `onTrial` method of the user instance or the `onTrial` method of the subscription instance. The two examples below are equivalent: +```php +if ($user->onTrial()) { + // ... +} +``` - if ($user->onTrial('default')) { - // - } +To determine if an existing trial has expired, you may use the `hasExpiredTrial` methods: - if ($user->subscription('default')->onTrial()) { - // - } +```php +if ($user->hasExpiredTrial()) { + // ... +} +``` - -#### Defining Trial Days In Paddle / Cashier +To determine if a user is on trial for a specific subscription type, you may provide the type to the `onTrial` or `hasExpiredTrial` methods: -You may choose to define how many trial days your plan's receive in the Paddle dashboard or always pass them explicitly using Cashier. If you choose to define your plan's trial days in Paddle you should be aware that new subscriptions, including new subscriptions for a customer that had a subscription in the past, will always receive a trial period unless you explicitly call the `trialDays(0)` method. +```php +if ($user->onTrial('default')) { + // ... +} + +if ($user->hasExpiredTrial('default')) { + // ... +} +``` ### Without Payment Method Up Front If you would like to offer trial periods without collecting the user's payment method information up front, you may set the `trial_ends_at` column on the customer record attached to your user to your desired trial ending date. This is typically done during user registration: - use App\Models\User; +```php +use App\Models\User; - $user = User::create([ - // ... - ]); +$user = User::create([ + // ... +]); - $user->createAsCustomer([ - 'trial_ends_at' => now()->addDays(10) - ]); +$user->createAsCustomer([ + 'trial_ends_at' => now()->addDays(10) +]); +``` Cashier refers to this type of trial as a "generic trial", since it is not attached to any existing subscription. The `onTrial` method on the `User` instance will return `true` if the current date is not past the value of `trial_ends_at`: - if ($user->onTrial()) { - // User is within their trial period... - } +```php +if ($user->onTrial()) { + // User is within their trial period... +} +``` -Once you are ready to create an actual subscription for the user, you may use the `newSubscription` method as usual: +Once you are ready to create an actual subscription for the user, you may use the `subscribe` method as usual: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/user/subscribe', function (Request $request) { - $payLink = $user->newSubscription('default', $monthly = 12345) - ->returnTo(route('home')) - ->create(); +Route::get('/user/subscribe', function (Request $request) { + $checkout = $request->user() + ->subscribe('pri_monthly') + ->returnTo(route('home')); - return view('billing', ['payLink' => $payLink]); - }); + return view('billing', ['checkout' => $checkout]); +}); +``` -To retrieve the user's trial ending date, you may use the `trialEndsAt` method. This method will return a Carbon date instance if a user is on a trial or `null` if they aren't. You may also pass an optional subscription name parameter if you would like to get the trial ending date for a specific subscription other than the default one: +To retrieve the user's trial ending date, you may use the `trialEndsAt` method. This method will return a Carbon date instance if a user is on a trial or `null` if they aren't. You may also pass an optional subscription type parameter if you would like to get the trial ending date for a specific subscription other than the default one: - if ($user->onTrial()) { - $trialEndsAt = $user->trialEndsAt('main'); - } +```php +if ($user->onTrial('default')) { + $trialEndsAt = $user->trialEndsAt(); +} +``` You may use the `onGenericTrial` method if you wish to know specifically that the user is within their "generic" trial period and has not created an actual subscription yet: - if ($user->onGenericTrial()) { - // User is within their "generic" trial period... - } +```php +if ($user->onGenericTrial()) { + // User is within their "generic" trial period... +} +``` -> {note} There is no way to extend or modify a trial period on a Paddle subscription after it has been created. + +### Extend or Activate a Trial + +You can extend an existing trial period on a subscription by invoking the `extendTrial` method and specifying the moment in time that the trial should end: + +```php +$user->subscription()->extendTrial(now()->addDays(5)); +``` + +Or, you may immediately activate a subscription by ending its trial by calling the `activate` method on the subscription: + +```php +$user->subscription()->activate(); +``` ## Handling Paddle Webhooks Paddle can notify your application of a variety of events via webhooks. By default, a route that points to Cashier's webhook controller is registered by the Cashier service provider. This controller will handle all incoming webhook requests. -By default, this controller will automatically handle cancelling subscriptions that have too many failed charges ([as defined by your Paddle subscription settings](https://vendors.paddle.com/subscription-settings)), subscription updates, and payment method changes; however, as we'll soon discover, you can extend this controller to handle any Paddle webhook event you like. +By default, this controller will automatically handle canceling subscriptions that have too many failed charges, subscription updates, and payment method changes; however, as we'll soon discover, you can extend this controller to handle any Paddle webhook event you like. -To ensure your application can handle Paddle webhooks, be sure to [configure the webhook URL in the Paddle control panel](https://vendors.paddle.com/alerts-webhooks). By default, Cashier's webhook controller responds to the `/paddle/webhook` URL path. The full list of all webhooks you should enable in the Paddle control panel are: +To ensure your application can handle Paddle webhooks, be sure to [configure the webhook URL in the Paddle control panel](https://vendors.paddle.com/notifications-v2). By default, Cashier's webhook controller responds to the `/paddle/webhook` URL path. The full list of all webhooks you should enable in the Paddle control panel are: +- Customer Updated +- Transaction Completed +- Transaction Updated - Subscription Created - Subscription Updated -- Subscription Cancelled -- Payment Succeeded -- Subscription Payment Succeeded +- Subscription Paused +- Subscription Canceled -> {note} Make sure you protect incoming requests with Cashier's included [webhook signature verification](/docs/{{version}}/cashier-paddle#verifying-webhook-signatures) middleware. +> [!WARNING] +> Make sure you protect incoming requests with Cashier's included [webhook signature verification](/docs/{{version}}/cashier-paddle#verifying-webhook-signatures) middleware. -#### Webhooks & CSRF Protection +#### Webhooks and CSRF Protection -Since Paddle webhooks need to bypass Laravel's [CSRF protection](/docs/{{version}}/csrf), be sure to list the URI as an exception in your `App\Http\Middleware\VerifyCsrfToken` middleware or list the route outside of the `web` middleware group: +Since Paddle webhooks need to bypass Laravel's [CSRF protection](/docs/{{version}}/csrf), you should ensure that Laravel does not attempt to verify the CSRF token for incoming Paddle webhooks. To accomplish this, you should exclude `paddle/*` from CSRF protection in your application's `bootstrap/app.php` file: - protected $except = [ +```php +->withMiddleware(function (Middleware $middleware): void { + $middleware->validateCsrfTokens(except: [ 'paddle/*', - ]; + ]); +}) +``` -#### Webhooks & Local Development +#### Webhooks and Local Development For Paddle to be able to send your application webhooks during local development, you will need to expose your application via a site sharing service such as [Ngrok](https://ngrok.com/) or [Expose](https://expose.dev/docs/introduction). If you are developing your application locally using [Laravel Sail](/docs/{{version}}/sail), you may use Sail's [site sharing command](/docs/{{version}}/sail#sharing-your-site). ### Defining Webhook Event Handlers -Cashier automatically handles subscription cancellation on failed charges and other common Paddle webhooks. However, if you have additional webhook events you would like to handle, you may do so by listening to the following events that are dispatched by Cashier: +Cashier automatically handles subscription cancelation on failed charges and other common Paddle webhooks. However, if you have additional webhook events you would like to handle, you may do so by listening to the following events that are dispatched by Cashier: - `Laravel\Paddle\Events\WebhookReceived` - `Laravel\Paddle\Events\WebhookHandled` -Both events contain the full payload of the Paddle webhook. For example, if you wish to handle the `invoice.payment_succeeded` webhook, you may register a [listener](/docs/{{version}}/events#defining-listeners) that will handle the event: +Both events contain the full payload of the Paddle webhook. For example, if you wish to handle the `transaction.billed` webhook, you may register a [listener](/docs/{{version}}/events#defining-listeners) that will handle the event: - payload['alert_name'] === 'payment_succeeded') { - // Handle the incoming event... - } + if ($event->payload['event_type'] === 'transaction.billed') { + // Handle the incoming event... } } - -Once your listener has been defined, you may register it within your application's `EventServiceProvider`: - - [ - PaddleEventListener::class, - ], - ]; - } +} +``` Cashier also emit events dedicated to the type of the received webhook. In addition to the full payload from Paddle, they also contain the relevant models that were used to process the webhook such as the billable model, the subscription, or the receipt:
-- `Laravel\Paddle\Events\PaymentSucceeded` -- `Laravel\Paddle\Events\SubscriptionPaymentSucceeded` +- `Laravel\Paddle\Events\CustomerUpdated` +- `Laravel\Paddle\Events\TransactionCompleted` +- `Laravel\Paddle\Events\TransactionUpdated` - `Laravel\Paddle\Events\SubscriptionCreated` - `Laravel\Paddle\Events\SubscriptionUpdated` -- `Laravel\Paddle\Events\SubscriptionCancelled` +- `Laravel\Paddle\Events\SubscriptionPaused` +- `Laravel\Paddle\Events\SubscriptionCanceled`
@@ -1035,175 +1425,156 @@ CASHIER_WEBHOOK=https://example.com/my-paddle-webhook-url ### Verifying Webhook Signatures -To secure your webhooks, you may use [Paddle's webhook signatures](https://developer.paddle.com/webhook-reference/verifying-webhooks). For convenience, Cashier automatically includes a middleware which validates that the incoming Paddle webhook request is valid. +To secure your webhooks, you may use [Paddle's webhook signatures](https://developer.paddle.com/webhooks/signature-verification). For convenience, Cashier automatically includes a middleware which validates that the incoming Paddle webhook request is valid. -To enable webhook verification, ensure that the `PADDLE_PUBLIC_KEY` environment variable is defined in your application's `.env` file. The public key may be retrieved from your Paddle account dashboard. +To enable webhook verification, ensure that the `PADDLE_WEBHOOK_SECRET` environment variable is defined in your application's `.env` file. The webhook secret may be retrieved from your Paddle account dashboard. ## Single Charges - -### Simple Charge + +### Charging for Products -If you would like to make a one-time charge against a customer, you may use the `charge` method on a billable model instance to generate a pay link for the charge. The `charge` method accepts the charge amount (float) as its first argument and a charge description as its second argument: +If you would like to initiate a product purchase for a customer, you may use the `checkout` method on a billable model instance to generate a checkout session for the purchase. The `checkout` method accepts one or multiple price ID's. If necessary, an associative array may be used to provide the quantity of the product that is being purchased: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/store', function (Request $request) { - return view('store', [ - 'payLink' => $user->charge(12.99, 'Action Figure') - ]); - }); +Route::get('/buy', function (Request $request) { + $checkout = $request->user()->checkout(['pri_tshirt', 'pri_socks' => 5]); -After generating the pay link, you may use Cashier's provided `paddle-button` Blade component to allow the user to initiate the Paddle widget and complete the charge: + return view('buy', ['checkout' => $checkout]); +}); +``` + +After generating the checkout session, you may use Cashier's provided `paddle-button` [Blade component](#overlay-checkout) to allow the user to view the Paddle checkout widget and complete the purchase: ```blade - + Buy ``` -The `charge` method accepts an array as its third argument, allowing you to pass any options you wish to the underlying Paddle pay link creation. Please consult [the Paddle documentation](https://developer.paddle.com/api-reference/product-api/pay-links/createpaylink) to learn more about the options available to you when creating charges: +A checkout session has a `customData` method, allowing you to pass any custom data you wish to the underlying transaction creation. Please consult [the Paddle documentation](https://developer.paddle.com/build/transactions/custom-data) to learn more about the options available to you when passing custom data: - $payLink = $user->charge(12.99, 'Action Figure', [ +```php +$checkout = $user->checkout('pri_tshirt') + ->customData([ 'custom_option' => $value, ]); - -Charges happen in the currency specified in the `cashier.currency` configuration option. By default, this is set to USD. You may override the default currency by defining the `CASHIER_CURRENCY` environment variable in your application's `.env` file: - -```ini -CASHIER_CURRENCY=EUR ``` -You can also [override prices per currency](https://developer.paddle.com/api-reference/product-api/pay-links/createpaylink#price-overrides) using Paddle's dynamic pricing matching system. To do so, pass an array of prices instead of a fixed amount: - - $payLink = $user->charge([ - 'USD:19.99', - 'EUR:15.99', - ], 'Action Figure'); + +### Refunding Transactions - -### Charging Products +Refunding transactions will return the refunded amount to your customer's payment method that was used at the time of purchase. If you need to refund a Paddle purchase, you may use the `refund` method on a `Cashier\Paddle\Transaction` model. This method accepts a reason as the first argument, one or more price ID's to refund with optional amounts as an associative array. You may retrieve the transactions for a given billable model using the `transactions` method. -If you would like to make a one-time charge against a specific product configured within Paddle, you may use the `chargeProduct` method on a billable model instance to generate a pay link: +For example, imagine we want to refund a specific transaction for prices `pri_123` and `pri_456`. We want to fully refund `pri_123`, but only refund two dollars for `pri_456`: - use Illuminate\Http\Request; +```php +use App\Models\User; - Route::get('/store', function (Request $request) { - return view('store', [ - 'payLink' => $request->user()->chargeProduct($productId = 123) - ]); - }); +$user = User::find(1); -Then, you may provide the pay link to the `paddle-button` component to allow the user to initialize the Paddle widget: +$transaction = $user->transactions()->first(); -```blade - - Buy - +$response = $transaction->refund('Accidental charge', [ + 'pri_123', // Fully refund this price... + 'pri_456' => 200, // Only partially refund this price... +]); ``` -The `chargeProduct` method accepts an array as its second argument, allowing you to pass any options you wish to the underlying Paddle pay link creation. Please consult [the Paddle documentation](https://developer.paddle.com/api-reference/product-api/pay-links/createpaylink) regarding the options that are available to you when creating charges: - - $payLink = $user->chargeProduct($productId, [ - 'custom_option' => $value, - ]); +The example above refunds specific line items in a transaction. If you want to refund the entire transaction, simply provide a reason: - -### Refunding Orders +```php +$response = $transaction->refund('Accidental charge'); +``` -If you need to refund a Paddle order, you may use the `refund` method. This method accepts the Paddle order ID as its first argument. You may retrieve the receipts for a given billable model using the `receipts` method: +For more information on refunds, please consult [Paddle's refund documentation](https://developer.paddle.com/build/transactions/create-transaction-adjustments). - use App\Models\User; +> [!WARNING] +> Refunds must always be approved by Paddle before fully processing. - $user = User::find(1); + +### Crediting Transactions - $receipt = $user->receipts()->first(); +Just like refunding, you can also credit transactions. Crediting transactions will add the funds to the customer's balance so it may be used for future purchases. Crediting transactions can only be done for manually-collected transactions and not for automatically-collected transactions (like subscriptions) since Paddle handles subscription credits automatically: - $refundRequestId = $user->refund($receipt->order_id); +```php +$transaction = $user->transactions()->first(); -You may optionally specify a specific amount to refund as well as a reason for the refund: +// Credit a specific line item fully... +$response = $transaction->credit('Compensation', 'pri_123'); +``` - $receipt = $user->receipts()->first(); +For more info, [see Paddle's documentation on crediting](https://developer.paddle.com/build/transactions/create-transaction-adjustments). - $refundRequestId = $user->refund( - $receipt->order_id, 5.00, 'Unused product time' - ); +> [!WARNING] +> Credits can only be applied for manually-collected transactions. Automatically-collected transactions are credited by Paddle themselves. -> {tip} You can use the `$refundRequestId` as a reference for the refund when contacting Paddle support. + +## Transactions - -## Receipts +You may easily retrieve an array of a billable model's transactions via the `transactions` property: -You may easily retrieve an array of a billable model's receipts via the `receipts` property: +```php +use App\Models\User; - use App\Models\User; +$user = User::find(1); - $user = User::find(1); +$transactions = $user->transactions; +``` - $receipts = $user->receipts; +Transactions represent payments for your products and purchases and are accompanied by invoices. Only completed transactions are stored in your application's database. -When listing the receipts for the customer, you may use the receipt instance's methods to display the relevant receipt information. For example, you may wish to list every receipt in a table, allowing the user to easily download any of the receipts: +When listing the transactions for a customer, you may use the transaction instance's methods to display the relevant payment information. For example, you may wish to list every transaction in a table, allowing the user to easily download any of the invoices: ```html - @foreach ($receipts as $receipt) + @foreach ($transactions as $transaction) - - - + + + + @endforeach
{{ $receipt->paid_at->toFormattedDateString() }}{{ $receipt->amount() }}Download{{ $transaction->billed_at->toFormattedDateString() }}{{ $transaction->total() }}{{ $transaction->tax() }}Download
``` +The `download-invoice` route may look like the following: + +```php +use Illuminate\Http\Request; +use Laravel\Paddle\Transaction; + +Route::get('/download-invoice/{transaction}', function (Request $request, Transaction $transaction) { + return $transaction->redirectToInvoicePdf(); +})->name('download-invoice'); +``` + -### Past & Upcoming Payments +### Past and Upcoming Payments You may use the `lastPayment` and `nextPayment` methods to retrieve and display a customer's past or upcoming payments for recurring subscriptions: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $subscription = $user->subscription('default'); +$subscription = $user->subscription(); - $lastPayment = $subscription->lastPayment(); - $nextPayment = $subscription->nextPayment(); +$lastPayment = $subscription->lastPayment(); +$nextPayment = $subscription->nextPayment(); +``` -Both of these methods will return an instance of `Laravel\Paddle\Payment`; however, `nextPayment` will return `null` when the billing cycle has ended (such as when a subscription has been cancelled): +Both of these methods will return an instance of `Laravel\Paddle\Payment`; however, `lastPayment` will return `null` when transactions have not been synced by webhooks yet, while `nextPayment` will return `null` when the billing cycle has ended (such as when a subscription has been canceled): ```blade Next payment: {{ $nextPayment->amount() }} due on {{ $nextPayment->date()->format('d/m/Y') }} ``` - -## Handling Failed Payments - -Subscription payments fail for various reasons, such as expired cards or a card having insufficient funds. When this happens, we recommend that you let Paddle handle payment failures for you. Specifically, you may [setup Paddle's automatic billing emails](https://vendors.paddle.com/subscription-settings) in your Paddle dashboard. - -Alternatively, you can perform more precise customization by catching the [`subscription_payment_failed`](https://developer.paddle.com/webhook-reference/subscription-alerts/subscription-payment-failed) webhook and enabling the "Subscription Payment Failed" option in the Webhook settings of your Paddle dashboard: - - ## Testing diff --git a/collections.md b/collections.md index 725992567e3..c159a3ca666 100644 --- a/collections.md +++ b/collections.md @@ -16,11 +16,13 @@ The `Illuminate\Support\Collection` class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We'll use the `collect` helper to create a new collection instance from the array, run the `strtoupper` function on each element, and then remove all empty elements: - $collection = collect(['taylor', 'abigail', null])->map(function ($name) { - return strtoupper($name); - })->reject(function ($name) { - return empty($name); - }); +```php +$collection = collect(['Taylor', 'Abigail', null])->map(function (?string $name) { + return strtoupper($name); +})->reject(function (string $name) { + return empty($name); +}); +``` As you can see, the `Collection` class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every `Collection` method returns an entirely new `Collection` instance. @@ -29,29 +31,36 @@ As you can see, the `Collection` class allows you to chain its methods to perfor As mentioned above, the `collect` helper returns a new `Illuminate\Support\Collection` instance for the given array. So, creating a collection is as simple as: - $collection = collect([1, 2, 3]); +```php +$collection = collect([1, 2, 3]); +``` + +You may also create a collection using the [make](#method-make) and [fromJson](#method-fromjson) methods. -> {tip} The results of [Eloquent](/docs/{{version}}/eloquent) queries are always returned as `Collection` instances. +> [!NOTE] +> The results of [Eloquent](/docs/{{version}}/eloquent) queries are always returned as `Collection` instances. ### Extending Collections Collections are "macroable", which allows you to add additional methods to the `Collection` class at run time. The `Illuminate\Support\Collection` class' `macro` method accepts a closure that will be executed when your macro is called. The macro closure may access the collection's other methods via `$this`, just as if it were a real method of the collection class. For example, the following code adds a `toUpper` method to the `Collection` class: - use Illuminate\Support\Collection; - use Illuminate\Support\Str; +```php +use Illuminate\Support\Collection; +use Illuminate\Support\Str; - Collection::macro('toUpper', function () { - return $this->map(function ($value) { - return Str::upper($value); - }); +Collection::macro('toUpper', function () { + return $this->map(function (string $value) { + return Str::upper($value); }); +}); - $collection = collect(['first', 'second']); +$collection = collect(['first', 'second']); - $upper = $collection->toUpper(); +$upper = $collection->toUpper(); - // ['FIRST', 'SECOND'] +// ['FIRST', 'SECOND'] +``` Typically, you should declare collection macros in the `boot` method of a [service provider](/docs/{{version}}/providers). @@ -60,18 +69,20 @@ Typically, you should declare collection macros in the `boot` method of a [servi If necessary, you may define macros that accept additional arguments: - use Illuminate\Support\Collection; - use Illuminate\Support\Facades\Lang; +```php +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Lang; - Collection::macro('toLocale', function ($locale) { - return $this->map(function ($value) use ($locale) { - return Lang::get($value, [], $locale); - }); +Collection::macro('toLocale', function (string $locale) { + return $this->map(function (string $value) use ($locale) { + return Lang::get($value, [], $locale); }); +}); - $collection = collect(['first', 'second']); +$collection = collect(['first', 'second']); - $translated = $collection->toLocale('es'); +$translated = $collection->toLocale('es'); +``` ## Available Methods @@ -79,28 +90,34 @@ If necessary, you may define macros that accept additional arguments: For the majority of the remaining collection documentation, we'll discuss each method available on the `Collection` class. Remember, all of these methods may be chained to fluently manipulate the underlying array. Furthermore, almost every method returns a new `Collection` instance, allowing you to preserve the original copy of the collection when necessary: -
+
+[after](#method-after) [all](#method-all) [average](#method-average) [avg](#method-avg) +[before](#method-before) [chunk](#method-chunk) [chunkWhile](#method-chunkwhile) [collapse](#method-collapse) +[collapseWithKeys](#method-collapsewithkeys) [collect](#method-collect) [combine](#method-combine) [concat](#method-concat) [contains](#method-contains) +[containsOneItem](#method-containsoneitem) [containsStrict](#method-containsstrict) [count](#method-count) [countBy](#method-countBy) @@ -108,28 +125,38 @@ For the majority of the remaining collection documentation, we'll discuss each m [dd](#method-dd) [diff](#method-diff) [diffAssoc](#method-diffassoc) +[diffAssocUsing](#method-diffassocusing) [diffKeys](#method-diffkeys) [doesntContain](#method-doesntcontain) +[doesntContainStrict](#method-doesntcontainstrict) +[dot](#method-dot) [dump](#method-dump) [duplicates](#method-duplicates) [duplicatesStrict](#method-duplicatesstrict) [each](#method-each) [eachSpread](#method-eachspread) +[ensure](#method-ensure) [every](#method-every) [except](#method-except) [filter](#method-filter) [first](#method-first) +[firstOrFail](#method-first-or-fail) [firstWhere](#method-first-where) [flatMap](#method-flatmap) [flatten](#method-flatten) [flip](#method-flip) [forget](#method-forget) [forPage](#method-forpage) +[fromJson](#method-fromjson) [get](#method-get) [groupBy](#method-groupby) [has](#method-has) +[hasAny](#method-hasany) [implode](#method-implode) [intersect](#method-intersect) +[intersectUsing](#method-intersectusing) +[intersectAssoc](#method-intersectAssoc) +[intersectAssocUsing](#method-intersectassocusing) [intersectByKeys](#method-intersectbykeys) [isEmpty](#method-isempty) [isNotEmpty](#method-isnotempty) @@ -137,6 +164,7 @@ For the majority of the remaining collection documentation, we'll discuss each m [keyBy](#method-keyby) [keys](#method-keys) [last](#method-last) +[lazy](#method-lazy) [macro](#method-macro) [make](#method-make) [map](#method-map) @@ -150,10 +178,12 @@ For the majority of the remaining collection documentation, we'll discuss each m [mergeRecursive](#method-mergerecursive) [min](#method-min) [mode](#method-mode) +[multiply](#method-multiply) [nth](#method-nth) [only](#method-only) [pad](#method-pad) [partition](#method-partition) +[percentage](#method-percentage) [pipe](#method-pipe) [pipeInto](#method-pipeinto) [pipeThrough](#method-pipethrough) @@ -166,20 +196,20 @@ For the majority of the remaining collection documentation, we'll discuss each m [random](#method-random) [range](#method-range) [reduce](#method-reduce) -[reduceMany](#method-reduce-many) [reduceSpread](#method-reduce-spread) [reject](#method-reject) [replace](#method-replace) [replaceRecursive](#method-replacerecursive) [reverse](#method-reverse) [search](#method-search) +[select](#method-select) [shift](#method-shift) [shuffle](#method-shuffle) -[sliding](#method-sliding) [skip](#method-skip) [skipUntil](#method-skipuntil) [skipWhile](#method-skipwhile) [slice](#method-slice) +[sliding](#method-sliding) [sole](#method-sole) [some](#method-some) [sort](#method-sort) @@ -200,6 +230,7 @@ For the majority of the remaining collection documentation, we'll discuss each m [times](#method-times) [toArray](#method-toarray) [toJson](#method-tojson) +[toPrettyJson](#method-to-pretty-json) [transform](#method-transform) [undot](#method-undot) [union](#method-union) @@ -209,6 +240,7 @@ For the majority of the remaining collection documentation, we'll discuss each m [unlessEmpty](#method-unlessempty) [unlessNotEmpty](#method-unlessnotempty) [unwrap](#method-unwrap) +[value](#method-value) [values](#method-values) [when](#method-when) [whenEmpty](#method-whenempty) @@ -242,52 +274,120 @@ For the majority of the remaining collection documentation, we'll discuss each m } + +#### `after()` {.collection-method .first-collection-method} + +The `after` method returns the item after the given item. `null` is returned if the given item is not found or is the last item: + +```php +$collection = collect([1, 2, 3, 4, 5]); + +$collection->after(3); + +// 4 + +$collection->after(5); + +// null +``` + +This method searches for the given item using "loose" comparison, meaning a string containing an integer value will be considered equal to an integer of the same value. To use "strict" comparison, you may provide the `strict` argument to the method: + +```php +collect([2, 4, 6, 8])->after('4', strict: true); + +// null +``` + +Alternatively, you may provide your own closure to search for the first item that passes a given truth test: + +```php +collect([2, 4, 6, 8])->after(function (int $item, int $key) { + return $item > 5; +}); + +// 8 +``` + -#### `all()` {.collection-method .first-collection-method} +#### `all()` {.collection-method} The `all` method returns the underlying array represented by the collection: - collect([1, 2, 3])->all(); +```php +collect([1, 2, 3])->all(); - // [1, 2, 3] +// [1, 2, 3] +``` #### `average()` {.collection-method} -Alias for the [`avg`](#method-avg) method. +Alias for the [avg](#method-avg) method. #### `avg()` {.collection-method} The `avg` method returns the [average value](https://en.wikipedia.org/wiki/Average) of a given key: - $average = collect([ - ['foo' => 10], - ['foo' => 10], - ['foo' => 20], - ['foo' => 40] - ])->avg('foo'); +```php +$average = collect([ + ['foo' => 10], + ['foo' => 10], + ['foo' => 20], + ['foo' => 40] +])->avg('foo'); + +// 20 + +$average = collect([1, 1, 2, 4])->avg(); + +// 2 +``` + + +#### `before()` {.collection-method} + +The `before` method is the opposite of the [after](#method-after) method. It returns the item before the given item. `null` is returned if the given item is not found or is the first item: - // 20 +```php +$collection = collect([1, 2, 3, 4, 5]); - $average = collect([1, 1, 2, 4])->avg(); +$collection->before(3); - // 2 +// 2 + +$collection->before(1); + +// null + +collect([2, 4, 6, 8])->before('4', strict: true); + +// null + +collect([2, 4, 6, 8])->before(function (int $item, int $key) { + return $item > 5; +}); + +// 4 +``` #### `chunk()` {.collection-method} The `chunk` method breaks the collection into multiple, smaller collections of a given size: - $collection = collect([1, 2, 3, 4, 5, 6, 7]); +```php +$collection = collect([1, 2, 3, 4, 5, 6, 7]); - $chunks = $collection->chunk(4); +$chunks = $collection->chunk(4); - $chunks->all(); +$chunks->all(); - // [[1, 2, 3, 4], [5, 6, 7]] +// [[1, 2, 3, 4], [5, 6, 7]] +``` -This method is especially useful in [views](/docs/{{version}}/views) when working with a grid system such as [Bootstrap](https://getbootstrap.com/docs/4.1/layout/grid/). For example, imagine you have a collection of [Eloquent](/docs/{{version}}/eloquent) models you want to display in a grid: +This method is especially useful in [views](/docs/{{version}}/views) when working with a grid system such as [Bootstrap](https://getbootstrap.com/docs/5.3/layout/grid/). For example, imagine you have a collection of [Eloquent](/docs/{{version}}/eloquent) models you want to display in a grid: ```blade @foreach ($products->chunk(3) as $chunk) @@ -304,91 +404,127 @@ This method is especially useful in [views](/docs/{{version}}/views) when workin The `chunkWhile` method breaks the collection into multiple, smaller collections based on the evaluation of the given callback. The `$chunk` variable passed to the closure may be used to inspect the previous element: - $collection = collect(str_split('AABBCCCD')); +```php +$collection = collect(str_split('AABBCCCD')); - $chunks = $collection->chunkWhile(function ($value, $key, $chunk) { - return $value === $chunk->last(); - }); +$chunks = $collection->chunkWhile(function (string $value, int $key, Collection $chunk) { + return $value === $chunk->last(); +}); - $chunks->all(); +$chunks->all(); - // [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']] +// [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']] +``` #### `collapse()` {.collection-method} -The `collapse` method collapses a collection of arrays into a single, flat collection: +The `collapse` method collapses a collection of arrays or collections into a single, flat collection: + +```php +$collection = collect([ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], +]); + +$collapsed = $collection->collapse(); + +$collapsed->all(); + +// [1, 2, 3, 4, 5, 6, 7, 8, 9] +``` + + +#### `collapseWithKeys()` {.collection-method} - $collection = collect([ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9], - ]); +The `collapseWithKeys` method flattens a collection of arrays or collections into a single collection, keeping the original keys intact. If the collection is already flat, it will return an empty collection: - $collapsed = $collection->collapse(); +```php +$collection = collect([ + ['first' => collect([1, 2, 3])], + ['second' => [4, 5, 6]], + ['third' => collect([7, 8, 9])] +]); - $collapsed->all(); +$collapsed = $collection->collapseWithKeys(); - // [1, 2, 3, 4, 5, 6, 7, 8, 9] +$collapsed->all(); + +// [ +// 'first' => [1, 2, 3], +// 'second' => [4, 5, 6], +// 'third' => [7, 8, 9], +// ] +``` #### `collect()` {.collection-method} The `collect` method returns a new `Collection` instance with the items currently in the collection: - $collectionA = collect([1, 2, 3]); +```php +$collectionA = collect([1, 2, 3]); - $collectionB = $collectionA->collect(); +$collectionB = $collectionA->collect(); - $collectionB->all(); +$collectionB->all(); - // [1, 2, 3] +// [1, 2, 3] +``` The `collect` method is primarily useful for converting [lazy collections](#lazy-collections) into standard `Collection` instances: - $lazyCollection = LazyCollection::make(function () { - yield 1; - yield 2; - yield 3; - }); +```php +$lazyCollection = LazyCollection::make(function () { + yield 1; + yield 2; + yield 3; +}); - $collection = $lazyCollection->collect(); +$collection = $lazyCollection->collect(); - get_class($collection); +$collection::class; - // 'Illuminate\Support\Collection' +// 'Illuminate\Support\Collection' - $collection->all(); +$collection->all(); - // [1, 2, 3] +// [1, 2, 3] +``` -> {tip} The `collect` method is especially useful when you have an instance of `Enumerable` and need a non-lazy collection instance. Since `collect()` is part of the `Enumerable` contract, you can safely use it to get a `Collection` instance. +> [!NOTE] +> The `collect` method is especially useful when you have an instance of `Enumerable` and need a non-lazy collection instance. Since `collect()` is part of the `Enumerable` contract, you can safely use it to get a `Collection` instance. #### `combine()` {.collection-method} The `combine` method combines the values of the collection, as keys, with the values of another array or collection: - $collection = collect(['name', 'age']); +```php +$collection = collect(['name', 'age']); - $combined = $collection->combine(['George', 29]); +$combined = $collection->combine(['George', 29]); - $combined->all(); +$combined->all(); - // ['name' => 'George', 'age' => 29] +// ['name' => 'George', 'age' => 29] +``` #### `concat()` {.collection-method} -The `concat` method appends the given `array` or collection's values onto the end of another collection: +The `concat` method appends the given array or collection's values onto the end of another collection: - $collection = collect(['John Doe']); +```php +$collection = collect(['John Doe']); - $concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']); +$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']); - $concatenated->all(); +$concatenated->all(); - // ['John Doe', 'Jane Doe', 'Johnny Doe'] +// ['John Doe', 'Jane Doe', 'Johnny Doe'] +``` The `concat` method numerically reindexes keys for items concatenated onto the original collection. To maintain keys in associative collections, see the [merge](#method-merge) method. @@ -397,384 +533,525 @@ The `concat` method numerically reindexes keys for items concatenated onto the o The `contains` method determines whether the collection contains a given item. You may pass a closure to the `contains` method to determine if an element exists in the collection matching a given truth test: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->contains(function ($value, $key) { - return $value > 5; - }); +$collection->contains(function (int $value, int $key) { + return $value > 5; +}); - // false +// false +``` Alternatively, you may pass a string to the `contains` method to determine whether the collection contains a given item value: - $collection = collect(['name' => 'Desk', 'price' => 100]); +```php +$collection = collect(['name' => 'Desk', 'price' => 100]); - $collection->contains('Desk'); +$collection->contains('Desk'); - // true +// true - $collection->contains('New York'); +$collection->contains('New York'); - // false +// false +``` You may also pass a key / value pair to the `contains` method, which will determine if the given pair exists in the collection: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Chair', 'price' => 100], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Chair', 'price' => 100], +]); - $collection->contains('product', 'Bookcase'); +$collection->contains('product', 'Bookcase'); - // false +// false +``` -The `contains` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [`containsStrict`](#method-containsstrict) method to filter using "strict" comparisons. +The `contains` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [containsStrict](#method-containsstrict) method to filter using "strict" comparisons. For the inverse of `contains`, see the [doesntContain](#method-doesntcontain) method. + +#### `containsOneItem()` {.collection-method} + +The `containsOneItem` method determines whether the collection contains a single item: + +```php +collect([])->containsOneItem(); + +// false + +collect(['1'])->containsOneItem(); + +// true + +collect(['1', '2'])->containsOneItem(); + +// false + +collect([1, 2, 3])->containsOneItem(fn (int $item) => $item === 2); + +// true +``` + #### `containsStrict()` {.collection-method} -This method has the same signature as the [`contains`](#method-contains) method; however, all values are compared using "strict" comparisons. +This method has the same signature as the [contains](#method-contains) method; however, all values are compared using "strict" comparisons. -> {tip} This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-contains). +> [!NOTE] +> This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-contains). #### `count()` {.collection-method} The `count` method returns the total number of items in the collection: - $collection = collect([1, 2, 3, 4]); +```php +$collection = collect([1, 2, 3, 4]); - $collection->count(); +$collection->count(); - // 4 +// 4 +``` #### `countBy()` {.collection-method} The `countBy` method counts the occurrences of values in the collection. By default, the method counts the occurrences of every element, allowing you to count certain "types" of elements in the collection: - $collection = collect([1, 2, 2, 2, 3]); +```php +$collection = collect([1, 2, 2, 2, 3]); - $counted = $collection->countBy(); +$counted = $collection->countBy(); - $counted->all(); +$counted->all(); - // [1 => 1, 2 => 3, 3 => 1] +// [1 => 1, 2 => 3, 3 => 1] +``` -You pass a closure to the `countBy` method to count all items by a custom value: +You may pass a closure to the `countBy` method to count all items by a custom value: - $collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']); +```php +$collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']); - $counted = $collection->countBy(function ($email) { - return substr(strrchr($email, "@"), 1); - }); +$counted = $collection->countBy(function (string $email) { + return substr(strrchr($email, '@'), 1); +}); - $counted->all(); +$counted->all(); - // ['gmail.com' => 2, 'yahoo.com' => 1] +// ['gmail.com' => 2, 'yahoo.com' => 1] +``` #### `crossJoin()` {.collection-method} The `crossJoin` method cross joins the collection's values among the given arrays or collections, returning a Cartesian product with all possible permutations: - $collection = collect([1, 2]); +```php +$collection = collect([1, 2]); - $matrix = $collection->crossJoin(['a', 'b']); +$matrix = $collection->crossJoin(['a', 'b']); - $matrix->all(); +$matrix->all(); - /* - [ - [1, 'a'], - [1, 'b'], - [2, 'a'], - [2, 'b'], - ] - */ +/* + [ + [1, 'a'], + [1, 'b'], + [2, 'a'], + [2, 'b'], + ] +*/ - $collection = collect([1, 2]); +$collection = collect([1, 2]); - $matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']); +$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']); - $matrix->all(); +$matrix->all(); - /* - [ - [1, 'a', 'I'], - [1, 'a', 'II'], - [1, 'b', 'I'], - [1, 'b', 'II'], - [2, 'a', 'I'], - [2, 'a', 'II'], - [2, 'b', 'I'], - [2, 'b', 'II'], - ] - */ +/* + [ + [1, 'a', 'I'], + [1, 'a', 'II'], + [1, 'b', 'I'], + [1, 'b', 'II'], + [2, 'a', 'I'], + [2, 'a', 'II'], + [2, 'b', 'I'], + [2, 'b', 'II'], + ] +*/ +``` #### `dd()` {.collection-method} The `dd` method dumps the collection's items and ends execution of the script: - $collection = collect(['John Doe', 'Jane Doe']); +```php +$collection = collect(['John Doe', 'Jane Doe']); - $collection->dd(); +$collection->dd(); - /* - Collection { - #items: array:2 [ - 0 => "John Doe" - 1 => "Jane Doe" - ] - } - */ +/* + array:2 [ + 0 => "John Doe" + 1 => "Jane Doe" + ] +*/ +``` -If you do not want to stop executing the script, use the [`dump`](#method-dump) method instead. +If you do not want to stop executing the script, use the [dump](#method-dump) method instead. #### `diff()` {.collection-method} The `diff` method compares the collection against another collection or a plain PHP `array` based on its values. This method will return the values in the original collection that are not present in the given collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $diff = $collection->diff([2, 4, 6, 8]); +$diff = $collection->diff([2, 4, 6, 8]); - $diff->all(); +$diff->all(); - // [1, 3, 5] +// [1, 3, 5] +``` -> {tip} This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-diff). +> [!NOTE] +> This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-diff). #### `diffAssoc()` {.collection-method} The `diffAssoc` method compares the collection against another collection or a plain PHP `array` based on its keys and values. This method will return the key / value pairs in the original collection that are not present in the given collection: - $collection = collect([ - 'color' => 'orange', - 'type' => 'fruit', - 'remain' => 6, - ]); +```php +$collection = collect([ + 'color' => 'orange', + 'type' => 'fruit', + 'remain' => 6, +]); - $diff = $collection->diffAssoc([ - 'color' => 'yellow', - 'type' => 'fruit', - 'remain' => 3, - 'used' => 6, - ]); +$diff = $collection->diffAssoc([ + 'color' => 'yellow', + 'type' => 'fruit', + 'remain' => 3, + 'used' => 6, +]); - $diff->all(); +$diff->all(); - // ['color' => 'orange', 'remain' => 6] +// ['color' => 'orange', 'remain' => 6] +``` - -#### `diffKeys()` {.collection-method} + +#### `diffAssocUsing()` {.collection-method} -The `diffKeys` method compares the collection against another collection or a plain PHP `array` based on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection: +Unlike `diffAssoc`, `diffAssocUsing` accepts a user supplied callback function for the indices comparison: - $collection = collect([ - 'one' => 10, - 'two' => 20, - 'three' => 30, - 'four' => 40, - 'five' => 50, - ]); +```php +$collection = collect([ + 'color' => 'orange', + 'type' => 'fruit', + 'remain' => 6, +]); - $diff = $collection->diffKeys([ - 'two' => 2, - 'four' => 4, - 'six' => 6, - 'eight' => 8, - ]); +$diff = $collection->diffAssocUsing([ + 'Color' => 'yellow', + 'Type' => 'fruit', + 'Remain' => 3, +], 'strnatcasecmp'); - $diff->all(); +$diff->all(); + +// ['color' => 'orange', 'remain' => 6] +``` + +The callback must be a comparison function that returns an integer less than, equal to, or greater than zero. For more information, refer to the PHP documentation on [array_diff_uassoc](https://www.php.net/array_diff_uassoc#refsect1-function.array-diff-uassoc-parameters), which is the PHP function that the `diffAssocUsing` method utilizes internally. + + +#### `diffKeys()` {.collection-method} + +The `diffKeys` method compares the collection against another collection or a plain PHP `array` based on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection: - // ['one' => 10, 'three' => 30, 'five' => 50] +```php +$collection = collect([ + 'one' => 10, + 'two' => 20, + 'three' => 30, + 'four' => 40, + 'five' => 50, +]); + +$diff = $collection->diffKeys([ + 'two' => 2, + 'four' => 4, + 'six' => 6, + 'eight' => 8, +]); + +$diff->all(); + +// ['one' => 10, 'three' => 30, 'five' => 50] +``` #### `doesntContain()` {.collection-method} The `doesntContain` method determines whether the collection does not contain a given item. You may pass a closure to the `doesntContain` method to determine if an element does not exist in the collection matching a given truth test: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->doesntContain(function ($value, $key) { - return $value < 5; - }); +$collection->doesntContain(function (int $value, int $key) { + return $value < 5; +}); - // false +// false +``` Alternatively, you may pass a string to the `doesntContain` method to determine whether the collection does not contain a given item value: - $collection = collect(['name' => 'Desk', 'price' => 100]); +```php +$collection = collect(['name' => 'Desk', 'price' => 100]); - $collection->doesntContain('Table'); +$collection->doesntContain('Table'); - // true +// true - $collection->doesntContain('Desk'); +$collection->doesntContain('Desk'); - // false +// false +``` You may also pass a key / value pair to the `doesntContain` method, which will determine if the given pair does not exist in the collection: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Chair', 'price' => 100], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Chair', 'price' => 100], +]); - $collection->doesntContain('product', 'Bookcase'); +$collection->doesntContain('product', 'Bookcase'); - // true +// true +``` The `doesntContain` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. + +#### `doesntContainStrict()` {.collection-method} + +This method has the same signature as the [doesntContain](#method-doesntcontain) method; however, all values are compared using "strict" comparisons. + + +#### `dot()` {.collection-method} + +The `dot` method flattens a multi-dimensional collection into a single level collection that uses "dot" notation to indicate depth: + +```php +$collection = collect(['products' => ['desk' => ['price' => 100]]]); + +$flattened = $collection->dot(); + +$flattened->all(); + +// ['products.desk.price' => 100] +``` + #### `dump()` {.collection-method} The `dump` method dumps the collection's items: - $collection = collect(['John Doe', 'Jane Doe']); +```php +$collection = collect(['John Doe', 'Jane Doe']); - $collection->dump(); +$collection->dump(); - /* - Collection { - #items: array:2 [ - 0 => "John Doe" - 1 => "Jane Doe" - ] - } - */ +/* + array:2 [ + 0 => "John Doe" + 1 => "Jane Doe" + ] +*/ +``` -If you want to stop executing the script after dumping the collection, use the [`dd`](#method-dd) method instead. +If you want to stop executing the script after dumping the collection, use the [dd](#method-dd) method instead. #### `duplicates()` {.collection-method} The `duplicates` method retrieves and returns duplicate values from the collection: - $collection = collect(['a', 'b', 'a', 'c', 'b']); +```php +$collection = collect(['a', 'b', 'a', 'c', 'b']); - $collection->duplicates(); +$collection->duplicates(); - // [2 => 'a', 4 => 'b'] +// [2 => 'a', 4 => 'b'] +``` If the collection contains arrays or objects, you can pass the key of the attributes that you wish to check for duplicate values: - $employees = collect([ - ['email' => 'abigail@example.com', 'position' => 'Developer'], - ['email' => 'james@example.com', 'position' => 'Designer'], - ['email' => 'victoria@example.com', 'position' => 'Developer'], - ]); +```php +$employees = collect([ + ['email' => 'abigail@example.com', 'position' => 'Developer'], + ['email' => 'james@example.com', 'position' => 'Designer'], + ['email' => 'victoria@example.com', 'position' => 'Developer'], +]); - $employees->duplicates('position'); +$employees->duplicates('position'); - // [2 => 'Developer'] +// [2 => 'Developer'] +``` #### `duplicatesStrict()` {.collection-method} -This method has the same signature as the [`duplicates`](#method-duplicates) method; however, all values are compared using "strict" comparisons. +This method has the same signature as the [duplicates](#method-duplicates) method; however, all values are compared using "strict" comparisons. #### `each()` {.collection-method} The `each` method iterates over the items in the collection and passes each item to a closure: - $collection->each(function ($item, $key) { - // - }); +```php +$collection = collect([1, 2, 3, 4]); + +$collection->each(function (int $item, int $key) { + // ... +}); +``` If you would like to stop iterating through the items, you may return `false` from your closure: - $collection->each(function ($item, $key) { - if (/* condition */) { - return false; - } - }); +```php +$collection->each(function (int $item, int $key) { + if (/* condition */) { + return false; + } +}); +``` #### `eachSpread()` {.collection-method} The `eachSpread` method iterates over the collection's items, passing each nested item value into the given callback: - $collection = collect([['John Doe', 35], ['Jane Doe', 33]]); +```php +$collection = collect([['John Doe', 35], ['Jane Doe', 33]]); - $collection->eachSpread(function ($name, $age) { - // - }); +$collection->eachSpread(function (string $name, int $age) { + // ... +}); +``` You may stop iterating through the items by returning `false` from the callback: - $collection->eachSpread(function ($name, $age) { - return false; - }); +```php +$collection->eachSpread(function (string $name, int $age) { + return false; +}); +``` + + +#### `ensure()` {.collection-method} + +The `ensure` method may be used to verify that all elements of a collection are of a given type or list of types. Otherwise, an `UnexpectedValueException` will be thrown: + +```php +return $collection->ensure(User::class); + +return $collection->ensure([User::class, Customer::class]); +``` + +Primitive types such as `string`, `int`, `float`, `bool`, and `array` may also be specified: + +```php +return $collection->ensure('int'); +``` + +> [!WARNING] +> The `ensure` method does not guarantee that elements of different types will not be added to the collection at a later time. #### `every()` {.collection-method} The `every` method may be used to verify that all elements of a collection pass a given truth test: - collect([1, 2, 3, 4])->every(function ($value, $key) { - return $value > 2; - }); +```php +collect([1, 2, 3, 4])->every(function (int $value, int $key) { + return $value > 2; +}); - // false +// false +``` If the collection is empty, the `every` method will return true: - $collection = collect([]); +```php +$collection = collect([]); - $collection->every(function ($value, $key) { - return $value > 2; - }); +$collection->every(function (int $value, int $key) { + return $value > 2; +}); - // true +// true +``` #### `except()` {.collection-method} The `except` method returns all items in the collection except for those with the specified keys: - $collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]); +```php +$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]); - $filtered = $collection->except(['price', 'discount']); +$filtered = $collection->except(['price', 'discount']); - $filtered->all(); +$filtered->all(); - // ['product_id' => 1] +// ['product_id' => 1] +``` For the inverse of `except`, see the [only](#method-only) method. -> {tip} This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-except). +> [!NOTE] +> This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-except). #### `filter()` {.collection-method} The `filter` method filters the collection using the given callback, keeping only those items that pass a given truth test: - $collection = collect([1, 2, 3, 4]); +```php +$collection = collect([1, 2, 3, 4]); - $filtered = $collection->filter(function ($value, $key) { - return $value > 2; - }); +$filtered = $collection->filter(function (int $value, int $key) { + return $value > 2; +}); - $filtered->all(); +$filtered->all(); - // [3, 4] +// [3, 4] +``` If no callback is supplied, all entries of the collection that are equivalent to `false` will be removed: - $collection = collect([1, 2, 3, null, false, '', 0, []]); +```php +$collection = collect([1, 2, 3, null, false, '', 0, []]); - $collection->filter()->all(); +$collection->filter()->all(); - // [1, 2, 3] +// [1, 2, 3] +``` For the inverse of `filter`, see the [reject](#method-reject) method. @@ -783,110 +1060,147 @@ For the inverse of `filter`, see the [reject](#method-reject) method. The `first` method returns the first element in the collection that passes a given truth test: - collect([1, 2, 3, 4])->first(function ($value, $key) { - return $value > 2; - }); +```php +collect([1, 2, 3, 4])->first(function (int $value, int $key) { + return $value > 2; +}); - // 3 +// 3 +``` You may also call the `first` method with no arguments to get the first element in the collection. If the collection is empty, `null` is returned: - collect([1, 2, 3, 4])->first(); +```php +collect([1, 2, 3, 4])->first(); + +// 1 +``` + + +#### `firstOrFail()` {.collection-method} + +The `firstOrFail` method is identical to the `first` method; however, if no result is found, an `Illuminate\Support\ItemNotFoundException` exception will be thrown: + +```php +collect([1, 2, 3, 4])->firstOrFail(function (int $value, int $key) { + return $value > 5; +}); + +// Throws ItemNotFoundException... +``` + +You may also call the `firstOrFail` method with no arguments to get the first element in the collection. If the collection is empty, an `Illuminate\Support\ItemNotFoundException` exception will be thrown: - // 1 +```php +collect([])->firstOrFail(); + +// Throws ItemNotFoundException... +``` #### `firstWhere()` {.collection-method} The `firstWhere` method returns the first element in the collection with the given key / value pair: - $collection = collect([ - ['name' => 'Regena', 'age' => null], - ['name' => 'Linda', 'age' => 14], - ['name' => 'Diego', 'age' => 23], - ['name' => 'Linda', 'age' => 84], - ]); +```php +$collection = collect([ + ['name' => 'Regena', 'age' => null], + ['name' => 'Linda', 'age' => 14], + ['name' => 'Diego', 'age' => 23], + ['name' => 'Linda', 'age' => 84], +]); - $collection->firstWhere('name', 'Linda'); +$collection->firstWhere('name', 'Linda'); - // ['name' => 'Linda', 'age' => 14] +// ['name' => 'Linda', 'age' => 14] +``` You may also call the `firstWhere` method with a comparison operator: - $collection->firstWhere('age', '>=', 18); +```php +$collection->firstWhere('age', '>=', 18); - // ['name' => 'Diego', 'age' => 23] +// ['name' => 'Diego', 'age' => 23] +``` Like the [where](#method-where) method, you may pass one argument to the `firstWhere` method. In this scenario, the `firstWhere` method will return the first item where the given item key's value is "truthy": - $collection->firstWhere('age'); +```php +$collection->firstWhere('age'); - // ['name' => 'Linda', 'age' => 14] +// ['name' => 'Linda', 'age' => 14] +``` #### `flatMap()` {.collection-method} The `flatMap` method iterates through the collection and passes each value to the given closure. The closure is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by one level: - $collection = collect([ - ['name' => 'Sally'], - ['school' => 'Arkansas'], - ['age' => 28] - ]); +```php +$collection = collect([ + ['name' => 'Sally'], + ['school' => 'Arkansas'], + ['age' => 28] +]); - $flattened = $collection->flatMap(function ($values) { - return array_map('strtoupper', $values); - }); +$flattened = $collection->flatMap(function (array $values) { + return array_map('strtoupper', $values); +}); - $flattened->all(); +$flattened->all(); - // ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28']; +// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28']; +``` #### `flatten()` {.collection-method} The `flatten` method flattens a multi-dimensional collection into a single dimension: - $collection = collect([ - 'name' => 'taylor', - 'languages' => [ - 'php', 'javascript' - ] - ]); +```php +$collection = collect([ + 'name' => 'Taylor', + 'languages' => [ + 'PHP', 'JavaScript' + ] +]); - $flattened = $collection->flatten(); +$flattened = $collection->flatten(); - $flattened->all(); +$flattened->all(); - // ['taylor', 'php', 'javascript']; +// ['Taylor', 'PHP', 'JavaScript']; +``` If necessary, you may pass the `flatten` method a "depth" argument: - $collection = collect([ - 'Apple' => [ - [ - 'name' => 'iPhone 6S', - 'brand' => 'Apple' - ], +```php +$collection = collect([ + 'Apple' => [ + [ + 'name' => 'iPhone 6S', + 'brand' => 'Apple' ], - 'Samsung' => [ - [ - 'name' => 'Galaxy S7', - 'brand' => 'Samsung' - ], + ], + 'Samsung' => [ + [ + 'name' => 'Galaxy S7', + 'brand' => 'Samsung' ], - ]); + ], +]); - $products = $collection->flatten(1); +$products = $collection->flatten(1); - $products->values()->all(); +$products->values()->all(); - /* - [ - ['name' => 'iPhone 6S', 'brand' => 'Apple'], - ['name' => 'Galaxy S7', 'brand' => 'Samsung'], - ] - */ +/* + [ + ['name' => 'iPhone 6S', 'brand' => 'Apple'], + ['name' => 'Galaxy S7', 'brand' => 'Samsung'], + ] +*/ +``` In this example, calling `flatten` without providing the depth would have also flattened the nested arrays, resulting in `['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']`. Providing a depth allows you to specify the number of levels nested arrays will be flattened. @@ -895,322 +1209,510 @@ In this example, calling `flatten` without providing the depth would have also f The `flip` method swaps the collection's keys with their corresponding values: - $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); +```php +$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']); - $flipped = $collection->flip(); +$flipped = $collection->flip(); - $flipped->all(); +$flipped->all(); - // ['taylor' => 'name', 'laravel' => 'framework'] +// ['Taylor' => 'name', 'Laravel' => 'framework'] +``` #### `forget()` {.collection-method} The `forget` method removes an item from the collection by its key: - $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); +```php +$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']); - $collection->forget('name'); +// Forget a single key... +$collection->forget('name'); - $collection->all(); +// ['framework' => 'Laravel'] - // ['framework' => 'laravel'] +// Forget multiple keys... +$collection->forget(['name', 'framework']); -> {note} Unlike most other collection methods, `forget` does not return a new modified collection; it modifies the collection it is called on. +// [] +``` + +> [!WARNING] +> Unlike most other collection methods, `forget` does not return a new modified collection; it modifies and returns the collection it is called on. #### `forPage()` {.collection-method} The `forPage` method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument: - $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]); +```php +$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]); + +$chunk = $collection->forPage(2, 3); + +$chunk->all(); - $chunk = $collection->forPage(2, 3); +// [4, 5, 6] +``` + + +#### `fromJson()` {.collection-method} + +The static `fromJson` method creates a new collection instance by decoding a given JSON string using the `json_decode` PHP function: + +```php +use Illuminate\Support\Collection; - $chunk->all(); +$json = json_encode([ + 'name' => 'Taylor Otwell', + 'role' => 'Developer', + 'status' => 'Active', +]); - // [4, 5, 6] +$collection = Collection::fromJson($json); +``` #### `get()` {.collection-method} The `get` method returns the item at a given key. If the key does not exist, `null` is returned: - $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); +```php +$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']); - $value = $collection->get('name'); +$value = $collection->get('name'); - // taylor +// Taylor +``` You may optionally pass a default value as the second argument: - $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); +```php +$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']); - $value = $collection->get('age', 34); +$value = $collection->get('age', 34); - // 34 +// 34 +``` You may even pass a callback as the method's default value. The result of the callback will be returned if the specified key does not exist: - $collection->get('email', function () { - return 'taylor@example.com'; - }); +```php +$collection->get('email', function () { + return 'taylor@example.com'; +}); - // taylor@example.com +// taylor@example.com +``` #### `groupBy()` {.collection-method} The `groupBy` method groups the collection's items by a given key: - $collection = collect([ - ['account_id' => 'account-x10', 'product' => 'Chair'], - ['account_id' => 'account-x10', 'product' => 'Bookcase'], - ['account_id' => 'account-x11', 'product' => 'Desk'], - ]); +```php +$collection = collect([ + ['account_id' => 'account-x10', 'product' => 'Chair'], + ['account_id' => 'account-x10', 'product' => 'Bookcase'], + ['account_id' => 'account-x11', 'product' => 'Desk'], +]); - $grouped = $collection->groupBy('account_id'); +$grouped = $collection->groupBy('account_id'); - $grouped->all(); +$grouped->all(); - /* - [ - 'account-x10' => [ - ['account_id' => 'account-x10', 'product' => 'Chair'], - ['account_id' => 'account-x10', 'product' => 'Bookcase'], - ], - 'account-x11' => [ - ['account_id' => 'account-x11', 'product' => 'Desk'], - ], - ] - */ +/* + [ + 'account-x10' => [ + ['account_id' => 'account-x10', 'product' => 'Chair'], + ['account_id' => 'account-x10', 'product' => 'Bookcase'], + ], + 'account-x11' => [ + ['account_id' => 'account-x11', 'product' => 'Desk'], + ], + ] +*/ +``` Instead of passing a string `key`, you may pass a callback. The callback should return the value you wish to key the group by: - $grouped = $collection->groupBy(function ($item, $key) { - return substr($item['account_id'], -3); - }); +```php +$grouped = $collection->groupBy(function (array $item, int $key) { + return substr($item['account_id'], -3); +}); - $grouped->all(); +$grouped->all(); - /* - [ - 'x10' => [ - ['account_id' => 'account-x10', 'product' => 'Chair'], - ['account_id' => 'account-x10', 'product' => 'Bookcase'], - ], - 'x11' => [ - ['account_id' => 'account-x11', 'product' => 'Desk'], - ], - ] - */ +/* + [ + 'x10' => [ + ['account_id' => 'account-x10', 'product' => 'Chair'], + ['account_id' => 'account-x10', 'product' => 'Bookcase'], + ], + 'x11' => [ + ['account_id' => 'account-x11', 'product' => 'Desk'], + ], + ] +*/ +``` Multiple grouping criteria may be passed as an array. Each array element will be applied to the corresponding level within a multi-dimensional array: - $data = new Collection([ - 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], - 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], - 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']], - 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']], - ]); - - $result = $data->groupBy(['skill', function ($item) { - return $item['roles']; - }], $preserveKeys = true); - - /* - [ - 1 => [ - 'Role_1' => [ - 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], - 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], - ], - 'Role_2' => [ - 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], - ], - 'Role_3' => [ - 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], - ], +```php +$data = new Collection([ + 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], + 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], + 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']], + 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']], +]); + +$result = $data->groupBy(['skill', function (array $item) { + return $item['roles']; +}], preserveKeys: true); + +/* +[ + 1 => [ + 'Role_1' => [ + 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], + 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], + ], + 'Role_2' => [ + 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], ], - 2 => [ - 'Role_1' => [ - 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']], - ], - 'Role_2' => [ - 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']], - ], + 'Role_3' => [ + 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], ], - ]; - */ + ], + 2 => [ + 'Role_1' => [ + 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']], + ], + 'Role_2' => [ + 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']], + ], + ], +]; +*/ +``` #### `has()` {.collection-method} The `has` method determines if a given key exists in the collection: - $collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]); +```php +$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]); + +$collection->has('product'); + +// true + +$collection->has(['product', 'amount']); + +// true + +$collection->has(['amount', 'price']); - $collection->has('product'); +// false +``` + + +#### `hasAny()` {.collection-method} - // true +The `hasAny` method determines whether any of the given keys exist in the collection: - $collection->has(['product', 'amount']); +```php +$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]); - // true +$collection->hasAny(['product', 'price']); - $collection->has(['amount', 'price']); +// true - // false +$collection->hasAny(['name', 'price']); + +// false +``` #### `implode()` {.collection-method} The `implode` method joins items in a collection. Its arguments depend on the type of items in the collection. If the collection contains arrays or objects, you should pass the key of the attributes you wish to join, and the "glue" string you wish to place between the values: - $collection = collect([ - ['account_id' => 1, 'product' => 'Desk'], - ['account_id' => 2, 'product' => 'Chair'], - ]); +```php +$collection = collect([ + ['account_id' => 1, 'product' => 'Desk'], + ['account_id' => 2, 'product' => 'Chair'], +]); - $collection->implode('product', ', '); +$collection->implode('product', ', '); - // Desk, Chair +// 'Desk, Chair' +``` If the collection contains simple strings or numeric values, you should pass the "glue" as the only argument to the method: - collect([1, 2, 3, 4, 5])->implode('-'); +```php +collect([1, 2, 3, 4, 5])->implode('-'); + +// '1-2-3-4-5' +``` + +You may pass a closure to the `implode` method if you would like to format the values being imploded: - // '1-2-3-4-5' +```php +$collection->implode(function (array $item, int $key) { + return strtoupper($item['product']); +}, ', '); + +// 'DESK, CHAIR' +``` #### `intersect()` {.collection-method} -The `intersect` method removes any values from the original collection that are not present in the given `array` or collection. The resulting collection will preserve the original collection's keys: +The `intersect` method removes any values from the original collection that are not present in the given array or collection. The resulting collection will preserve the original collection's keys: + +```php +$collection = collect(['Desk', 'Sofa', 'Chair']); + +$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']); + +$intersect->all(); + +// [0 => 'Desk', 2 => 'Chair'] +``` + +> [!NOTE] +> This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-intersect). - $collection = collect(['Desk', 'Sofa', 'Chair']); + +#### `intersectUsing()` {.collection-method} - $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']); +The `intersectUsing` method removes any values from the original collection that are not present in the given array or collection, using a custom callback to compare the values. The resulting collection will preserve the original collection's keys: - $intersect->all(); +```php +$collection = collect(['Desk', 'Sofa', 'Chair']); - // [0 => 'Desk', 2 => 'Chair'] +$intersect = $collection->intersectUsing(['desk', 'chair', 'bookcase'], function (string $a, string $b) { + return strcasecmp($a, $b); +}); -> {tip} This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-intersect). +$intersect->all(); + +// [0 => 'Desk', 2 => 'Chair'] +``` + + +#### `intersectAssoc()` {.collection-method} + +The `intersectAssoc` method compares the original collection against another collection or array, returning the key / value pairs that are present in all of the given collections: + +```php +$collection = collect([ + 'color' => 'red', + 'size' => 'M', + 'material' => 'cotton' +]); + +$intersect = $collection->intersectAssoc([ + 'color' => 'blue', + 'size' => 'M', + 'material' => 'polyester' +]); + +$intersect->all(); + +// ['size' => 'M'] +``` + + +#### `intersectAssocUsing()` {.collection-method} + +The `intersectAssocUsing` method compares the original collection against another collection or array, returning the key / value pairs that are present in both, using a custom comparison callback to determine equality for both keys and values: + +```php +$collection = collect([ + 'color' => 'red', + 'Size' => 'M', + 'material' => 'cotton', +]); + +$intersect = $collection->intersectAssocUsing([ + 'color' => 'blue', + 'size' => 'M', + 'material' => 'polyester', +], function (string $a, string $b) { + return strcasecmp($a, $b); +}); + +$intersect->all(); + +// ['Size' => 'M'] +``` #### `intersectByKeys()` {.collection-method} -The `intersectByKeys` method removes any keys and their corresponding values from the original collection that are not present in the given `array` or collection: +The `intersectByKeys` method removes any keys and their corresponding values from the original collection that are not present in the given array or collection: - $collection = collect([ - 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009, - ]); +```php +$collection = collect([ + 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009, +]); - $intersect = $collection->intersectByKeys([ - 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011, - ]); +$intersect = $collection->intersectByKeys([ + 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011, +]); - $intersect->all(); +$intersect->all(); - // ['type' => 'screen', 'year' => 2009] +// ['type' => 'screen', 'year' => 2009] +``` #### `isEmpty()` {.collection-method} The `isEmpty` method returns `true` if the collection is empty; otherwise, `false` is returned: - collect([])->isEmpty(); +```php +collect([])->isEmpty(); - // true +// true +``` #### `isNotEmpty()` {.collection-method} The `isNotEmpty` method returns `true` if the collection is not empty; otherwise, `false` is returned: - collect([])->isNotEmpty(); +```php +collect([])->isNotEmpty(); - // false +// false +``` #### `join()` {.collection-method} The `join` method joins the collection's values with a string. Using this method's second argument, you may also specify how the final element should be appended to the string: - collect(['a', 'b', 'c'])->join(', '); // 'a, b, c' - collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c' - collect(['a', 'b'])->join(', ', ' and '); // 'a and b' - collect(['a'])->join(', ', ' and '); // 'a' - collect([])->join(', ', ' and '); // '' +```php +collect(['a', 'b', 'c'])->join(', '); // 'a, b, c' +collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c' +collect(['a', 'b'])->join(', ', ' and '); // 'a and b' +collect(['a'])->join(', ', ' and '); // 'a' +collect([])->join(', ', ' and '); // '' +``` #### `keyBy()` {.collection-method} The `keyBy` method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection: - $collection = collect([ - ['product_id' => 'prod-100', 'name' => 'Desk'], - ['product_id' => 'prod-200', 'name' => 'Chair'], - ]); +```php +$collection = collect([ + ['product_id' => 'prod-100', 'name' => 'Desk'], + ['product_id' => 'prod-200', 'name' => 'Chair'], +]); - $keyed = $collection->keyBy('product_id'); +$keyed = $collection->keyBy('product_id'); - $keyed->all(); +$keyed->all(); - /* - [ - 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], - 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], - ] - */ +/* + [ + 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], + 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], + ] +*/ +``` You may also pass a callback to the method. The callback should return the value to key the collection by: - $keyed = $collection->keyBy(function ($item) { - return strtoupper($item['product_id']); - }); +```php +$keyed = $collection->keyBy(function (array $item, int $key) { + return strtoupper($item['product_id']); +}); - $keyed->all(); +$keyed->all(); - /* - [ - 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], - 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], - ] - */ +/* + [ + 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], + 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], + ] +*/ +``` #### `keys()` {.collection-method} The `keys` method returns all of the collection's keys: - $collection = collect([ - 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], - 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], - ]); +```php +$collection = collect([ + 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], + 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], +]); - $keys = $collection->keys(); +$keys = $collection->keys(); - $keys->all(); +$keys->all(); - // ['prod-100', 'prod-200'] +// ['prod-100', 'prod-200'] +``` #### `last()` {.collection-method} The `last` method returns the last element in the collection that passes a given truth test: - collect([1, 2, 3, 4])->last(function ($value, $key) { - return $value < 3; - }); +```php +collect([1, 2, 3, 4])->last(function (int $value, int $key) { + return $value < 3; +}); - // 2 +// 2 +``` You may also call the `last` method with no arguments to get the last element in the collection. If the collection is empty, `null` is returned: - collect([1, 2, 3, 4])->last(); +```php +collect([1, 2, 3, 4])->last(); + +// 4 +``` + + +#### `lazy()` {.collection-method} + +The `lazy` method returns a new [LazyCollection](#lazy-collections) instance from the underlying array of items: + +```php +$lazyCollection = collect([1, 2, 3, 4])->lazy(); + +$lazyCollection::class; + +// Illuminate\Support\LazyCollection + +$lazyCollection->all(); + +// [1, 2, 3, 4] +``` + +This is especially useful when you need to perform transformations on a huge `Collection` that contains many items: + +```php +$count = $hugeCollection + ->lazy() + ->where('country', 'FR') + ->where('balance', '>', '100') + ->count(); +``` - // 4 +By converting the collection to a `LazyCollection`, we avoid having to allocate a ton of additional memory. Though the original collection still keeps _its_ values in memory, the subsequent filters will not. Therefore, virtually no additional memory will be allocated when filtering the collection's results. #### `macro()` {.collection-method} @@ -1222,282 +1724,339 @@ The static `macro` method allows you to add methods to the `Collection` class at The static `make` method creates a new collection instance. See the [Creating Collections](#creating-collections) section. +```php +use Illuminate\Support\Collection; + +$collection = Collection::make([1, 2, 3]); +``` + #### `map()` {.collection-method} The `map` method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $multiplied = $collection->map(function ($item, $key) { - return $item * 2; - }); +$multiplied = $collection->map(function (int $item, int $key) { + return $item * 2; +}); - $multiplied->all(); +$multiplied->all(); - // [2, 4, 6, 8, 10] +// [2, 4, 6, 8, 10] +``` -> {note} Like most other collection methods, `map` returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the [`transform`](#method-transform) method. +> [!WARNING] +> Like most other collection methods, `map` returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the [transform](#method-transform) method. #### `mapInto()` {.collection-method} The `mapInto()` method iterates over the collection, creating a new instance of the given class by passing the value into the constructor: - class Currency - { - /** - * Create a new currency instance. - * - * @param string $code - * @return void - */ - function __construct(string $code) - { - $this->code = $code; - } - } +```php +class Currency +{ + /** + * Create a new currency instance. + */ + function __construct( + public string $code, + ) {} +} - $collection = collect(['USD', 'EUR', 'GBP']); +$collection = collect(['USD', 'EUR', 'GBP']); - $currencies = $collection->mapInto(Currency::class); +$currencies = $collection->mapInto(Currency::class); - $currencies->all(); +$currencies->all(); - // [Currency('USD'), Currency('EUR'), Currency('GBP')] +// [Currency('USD'), Currency('EUR'), Currency('GBP')] +``` #### `mapSpread()` {.collection-method} The `mapSpread` method iterates over the collection's items, passing each nested item value into the given closure. The closure is free to modify the item and return it, thus forming a new collection of modified items: - $collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); +```php +$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - $chunks = $collection->chunk(2); +$chunks = $collection->chunk(2); - $sequence = $chunks->mapSpread(function ($even, $odd) { - return $even + $odd; - }); +$sequence = $chunks->mapSpread(function (int $even, int $odd) { + return $even + $odd; +}); - $sequence->all(); +$sequence->all(); - // [1, 5, 9, 13, 17] +// [1, 5, 9, 13, 17] +``` #### `mapToGroups()` {.collection-method} The `mapToGroups` method groups the collection's items by the given closure. The closure should return an associative array containing a single key / value pair, thus forming a new collection of grouped values: - $collection = collect([ - [ - 'name' => 'John Doe', - 'department' => 'Sales', - ], - [ - 'name' => 'Jane Doe', - 'department' => 'Sales', - ], - [ - 'name' => 'Johnny Doe', - 'department' => 'Marketing', - ] - ]); +```php +$collection = collect([ + [ + 'name' => 'John Doe', + 'department' => 'Sales', + ], + [ + 'name' => 'Jane Doe', + 'department' => 'Sales', + ], + [ + 'name' => 'Johnny Doe', + 'department' => 'Marketing', + ] +]); - $grouped = $collection->mapToGroups(function ($item, $key) { - return [$item['department'] => $item['name']]; - }); +$grouped = $collection->mapToGroups(function (array $item, int $key) { + return [$item['department'] => $item['name']]; +}); - $grouped->all(); +$grouped->all(); - /* - [ - 'Sales' => ['John Doe', 'Jane Doe'], - 'Marketing' => ['Johnny Doe'], - ] - */ +/* + [ + 'Sales' => ['John Doe', 'Jane Doe'], + 'Marketing' => ['Johnny Doe'], + ] +*/ - $grouped->get('Sales')->all(); +$grouped->get('Sales')->all(); - // ['John Doe', 'Jane Doe'] +// ['John Doe', 'Jane Doe'] +``` #### `mapWithKeys()` {.collection-method} The `mapWithKeys` method iterates through the collection and passes each value to the given callback. The callback should return an associative array containing a single key / value pair: - $collection = collect([ - [ - 'name' => 'John', - 'department' => 'Sales', - 'email' => 'john@example.com', - ], - [ - 'name' => 'Jane', - 'department' => 'Marketing', - 'email' => 'jane@example.com', - ] - ]); - - $keyed = $collection->mapWithKeys(function ($item, $key) { - return [$item['email'] => $item['name']]; - }); +```php +$collection = collect([ + [ + 'name' => 'John', + 'department' => 'Sales', + 'email' => 'john@example.com', + ], + [ + 'name' => 'Jane', + 'department' => 'Marketing', + 'email' => 'jane@example.com', + ] +]); - $keyed->all(); +$keyed = $collection->mapWithKeys(function (array $item, int $key) { + return [$item['email'] => $item['name']]; +}); - /* - [ - 'john@example.com' => 'John', - 'jane@example.com' => 'Jane', - ] - */ +$keyed->all(); + +/* + [ + 'john@example.com' => 'John', + 'jane@example.com' => 'Jane', + ] +*/ +``` #### `max()` {.collection-method} The `max` method returns the maximum value of a given key: - $max = collect([ - ['foo' => 10], - ['foo' => 20] - ])->max('foo'); +```php +$max = collect([ + ['foo' => 10], + ['foo' => 20] +])->max('foo'); - // 20 +// 20 - $max = collect([1, 2, 3, 4, 5])->max(); +$max = collect([1, 2, 3, 4, 5])->max(); - // 5 +// 5 +``` #### `median()` {.collection-method} The `median` method returns the [median value](https://en.wikipedia.org/wiki/Median) of a given key: - $median = collect([ - ['foo' => 10], - ['foo' => 10], - ['foo' => 20], - ['foo' => 40] - ])->median('foo'); +```php +$median = collect([ + ['foo' => 10], + ['foo' => 10], + ['foo' => 20], + ['foo' => 40] +])->median('foo'); - // 15 +// 15 - $median = collect([1, 1, 2, 4])->median(); +$median = collect([1, 1, 2, 4])->median(); - // 1.5 +// 1.5 +``` #### `merge()` {.collection-method} -The `merge` method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection: +The `merge` method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given item's value will overwrite the value in the original collection: - $collection = collect(['product_id' => 1, 'price' => 100]); +```php +$collection = collect(['product_id' => 1, 'price' => 100]); - $merged = $collection->merge(['price' => 200, 'discount' => false]); +$merged = $collection->merge(['price' => 200, 'discount' => false]); - $merged->all(); +$merged->all(); - // ['product_id' => 1, 'price' => 200, 'discount' => false] +// ['product_id' => 1, 'price' => 200, 'discount' => false] +``` -If the given items's keys are numeric, the values will be appended to the end of the collection: +If the given item's keys are numeric, the values will be appended to the end of the collection: - $collection = collect(['Desk', 'Chair']); +```php +$collection = collect(['Desk', 'Chair']); - $merged = $collection->merge(['Bookcase', 'Door']); +$merged = $collection->merge(['Bookcase', 'Door']); - $merged->all(); +$merged->all(); - // ['Desk', 'Chair', 'Bookcase', 'Door'] +// ['Desk', 'Chair', 'Bookcase', 'Door'] +``` #### `mergeRecursive()` {.collection-method} The `mergeRecursive` method merges the given array or collection recursively with the original collection. If a string key in the given items matches a string key in the original collection, then the values for these keys are merged together into an array, and this is done recursively: - $collection = collect(['product_id' => 1, 'price' => 100]); +```php +$collection = collect(['product_id' => 1, 'price' => 100]); - $merged = $collection->mergeRecursive([ - 'product_id' => 2, - 'price' => 200, - 'discount' => false - ]); +$merged = $collection->mergeRecursive([ + 'product_id' => 2, + 'price' => 200, + 'discount' => false +]); - $merged->all(); +$merged->all(); - // ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false] +// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false] +``` #### `min()` {.collection-method} The `min` method returns the minimum value of a given key: - $min = collect([['foo' => 10], ['foo' => 20]])->min('foo'); +```php +$min = collect([['foo' => 10], ['foo' => 20]])->min('foo'); - // 10 +// 10 - $min = collect([1, 2, 3, 4, 5])->min(); +$min = collect([1, 2, 3, 4, 5])->min(); - // 1 +// 1 +``` #### `mode()` {.collection-method} The `mode` method returns the [mode value](https://en.wikipedia.org/wiki/Mode_(statistics)) of a given key: - $mode = collect([ - ['foo' => 10], - ['foo' => 10], - ['foo' => 20], - ['foo' => 40] - ])->mode('foo'); +```php +$mode = collect([ + ['foo' => 10], + ['foo' => 10], + ['foo' => 20], + ['foo' => 40] +])->mode('foo'); + +// [10] - // [10] +$mode = collect([1, 1, 2, 4])->mode(); - $mode = collect([1, 1, 2, 4])->mode(); +// [1] - // [1] +$mode = collect([1, 1, 2, 2])->mode(); + +// [1, 2] +``` - $mode = collect([1, 1, 2, 2])->mode(); + +#### `multiply()` {.collection-method} - // [1, 2] +The `multiply` method creates the specified number of copies of all items in the collection: + +```php +$users = collect([ + ['name' => 'User #1', 'email' => 'user1@example.com'], + ['name' => 'User #2', 'email' => 'user2@example.com'], +])->multiply(3); + +/* + [ + ['name' => 'User #1', 'email' => 'user1@example.com'], + ['name' => 'User #2', 'email' => 'user2@example.com'], + ['name' => 'User #1', 'email' => 'user1@example.com'], + ['name' => 'User #2', 'email' => 'user2@example.com'], + ['name' => 'User #1', 'email' => 'user1@example.com'], + ['name' => 'User #2', 'email' => 'user2@example.com'], + ] +*/ +``` #### `nth()` {.collection-method} The `nth` method creates a new collection consisting of every n-th element: - $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); +```php +$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); - $collection->nth(4); +$collection->nth(4); - // ['a', 'e'] +// ['a', 'e'] +``` You may optionally pass a starting offset as the second argument: - $collection->nth(4, 1); +```php +$collection->nth(4, 1); - // ['b', 'f'] +// ['b', 'f'] +``` #### `only()` {.collection-method} The `only` method returns the items in the collection with the specified keys: - $collection = collect([ - 'product_id' => 1, - 'name' => 'Desk', - 'price' => 100, - 'discount' => false - ]); +```php +$collection = collect([ + 'product_id' => 1, + 'name' => 'Desk', + 'price' => 100, + 'discount' => false +]); - $filtered = $collection->only(['product_id', 'name']); +$filtered = $collection->only(['product_id', 'name']); - $filtered->all(); +$filtered->all(); - // ['product_id' => 1, 'name' => 'Desk'] +// ['product_id' => 1, 'name' => 'Desk'] +``` For the inverse of `only`, see the [except](#method-except) method. -> {tip} This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-only). +> [!NOTE] +> This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-only). #### `pad()` {.collection-method} @@ -1506,1681 +2065,1970 @@ The `pad` method will fill the array with the given value until the array reache To pad to the left, you should specify a negative size. No padding will take place if the absolute value of the given size is less than or equal to the length of the array: - $collection = collect(['A', 'B', 'C']); +```php +$collection = collect(['A', 'B', 'C']); - $filtered = $collection->pad(5, 0); +$filtered = $collection->pad(5, 0); - $filtered->all(); +$filtered->all(); - // ['A', 'B', 'C', 0, 0] +// ['A', 'B', 'C', 0, 0] - $filtered = $collection->pad(-5, 0); +$filtered = $collection->pad(-5, 0); - $filtered->all(); +$filtered->all(); - // [0, 0, 'A', 'B', 'C'] +// [0, 0, 'A', 'B', 'C'] +``` #### `partition()` {.collection-method} The `partition` method may be combined with PHP array destructuring to separate elements that pass a given truth test from those that do not: - $collection = collect([1, 2, 3, 4, 5, 6]); +```php +$collection = collect([1, 2, 3, 4, 5, 6]); - [$underThree, $equalOrAboveThree] = $collection->partition(function ($i) { - return $i < 3; - }); +[$underThree, $equalOrAboveThree] = $collection->partition(function (int $i) { + return $i < 3; +}); + +$underThree->all(); + +// [1, 2] + +$equalOrAboveThree->all(); + +// [3, 4, 5, 6] +``` + +> [!NOTE] +> This method's behavior is modified when interacting with [Eloquent collections](/docs/{{version}}/eloquent-collections#method-partition). + + +#### `percentage()` {.collection-method} + +The `percentage` method may be used to quickly determine the percentage of items in the collection that pass a given truth test: + +```php +$collection = collect([1, 1, 2, 2, 2, 3]); - $underThree->all(); +$percentage = $collection->percentage(fn (int $value) => $value === 1); - // [1, 2] +// 33.33 +``` + +By default, the percentage will be rounded to two decimal places. However, you may customize this behavior by providing a second argument to the method: - $equalOrAboveThree->all(); +```php +$percentage = $collection->percentage(fn (int $value) => $value === 1, precision: 3); - // [3, 4, 5, 6] +// 33.333 +``` #### `pipe()` {.collection-method} The `pipe` method passes the collection to the given closure and returns the result of the executed closure: - $collection = collect([1, 2, 3]); +```php +$collection = collect([1, 2, 3]); - $piped = $collection->pipe(function ($collection) { - return $collection->sum(); - }); +$piped = $collection->pipe(function (Collection $collection) { + return $collection->sum(); +}); - // 6 +// 6 +``` #### `pipeInto()` {.collection-method} The `pipeInto` method creates a new instance of the given class and passes the collection into the constructor: - class ResourceCollection - { - /** - * The Collection instance. - */ - public $collection; - - /** - * Create a new ResourceCollection instance. - * - * @param Collection $collection - * @return void - */ - public function __construct(Collection $collection) - { - $this->collection = $collection; - } - } +```php +class ResourceCollection +{ + /** + * Create a new ResourceCollection instance. + */ + public function __construct( + public Collection $collection, + ) {} +} - $collection = collect([1, 2, 3]); +$collection = collect([1, 2, 3]); - $resource = $collection->pipeInto(ResourceCollection::class); +$resource = $collection->pipeInto(ResourceCollection::class); - $resource->collection->all(); +$resource->collection->all(); - // [1, 2, 3] +// [1, 2, 3] +``` #### `pipeThrough()` {.collection-method} The `pipeThrough` method passes the collection to the given array of closures and returns the result of the executed closures: - $collection = collect([1, 2, 3]); +```php +use Illuminate\Support\Collection; + +$collection = collect([1, 2, 3]); - $result = $collection->pipeThrough([ - function ($collection) { - return $collection->merge([4, 5]); - }, - function ($collection) { - return $collection->sum(); - }, - ]); +$result = $collection->pipeThrough([ + function (Collection $collection) { + return $collection->merge([4, 5]); + }, + function (Collection $collection) { + return $collection->sum(); + }, +]); - // 15 +// 15 +``` #### `pluck()` {.collection-method} The `pluck` method retrieves all of the values for a given key: - $collection = collect([ - ['product_id' => 'prod-100', 'name' => 'Desk'], - ['product_id' => 'prod-200', 'name' => 'Chair'], - ]); +```php +$collection = collect([ + ['product_id' => 'prod-100', 'name' => 'Desk'], + ['product_id' => 'prod-200', 'name' => 'Chair'], +]); - $plucked = $collection->pluck('name'); +$plucked = $collection->pluck('name'); - $plucked->all(); +$plucked->all(); - // ['Desk', 'Chair'] +// ['Desk', 'Chair'] +``` You may also specify how you wish the resulting collection to be keyed: - $plucked = $collection->pluck('name', 'product_id'); +```php +$plucked = $collection->pluck('name', 'product_id'); - $plucked->all(); +$plucked->all(); - // ['prod-100' => 'Desk', 'prod-200' => 'Chair'] +// ['prod-100' => 'Desk', 'prod-200' => 'Chair'] +``` The `pluck` method also supports retrieving nested values using "dot" notation: - $collection = collect([ - [ - 'speakers' => [ - 'first_day' => ['Rosa', 'Judith'], - 'second_day' => ['Angela', 'Kathleen'], - ], +```php +$collection = collect([ + [ + 'name' => 'Laracon', + 'speakers' => [ + 'first_day' => ['Rosa', 'Judith'], + ], + ], + [ + 'name' => 'VueConf', + 'speakers' => [ + 'first_day' => ['Abigail', 'Joey'], ], - ]); + ], +]); - $plucked = $collection->pluck('speakers.first_day'); +$plucked = $collection->pluck('speakers.first_day'); - $plucked->all(); +$plucked->all(); - // ['Rosa', 'Judith'] +// [['Rosa', 'Judith'], ['Abigail', 'Joey']] +``` If duplicate keys exist, the last matching element will be inserted into the plucked collection: - $collection = collect([ - ['brand' => 'Tesla', 'color' => 'red'], - ['brand' => 'Pagani', 'color' => 'white'], - ['brand' => 'Tesla', 'color' => 'black'], - ['brand' => 'Pagani', 'color' => 'orange'], - ]); +```php +$collection = collect([ + ['brand' => 'Tesla', 'color' => 'red'], + ['brand' => 'Pagani', 'color' => 'white'], + ['brand' => 'Tesla', 'color' => 'black'], + ['brand' => 'Pagani', 'color' => 'orange'], +]); - $plucked = $collection->pluck('color', 'brand'); +$plucked = $collection->pluck('color', 'brand'); - $plucked->all(); +$plucked->all(); - // ['Tesla' => 'black', 'Pagani' => 'orange'] +// ['Tesla' => 'black', 'Pagani' => 'orange'] +``` #### `pop()` {.collection-method} -The `pop` method removes and returns the last item from the collection: +The `pop` method removes and returns the last item from the collection. If the collection is empty, `null` will be returned: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->pop(); +$collection->pop(); - // 5 +// 5 - $collection->all(); +$collection->all(); - // [1, 2, 3, 4] +// [1, 2, 3, 4] +``` You may pass an integer to the `pop` method to remove and return multiple items from the end of a collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->pop(3); +$collection->pop(3); - // collect([5, 4, 3]) +// collect([5, 4, 3]) - $collection->all(); +$collection->all(); - // [1, 2] +// [1, 2] +``` #### `prepend()` {.collection-method} The `prepend` method adds an item to the beginning of the collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->prepend(0); +$collection->prepend(0); - $collection->all(); +$collection->all(); - // [0, 1, 2, 3, 4, 5] +// [0, 1, 2, 3, 4, 5] +``` You may also pass a second argument to specify the key of the prepended item: - $collection = collect(['one' => 1, 'two' => 2]); +```php +$collection = collect(['one' => 1, 'two' => 2]); - $collection->prepend(0, 'zero'); +$collection->prepend(0, 'zero'); - $collection->all(); +$collection->all(); - // ['zero' => 0, 'one' => 1, 'two' => 2] +// ['zero' => 0, 'one' => 1, 'two' => 2] +``` #### `pull()` {.collection-method} The `pull` method removes and returns an item from the collection by its key: - $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']); +```php +$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']); - $collection->pull('name'); +$collection->pull('name'); - // 'Desk' +// 'Desk' - $collection->all(); +$collection->all(); - // ['product_id' => 'prod-100'] +// ['product_id' => 'prod-100'] +``` #### `push()` {.collection-method} The `push` method appends an item to the end of the collection: - $collection = collect([1, 2, 3, 4]); +```php +$collection = collect([1, 2, 3, 4]); - $collection->push(5); +$collection->push(5); - $collection->all(); +$collection->all(); + +// [1, 2, 3, 4, 5] +``` - // [1, 2, 3, 4, 5] +You may also provide multiple items to append to the end of the collection: + +```php +$collection = collect([1, 2, 3, 4]); + +$collection->push(5, 6, 7); + +$collection->all(); + +// [1, 2, 3, 4, 5, 6, 7] +``` #### `put()` {.collection-method} The `put` method sets the given key and value in the collection: - $collection = collect(['product_id' => 1, 'name' => 'Desk']); +```php +$collection = collect(['product_id' => 1, 'name' => 'Desk']); - $collection->put('price', 100); +$collection->put('price', 100); - $collection->all(); +$collection->all(); - // ['product_id' => 1, 'name' => 'Desk', 'price' => 100] +// ['product_id' => 1, 'name' => 'Desk', 'price' => 100] +``` #### `random()` {.collection-method} The `random` method returns a random item from the collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->random(); +$collection->random(); - // 4 - (retrieved randomly) +// 4 - (retrieved randomly) +``` You may pass an integer to `random` to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive: - $random = $collection->random(3); +```php +$random = $collection->random(3); - $random->all(); +$random->all(); - // [2, 4, 5] - (retrieved randomly) +// [2, 4, 5] - (retrieved randomly) +``` If the collection instance has fewer items than requested, the `random` method will throw an `InvalidArgumentException`. +The `random` method also accepts a closure, which will receive the current collection instance: + +```php +use Illuminate\Support\Collection; + +$random = $collection->random(fn (Collection $items) => min(10, count($items))); + +$random->all(); + +// [1, 2, 3, 4, 5] - (retrieved randomly) +``` + #### `range()` {.collection-method} The `range` method returns a collection containing integers between the specified range: - $collection = collect()->range(3, 6); +```php +$collection = collect()->range(3, 6); - $collection->all(); +$collection->all(); - // [3, 4, 5, 6] +// [3, 4, 5, 6] +``` #### `reduce()` {.collection-method} The `reduce` method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration: - $collection = collect([1, 2, 3]); +```php +$collection = collect([1, 2, 3]); - $total = $collection->reduce(function ($carry, $item) { - return $carry + $item; - }); +$total = $collection->reduce(function (?int $carry, int $item) { + return $carry + $item; +}); - // 6 +// 6 +``` The value for `$carry` on the first iteration is `null`; however, you may specify its initial value by passing a second argument to `reduce`: - $collection->reduce(function ($carry, $item) { - return $carry + $item; - }, 4); - - // 10 - -The `reduce` method also passes array keys in associative collections to the given callback: +```php +$collection->reduce(function (int $carry, int $item) { + return $carry + $item; +}, 4); - $collection = collect([ - 'usd' => 1400, - 'gbp' => 1200, - 'eur' => 1000, - ]); - - $ratio = [ - 'usd' => 1, - 'gbp' => 1.37, - 'eur' => 1.22, - ]; - - $collection->reduce(function ($carry, $value, $key) use ($ratio) { - return $carry + ($value * $ratio[$key]); - }); - - // 4264 +// 10 +``` - -#### `reduceMany()` {.collection-method} +The `reduce` method also passes array keys to the given callback: -The `reduceMany` method reduces the collection to an array of values, passing the results of each iteration into the subsequent iteration. This method is similar to the `reduce` method; however, it can accept multiple initial values: +```php +$collection = collect([ + 'usd' => 1400, + 'gbp' => 1200, + 'eur' => 1000, +]); - [$creditsRemaining, $batch] = Image::where('status', 'unprocessed') - ->get() - ->reduceMany(function ($creditsRemaining, $batch, $image) { - if ($creditsRemaining >= $image->creditsRequired()) { - $batch->push($image); +$ratio = [ + 'usd' => 1, + 'gbp' => 1.37, + 'eur' => 1.22, +]; - $creditsRemaining -= $image->creditsRequired(); - } +$collection->reduce(function (int $carry, int $value, string $key) use ($ratio) { + return $carry + ($value * $ratio[$key]); +}, 0); - return [$creditsRemaining, $batch]; - }, $creditsAvailable, collect()); +// 4264 +``` #### `reduceSpread()` {.collection-method} The `reduceSpread` method reduces the collection to an array of values, passing the results of each iteration into the subsequent iteration. This method is similar to the `reduce` method; however, it can accept multiple initial values: - [$creditsRemaining, $batch] = Image::where('status', 'unprocessed') - ->get() - ->reduceSpread(function ($creditsRemaining, $batch, $image) { - if ($creditsRemaining >= $image->creditsRequired()) { - $batch->push($image); +```php +[$creditsRemaining, $batch] = Image::where('status', 'unprocessed') + ->get() + ->reduceSpread(function (int $creditsRemaining, Collection $batch, Image $image) { + if ($creditsRemaining >= $image->creditsRequired()) { + $batch->push($image); - $creditsRemaining -= $image->creditsRequired(); - } + $creditsRemaining -= $image->creditsRequired(); + } - return [$creditsRemaining, $batch]; - }, $creditsAvailable, collect()); + return [$creditsRemaining, $batch]; + }, $creditsAvailable, collect()); +``` #### `reject()` {.collection-method} The `reject` method filters the collection using the given closure. The closure should return `true` if the item should be removed from the resulting collection: - $collection = collect([1, 2, 3, 4]); +```php +$collection = collect([1, 2, 3, 4]); - $filtered = $collection->reject(function ($value, $key) { - return $value > 2; - }); +$filtered = $collection->reject(function (int $value, int $key) { + return $value > 2; +}); - $filtered->all(); +$filtered->all(); - // [1, 2] +// [1, 2] +``` -For the inverse of the `reject` method, see the [`filter`](#method-filter) method. +For the inverse of the `reject` method, see the [filter](#method-filter) method. #### `replace()` {.collection-method} The `replace` method behaves similarly to `merge`; however, in addition to overwriting matching items that have string keys, the `replace` method will also overwrite items in the collection that have matching numeric keys: - $collection = collect(['Taylor', 'Abigail', 'James']); +```php +$collection = collect(['Taylor', 'Abigail', 'James']); - $replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']); +$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']); - $replaced->all(); +$replaced->all(); - // ['Taylor', 'Victoria', 'James', 'Finn'] +// ['Taylor', 'Victoria', 'James', 'Finn'] +``` #### `replaceRecursive()` {.collection-method} -This method works like `replace`, but it will recur into arrays and apply the same replacement process to the inner values: +The `replaceRecursive` method behaves similarly to `replace`, but it will recur into arrays and apply the same replacement process to the inner values: - $collection = collect([ - 'Taylor', - 'Abigail', - [ - 'James', - 'Victoria', - 'Finn' - ] - ]); +```php +$collection = collect([ + 'Taylor', + 'Abigail', + [ + 'James', + 'Victoria', + 'Finn' + ] +]); - $replaced = $collection->replaceRecursive([ - 'Charlie', - 2 => [1 => 'King'] - ]); +$replaced = $collection->replaceRecursive([ + 'Charlie', + 2 => [1 => 'King'] +]); - $replaced->all(); +$replaced->all(); - // ['Charlie', 'Abigail', ['James', 'King', 'Finn']] +// ['Charlie', 'Abigail', ['James', 'King', 'Finn']] +``` #### `reverse()` {.collection-method} The `reverse` method reverses the order of the collection's items, preserving the original keys: - $collection = collect(['a', 'b', 'c', 'd', 'e']); +```php +$collection = collect(['a', 'b', 'c', 'd', 'e']); - $reversed = $collection->reverse(); +$reversed = $collection->reverse(); - $reversed->all(); +$reversed->all(); - /* - [ - 4 => 'e', - 3 => 'd', - 2 => 'c', - 1 => 'b', - 0 => 'a', - ] - */ +/* + [ + 4 => 'e', + 3 => 'd', + 2 => 'c', + 1 => 'b', + 0 => 'a', + ] +*/ +``` #### `search()` {.collection-method} The `search` method searches the collection for the given value and returns its key if found. If the item is not found, `false` is returned: - $collection = collect([2, 4, 6, 8]); +```php +$collection = collect([2, 4, 6, 8]); - $collection->search(4); +$collection->search(4); - // 1 +// 1 +``` The search is done using a "loose" comparison, meaning a string with an integer value will be considered equal to an integer of the same value. To use "strict" comparison, pass `true` as the second argument to the method: - collect([2, 4, 6, 8])->search('4', $strict = true); +```php +collect([2, 4, 6, 8])->search('4', strict: true); - // false +// false +``` Alternatively, you may provide your own closure to search for the first item that passes a given truth test: - collect([2, 4, 6, 8])->search(function ($item, $key) { - return $item > 5; - }); +```php +collect([2, 4, 6, 8])->search(function (int $item, int $key) { + return $item > 5; +}); + +// 2 +``` + + +#### `select()` {.collection-method} - // 2 +The `select` method selects the given keys from the collection, similar to an SQL `SELECT` statement: + +```php +$users = collect([ + ['name' => 'Taylor Otwell', 'role' => 'Developer', 'status' => 'active'], + ['name' => 'Victoria Faith', 'role' => 'Researcher', 'status' => 'active'], +]); + +$users->select(['name', 'role']); + +/* + [ + ['name' => 'Taylor Otwell', 'role' => 'Developer'], + ['name' => 'Victoria Faith', 'role' => 'Researcher'], + ], +*/ +``` #### `shift()` {.collection-method} The `shift` method removes and returns the first item from the collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->shift(); +$collection->shift(); - // 1 +// 1 - $collection->all(); +$collection->all(); - // [2, 3, 4, 5] +// [2, 3, 4, 5] +``` You may pass an integer to the `shift` method to remove and return multiple items from the beginning of a collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->shift(3); +$collection->shift(3); - // collect([1, 2, 3]) +// collect([1, 2, 3]) - $collection->all(); +$collection->all(); - // [4, 5] +// [4, 5] +``` #### `shuffle()` {.collection-method} The `shuffle` method randomly shuffles the items in the collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $shuffled = $collection->shuffle(); +$shuffled = $collection->shuffle(); - $shuffled->all(); +$shuffled->all(); - // [3, 2, 5, 1, 4] - (generated randomly) +// [3, 2, 5, 1, 4] - (generated randomly) +``` - -#### `sliding()` {.collection-method} + +#### `skip()` {.collection-method} -The `sliding` method returns a new collection of chunks representing a "sliding window" view of the items in the collection: +The `skip` method returns a new collection, with the given number of elements removed from the beginning of the collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - $chunks = $collection->sliding(2); +$collection = $collection->skip(4); - $chunks->toArray(); +$collection->all(); - // [[1, 2], [2, 3], [3, 4], [4, 5]] +// [5, 6, 7, 8, 9, 10] +``` -This is especially useful in conjunction with the [`eachSpread`](#method-eachspread) method: + +#### `skipUntil()` {.collection-method} - $transactions->sliding(2)->eachSpread(function ($previous, $current) { - $current->total = $previous->total + $current->amount; - }); +The `skipUntil` method skips over items from the collection while the given callback returns `false`. Once the callback returns `true` all of the remaining items in the collection will be returned as a new collection: -You may optionally pass a second "step" value, which determines the distance between the first item of every chunk: +```php +$collection = collect([1, 2, 3, 4]); - $collection = collect([1, 2, 3, 4, 5]); +$subset = $collection->skipUntil(function (int $item) { + return $item >= 3; +}); - $chunks = $collection->sliding(3, step: 2); +$subset->all(); - $chunks->toArray(); +// [3, 4] +``` - // [[1, 2, 3], [3, 4, 5]] +You may also pass a simple value to the `skipUntil` method to skip all items until the given value is found: - -#### `skip()` {.collection-method} +```php +$collection = collect([1, 2, 3, 4]); -The `skip` method returns a new collection, with the given number of elements removed from the beginning of the collection: +$subset = $collection->skipUntil(3); - $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +$subset->all(); - $collection = $collection->skip(4); +// [3, 4] +``` - $collection->all(); +> [!WARNING] +> If the given value is not found or the callback never returns `true`, the `skipUntil` method will return an empty collection. - // [5, 6, 7, 8, 9, 10] + +#### `skipWhile()` {.collection-method} - -#### `skipUntil()` {.collection-method} +The `skipWhile` method skips over items from the collection while the given callback returns `true`. Once the callback returns `false` all of the remaining items in the collection will be returned as a new collection: -The `skipUntil` method skips over items from the collection until the given callback returns `true` and then returns the remaining items in the collection as a new collection instance: +```php +$collection = collect([1, 2, 3, 4]); - $collection = collect([1, 2, 3, 4]); +$subset = $collection->skipWhile(function (int $item) { + return $item <= 3; +}); - $subset = $collection->skipUntil(function ($item) { - return $item >= 3; - }); +$subset->all(); - $subset->all(); +// [4] +``` - // [3, 4] +> [!WARNING] +> If the callback never returns `false`, the `skipWhile` method will return an empty collection. -You may also pass a simple value to the `skipUntil` method to skip all items until the given value is found: + +#### `slice()` {.collection-method} - $collection = collect([1, 2, 3, 4]); +The `slice` method returns a slice of the collection starting at the given index: - $subset = $collection->skipUntil(3); +```php +$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - $subset->all(); +$slice = $collection->slice(4); - // [3, 4] +$slice->all(); -> {note} If the given value is not found or the callback never returns `true`, the `skipUntil` method will return an empty collection. +// [5, 6, 7, 8, 9, 10] +``` - -#### `skipWhile()` {.collection-method} +If you would like to limit the size of the returned slice, pass the desired size as the second argument to the method: -The `skipWhile` method skips over items from the collection while the given callback returns `true` and then returns the remaining items in the collection as a new collection: +```php +$slice = $collection->slice(4, 2); - $collection = collect([1, 2, 3, 4]); +$slice->all(); - $subset = $collection->skipWhile(function ($item) { - return $item <= 3; - }); +// [5, 6] +``` - $subset->all(); +The returned slice will preserve keys by default. If you do not wish to preserve the original keys, you can use the [values](#method-values) method to reindex them. - // [4] + +#### `sliding()` {.collection-method} -> {note} If the callback never returns `false`, the `skipWhile` method will return an empty collection. +The `sliding` method returns a new collection of chunks representing a "sliding window" view of the items in the collection: - -#### `slice()` {.collection-method} +```php +$collection = collect([1, 2, 3, 4, 5]); -The `slice` method returns a slice of the collection starting at the given index: +$chunks = $collection->sliding(2); - $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +$chunks->toArray(); - $slice = $collection->slice(4); +// [[1, 2], [2, 3], [3, 4], [4, 5]] +``` - $slice->all(); +This is especially useful in conjunction with the [eachSpread](#method-eachspread) method: - // [5, 6, 7, 8, 9, 10] +```php +$transactions->sliding(2)->eachSpread(function (Collection $previous, Collection $current) { + $current->total = $previous->total + $current->amount; +}); +``` -If you would like to limit the size of the returned slice, pass the desired size as the second argument to the method: +You may optionally pass a second "step" value, which determines the distance between the first item of every chunk: - $slice = $collection->slice(4, 2); +```php +$collection = collect([1, 2, 3, 4, 5]); - $slice->all(); +$chunks = $collection->sliding(3, step: 2); - // [5, 6] +$chunks->toArray(); -The returned slice will preserve keys by default. If you do not wish to preserve the original keys, you can use the [`values`](#method-values) method to reindex them. +// [[1, 2, 3], [3, 4, 5]] +``` #### `sole()` {.collection-method} The `sole` method returns the first element in the collection that passes a given truth test, but only if the truth test matches exactly one element: - collect([1, 2, 3, 4])->sole(function ($value, $key) { - return $value === 2; - }); +```php +collect([1, 2, 3, 4])->sole(function (int $value, int $key) { + return $value === 2; +}); - // 2 +// 2 +``` You may also pass a key / value pair to the `sole` method, which will return the first element in the collection that matches the given pair, but only if it exactly one element matches: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Chair', 'price' => 100], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Chair', 'price' => 100], +]); - $collection->sole('product', 'Chair'); +$collection->sole('product', 'Chair'); - // ['product' => 'Chair', 'price' => 100] +// ['product' => 'Chair', 'price' => 100] +``` Alternatively, you may also call the `sole` method with no argument to get the first element in the collection if there is only one element: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], +]); - $collection->sole(); +$collection->sole(); - // ['product' => 'Desk', 'price' => 200] +// ['product' => 'Desk', 'price' => 200] +``` If there are no elements in the collection that should be returned by the `sole` method, an `\Illuminate\Collections\ItemNotFoundException` exception will be thrown. If there is more than one element that should be returned, an `\Illuminate\Collections\MultipleItemsFoundException` will be thrown. #### `some()` {.collection-method} -Alias for the [`contains`](#method-contains) method. +Alias for the [contains](#method-contains) method. #### `sort()` {.collection-method} -The `sort` method sorts the collection. The sorted collection keeps the original array keys, so in the following example we will use the [`values`](#method-values) method to reset the keys to consecutively numbered indexes: +The `sort` method sorts the collection. The sorted collection keeps the original array keys, so in the following example we will use the [values](#method-values) method to reset the keys to consecutively numbered indexes: - $collection = collect([5, 3, 1, 2, 4]); +```php +$collection = collect([5, 3, 1, 2, 4]); - $sorted = $collection->sort(); +$sorted = $collection->sort(); - $sorted->values()->all(); +$sorted->values()->all(); - // [1, 2, 3, 4, 5] +// [1, 2, 3, 4, 5] +``` -If your sorting needs are more advanced, you may pass a callback to `sort` with your own algorithm. Refer to the PHP documentation on [`uasort`](https://secure.php.net/manual/en/function.uasort.php#refsect1-function.uasort-parameters), which is what the collection's `sort` method calls utilizes internally. +If your sorting needs are more advanced, you may pass a callback to `sort` with your own algorithm. Refer to the PHP documentation on [uasort](https://secure.php.net/manual/en/function.uasort.php#refsect1-function.uasort-parameters), which is what the collection's `sort` method calls utilizes internally. -> {tip} If you need to sort a collection of nested arrays or objects, see the [`sortBy`](#method-sortby) and [`sortByDesc`](#method-sortbydesc) methods. +> [!NOTE] +> If you need to sort a collection of nested arrays or objects, see the [sortBy](#method-sortby) and [sortByDesc](#method-sortbydesc) methods. #### `sortBy()` {.collection-method} -The `sortBy` method sorts the collection by the given key. The sorted collection keeps the original array keys, so in the following example we will use the [`values`](#method-values) method to reset the keys to consecutively numbered indexes: +The `sortBy` method sorts the collection by the given key. The sorted collection keeps the original array keys, so in the following example we will use the [values](#method-values) method to reset the keys to consecutively numbered indexes: - $collection = collect([ - ['name' => 'Desk', 'price' => 200], +```php +$collection = collect([ + ['name' => 'Desk', 'price' => 200], + ['name' => 'Chair', 'price' => 100], + ['name' => 'Bookcase', 'price' => 150], +]); + +$sorted = $collection->sortBy('price'); + +$sorted->values()->all(); + +/* + [ ['name' => 'Chair', 'price' => 100], ['name' => 'Bookcase', 'price' => 150], - ]); + ['name' => 'Desk', 'price' => 200], + ] +*/ +``` - $sorted = $collection->sortBy('price'); +The `sortBy` method accepts [sort flags](https://www.php.net/manual/en/function.sort.php) as its second argument: - $sorted->values()->all(); +```php +$collection = collect([ + ['title' => 'Item 1'], + ['title' => 'Item 12'], + ['title' => 'Item 3'], +]); - /* - [ - ['name' => 'Chair', 'price' => 100], - ['name' => 'Bookcase', 'price' => 150], - ['name' => 'Desk', 'price' => 200], - ] - */ +$sorted = $collection->sortBy('title', SORT_NATURAL); -The `sortBy` method accepts [sort flags](https://www.php.net/manual/en/function.sort.php) as its second argument: +$sorted->values()->all(); - $collection = collect([ +/* + [ ['title' => 'Item 1'], - ['title' => 'Item 12'], ['title' => 'Item 3'], - ]); + ['title' => 'Item 12'], + ] +*/ +``` - $sorted = $collection->sortBy('title', SORT_NATURAL); +Alternatively, you may pass your own closure to determine how to sort the collection's values: - $sorted->values()->all(); +```php +$collection = collect([ + ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], + ['name' => 'Chair', 'colors' => ['Black']], + ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']], +]); - /* - [ - ['title' => 'Item 1'], - ['title' => 'Item 3'], - ['title' => 'Item 12'], - ] - */ +$sorted = $collection->sortBy(function (array $product, int $key) { + return count($product['colors']); +}); -Alternatively, you may pass your own closure to determine how to sort the collection's values: +$sorted->values()->all(); - $collection = collect([ - ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], +/* + [ ['name' => 'Chair', 'colors' => ['Black']], + ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']], - ]); + ] +*/ +``` - $sorted = $collection->sortBy(function ($product, $key) { - return count($product['colors']); - }); +If you would like to sort your collection by multiple attributes, you may pass an array of sort operations to the `sortBy` method. Each sort operation should be an array consisting of the attribute that you wish to sort by and the direction of the desired sort: - $sorted->values()->all(); +```php +$collection = collect([ + ['name' => 'Taylor Otwell', 'age' => 34], + ['name' => 'Abigail Otwell', 'age' => 30], + ['name' => 'Taylor Otwell', 'age' => 36], + ['name' => 'Abigail Otwell', 'age' => 32], +]); - /* - [ - ['name' => 'Chair', 'colors' => ['Black']], - ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], - ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']], - ] - */ +$sorted = $collection->sortBy([ + ['name', 'asc'], + ['age', 'desc'], +]); -If you would like to sort your collection by multiple attributes, you may pass an array of sort operations to the `sortBy` method. Each sort operation should be an array consisting of the attribute that you wish to sort by and the direction of the desired sort: +$sorted->values()->all(); - $collection = collect([ - ['name' => 'Taylor Otwell', 'age' => 34], +/* + [ + ['name' => 'Abigail Otwell', 'age' => 32], ['name' => 'Abigail Otwell', 'age' => 30], ['name' => 'Taylor Otwell', 'age' => 36], - ['name' => 'Abigail Otwell', 'age' => 32], - ]); + ['name' => 'Taylor Otwell', 'age' => 34], + ] +*/ +``` - $sorted = $collection->sortBy([ - ['name', 'asc'], - ['age', 'desc'], - ]); +When sorting a collection by multiple attributes, you may also provide closures that define each sort operation: - $sorted->values()->all(); +```php +$collection = collect([ + ['name' => 'Taylor Otwell', 'age' => 34], + ['name' => 'Abigail Otwell', 'age' => 30], + ['name' => 'Taylor Otwell', 'age' => 36], + ['name' => 'Abigail Otwell', 'age' => 32], +]); - /* - [ - ['name' => 'Abigail Otwell', 'age' => 32], - ['name' => 'Abigail Otwell', 'age' => 30], - ['name' => 'Taylor Otwell', 'age' => 36], - ['name' => 'Taylor Otwell', 'age' => 34], - ] - */ +$sorted = $collection->sortBy([ + fn (array $a, array $b) => $a['name'] <=> $b['name'], + fn (array $a, array $b) => $b['age'] <=> $a['age'], +]); -When sorting a collection by multiple attributes, you may also provide closures that define each sort operation: +$sorted->values()->all(); - $collection = collect([ - ['name' => 'Taylor Otwell', 'age' => 34], +/* + [ + ['name' => 'Abigail Otwell', 'age' => 32], ['name' => 'Abigail Otwell', 'age' => 30], ['name' => 'Taylor Otwell', 'age' => 36], - ['name' => 'Abigail Otwell', 'age' => 32], - ]); - - $sorted = $collection->sortBy([ - fn ($a, $b) => $a['name'] <=> $b['name'], - fn ($a, $b) => $b['age'] <=> $a['age'], - ]); - - $sorted->values()->all(); - - /* - [ - ['name' => 'Abigail Otwell', 'age' => 32], - ['name' => 'Abigail Otwell', 'age' => 30], - ['name' => 'Taylor Otwell', 'age' => 36], - ['name' => 'Taylor Otwell', 'age' => 34], - ] - */ + ['name' => 'Taylor Otwell', 'age' => 34], + ] +*/ +``` #### `sortByDesc()` {.collection-method} -This method has the same signature as the [`sortBy`](#method-sortby) method, but will sort the collection in the opposite order. +This method has the same signature as the [sortBy](#method-sortby) method, but will sort the collection in the opposite order. #### `sortDesc()` {.collection-method} -This method will sort the collection in the opposite order as the [`sort`](#method-sort) method: +This method will sort the collection in the opposite order as the [sort](#method-sort) method: - $collection = collect([5, 3, 1, 2, 4]); +```php +$collection = collect([5, 3, 1, 2, 4]); - $sorted = $collection->sortDesc(); +$sorted = $collection->sortDesc(); - $sorted->values()->all(); +$sorted->values()->all(); - // [5, 4, 3, 2, 1] +// [5, 4, 3, 2, 1] +``` -Unlike `sort`, you may not pass a closure to `sortDesc`. Instead, you should use the [`sort`](#method-sort) method and invert your comparison. +Unlike `sort`, you may not pass a closure to `sortDesc`. Instead, you should use the [sort](#method-sort) method and invert your comparison. #### `sortKeys()` {.collection-method} The `sortKeys` method sorts the collection by the keys of the underlying associative array: - $collection = collect([ - 'id' => 22345, - 'first' => 'John', - 'last' => 'Doe', - ]); +```php +$collection = collect([ + 'id' => 22345, + 'first' => 'John', + 'last' => 'Doe', +]); - $sorted = $collection->sortKeys(); +$sorted = $collection->sortKeys(); - $sorted->all(); +$sorted->all(); - /* - [ - 'first' => 'John', - 'id' => 22345, - 'last' => 'Doe', - ] - */ +/* + [ + 'first' => 'John', + 'id' => 22345, + 'last' => 'Doe', + ] +*/ +``` #### `sortKeysDesc()` {.collection-method} -This method has the same signature as the [`sortKeys`](#method-sortkeys) method, but will sort the collection in the opposite order. +This method has the same signature as the [sortKeys](#method-sortkeys) method, but will sort the collection in the opposite order. #### `sortKeysUsing()` {.collection-method} The `sortKeysUsing` method sorts the collection by the keys of the underlying associative array using a callback: - $collection = collect([ - 'ID' => 22345, - 'first' => 'John', - 'last' => 'Doe', - ]); +```php +$collection = collect([ + 'ID' => 22345, + 'first' => 'John', + 'last' => 'Doe', +]); - $sorted = $collection->sortKeysUsing('strnatcasecmp'); +$sorted = $collection->sortKeysUsing('strnatcasecmp'); - $sorted->all(); +$sorted->all(); - /* - [ - 'first' => 'John', - 'ID' => 22345, - 'last' => 'Doe', - ] - */ +/* + [ + 'first' => 'John', + 'ID' => 22345, + 'last' => 'Doe', + ] +*/ +``` -The callback must be a comparison function that returns an integer less than, equal to, or greater than zero. For more information, refer to the PHP documentation on [`uksort`](https://www.php.net/manual/en/function.uksort.php#refsect1-function.uksort-parameters), which is the PHP function that `sortKeysUsing` method utilizes internally. +The callback must be a comparison function that returns an integer less than, equal to, or greater than zero. For more information, refer to the PHP documentation on [uksort](https://www.php.net/manual/en/function.uksort.php#refsect1-function.uksort-parameters), which is the PHP function that `sortKeysUsing` method utilizes internally. #### `splice()` {.collection-method} The `splice` method removes and returns a slice of items starting at the specified index: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $chunk = $collection->splice(2); +$chunk = $collection->splice(2); - $chunk->all(); +$chunk->all(); - // [3, 4, 5] +// [3, 4, 5] - $collection->all(); +$collection->all(); - // [1, 2] +// [1, 2] +``` You may pass a second argument to limit the size of the resulting collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $chunk = $collection->splice(2, 1); +$chunk = $collection->splice(2, 1); - $chunk->all(); +$chunk->all(); - // [3] +// [3] - $collection->all(); +$collection->all(); - // [1, 2, 4, 5] +// [1, 2, 4, 5] +``` In addition, you may pass a third argument containing the new items to replace the items removed from the collection: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $chunk = $collection->splice(2, 1, [10, 11]); +$chunk = $collection->splice(2, 1, [10, 11]); - $chunk->all(); +$chunk->all(); - // [3] +// [3] - $collection->all(); +$collection->all(); - // [1, 2, 10, 11, 4, 5] +// [1, 2, 10, 11, 4, 5] +``` #### `split()` {.collection-method} The `split` method breaks a collection into the given number of groups: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $groups = $collection->split(3); +$groups = $collection->split(3); - $groups->all(); +$groups->all(); - // [[1, 2], [3, 4], [5]] +// [[1, 2], [3, 4], [5]] +``` #### `splitIn()` {.collection-method} The `splitIn` method breaks a collection into the given number of groups, filling non-terminal groups completely before allocating the remainder to the final group: - $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +```php +$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - $groups = $collection->splitIn(3); +$groups = $collection->splitIn(3); - $groups->all(); +$groups->all(); - // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]] +// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]] +``` #### `sum()` {.collection-method} The `sum` method returns the sum of all items in the collection: - collect([1, 2, 3, 4, 5])->sum(); +```php +collect([1, 2, 3, 4, 5])->sum(); - // 15 +// 15 +``` If the collection contains nested arrays or objects, you should pass a key that will be used to determine which values to sum: - $collection = collect([ - ['name' => 'JavaScript: The Good Parts', 'pages' => 176], - ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096], - ]); +```php +$collection = collect([ + ['name' => 'JavaScript: The Good Parts', 'pages' => 176], + ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096], +]); - $collection->sum('pages'); +$collection->sum('pages'); - // 1272 +// 1272 +``` In addition, you may pass your own closure to determine which values of the collection to sum: - $collection = collect([ - ['name' => 'Chair', 'colors' => ['Black']], - ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], - ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']], - ]); +```php +$collection = collect([ + ['name' => 'Chair', 'colors' => ['Black']], + ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], + ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']], +]); - $collection->sum(function ($product) { - return count($product['colors']); - }); +$collection->sum(function (array $product) { + return count($product['colors']); +}); - // 6 +// 6 +``` #### `take()` {.collection-method} The `take` method returns a new collection with the specified number of items: - $collection = collect([0, 1, 2, 3, 4, 5]); +```php +$collection = collect([0, 1, 2, 3, 4, 5]); - $chunk = $collection->take(3); +$chunk = $collection->take(3); - $chunk->all(); +$chunk->all(); - // [0, 1, 2] +// [0, 1, 2] +``` You may also pass a negative integer to take the specified number of items from the end of the collection: - $collection = collect([0, 1, 2, 3, 4, 5]); +```php +$collection = collect([0, 1, 2, 3, 4, 5]); - $chunk = $collection->take(-2); +$chunk = $collection->take(-2); - $chunk->all(); +$chunk->all(); - // [4, 5] +// [4, 5] +``` #### `takeUntil()` {.collection-method} The `takeUntil` method returns items in the collection until the given callback returns `true`: - $collection = collect([1, 2, 3, 4]); +```php +$collection = collect([1, 2, 3, 4]); - $subset = $collection->takeUntil(function ($item) { - return $item >= 3; - }); +$subset = $collection->takeUntil(function (int $item) { + return $item >= 3; +}); - $subset->all(); +$subset->all(); - // [1, 2] +// [1, 2] +``` You may also pass a simple value to the `takeUntil` method to get the items until the given value is found: - $collection = collect([1, 2, 3, 4]); +```php +$collection = collect([1, 2, 3, 4]); - $subset = $collection->takeUntil(3); +$subset = $collection->takeUntil(3); - $subset->all(); +$subset->all(); - // [1, 2] +// [1, 2] +``` -> {note} If the given value is not found or the callback never returns `true`, the `takeUntil` method will return all items in the collection. +> [!WARNING] +> If the given value is not found or the callback never returns `true`, the `takeUntil` method will return all items in the collection. #### `takeWhile()` {.collection-method} The `takeWhile` method returns items in the collection until the given callback returns `false`: - $collection = collect([1, 2, 3, 4]); +```php +$collection = collect([1, 2, 3, 4]); - $subset = $collection->takeWhile(function ($item) { - return $item < 3; - }); +$subset = $collection->takeWhile(function (int $item) { + return $item < 3; +}); - $subset->all(); +$subset->all(); - // [1, 2] +// [1, 2] +``` -> {note} If the callback never returns `false`, the `takeWhile` method will return all items in the collection. +> [!WARNING] +> If the callback never returns `false`, the `takeWhile` method will return all items in the collection. #### `tap()` {.collection-method} The `tap` method passes the collection to the given callback, allowing you to "tap" into the collection at a specific point and do something with the items while not affecting the collection itself. The collection is then returned by the `tap` method: - collect([2, 4, 3, 1, 5]) - ->sort() - ->tap(function ($collection) { - Log::debug('Values after sorting', $collection->values()->all()); - }) - ->shift(); +```php +collect([2, 4, 3, 1, 5]) + ->sort() + ->tap(function (Collection $collection) { + Log::debug('Values after sorting', $collection->values()->all()); + }) + ->shift(); - // 1 +// 1 +``` #### `times()` {.collection-method} The static `times` method creates a new collection by invoking the given closure a specified number of times: - $collection = Collection::times(10, function ($number) { - return $number * 9; - }); +```php +$collection = Collection::times(10, function (int $number) { + return $number * 9; +}); - $collection->all(); +$collection->all(); - // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90] +// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90] +``` #### `toArray()` {.collection-method} The `toArray` method converts the collection into a plain PHP `array`. If the collection's values are [Eloquent](/docs/{{version}}/eloquent) models, the models will also be converted to arrays: - $collection = collect(['name' => 'Desk', 'price' => 200]); +```php +$collection = collect(['name' => 'Desk', 'price' => 200]); - $collection->toArray(); +$collection->toArray(); - /* - [ - ['name' => 'Desk', 'price' => 200], - ] - */ +/* + [ + ['name' => 'Desk', 'price' => 200], + ] +*/ +``` -> {note} `toArray` also converts all of the collection's nested objects that are an instance of `Arrayable` to an array. If you want to get the raw array underlying the collection, use the [`all`](#method-all) method instead. +> [!WARNING] +> `toArray` also converts all of the collection's nested objects that are an instance of `Arrayable` to an array. If you want to get the raw array underlying the collection, use the [all](#method-all) method instead. #### `toJson()` {.collection-method} The `toJson` method converts the collection into a JSON serialized string: - $collection = collect(['name' => 'Desk', 'price' => 200]); +```php +$collection = collect(['name' => 'Desk', 'price' => 200]); + +$collection->toJson(); + +// '{"name":"Desk", "price":200}' +``` + + +#### `toPrettyJson()` {.collection-method} - $collection->toJson(); +The `toPrettyJson` method converts the collection into a formatted JSON string using the `JSON_PRETTY_PRINT` option: - // '{"name":"Desk", "price":200}' +```php +$collection = collect(['name' => 'Desk', 'price' => 200]); + +$collection->toPrettyJson(); +``` #### `transform()` {.collection-method} The `transform` method iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback: - $collection = collect([1, 2, 3, 4, 5]); +```php +$collection = collect([1, 2, 3, 4, 5]); - $collection->transform(function ($item, $key) { - return $item * 2; - }); +$collection->transform(function (int $item, int $key) { + return $item * 2; +}); - $collection->all(); +$collection->all(); - // [2, 4, 6, 8, 10] +// [2, 4, 6, 8, 10] +``` -> {note} Unlike most other collection methods, `transform` modifies the collection itself. If you wish to create a new collection instead, use the [`map`](#method-map) method. +> [!WARNING] +> Unlike most other collection methods, `transform` modifies the collection itself. If you wish to create a new collection instead, use the [map](#method-map) method. #### `undot()` {.collection-method} The `undot` method expands a single-dimensional collection that uses "dot" notation into a multi-dimensional collection: - $person = collect([ - 'name.first_name' => 'Marie', - 'name.last_name' => 'Valentine', - 'address.line_1' => '2992 Eagle Drive', - 'address.line_2' => '', - 'address.suburb' => 'Detroit', - 'address.state' => 'MI', - 'address.postcode' => '48219' - ]) +```php +$person = collect([ + 'name.first_name' => 'Marie', + 'name.last_name' => 'Valentine', + 'address.line_1' => '2992 Eagle Drive', + 'address.line_2' => '', + 'address.suburb' => 'Detroit', + 'address.state' => 'MI', + 'address.postcode' => '48219' +]); - $person = $person->undot(); +$person = $person->undot(); - $person->toArray(); +$person->toArray(); - /* - [ - "name" => [ - "first_name" => "Marie", - "last_name" => "Valentine", - ], - "address" => [ - "line_1" => "2992 Eagle Drive", - "line_2" => "", - "suburb" => "Detroit", - "state" => "MI", - "postcode" => "48219", - ], - ] - */ +/* + [ + "name" => [ + "first_name" => "Marie", + "last_name" => "Valentine", + ], + "address" => [ + "line_1" => "2992 Eagle Drive", + "line_2" => "", + "suburb" => "Detroit", + "state" => "MI", + "postcode" => "48219", + ], + ] +*/ +``` #### `union()` {.collection-method} The `union` method adds the given array to the collection. If the given array contains keys that are already in the original collection, the original collection's values will be preferred: - $collection = collect([1 => ['a'], 2 => ['b']]); +```php +$collection = collect([1 => ['a'], 2 => ['b']]); - $union = $collection->union([3 => ['c'], 1 => ['d']]); +$union = $collection->union([3 => ['c'], 1 => ['d']]); - $union->all(); +$union->all(); - // [1 => ['a'], 2 => ['b'], 3 => ['c']] +// [1 => ['a'], 2 => ['b'], 3 => ['c']] +``` #### `unique()` {.collection-method} -The `unique` method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in the following example we will use the [`values`](#method-values) method to reset the keys to consecutively numbered indexes: +The `unique` method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in the following example we will use the [values](#method-values) method to reset the keys to consecutively numbered indexes: - $collection = collect([1, 1, 2, 2, 3, 4, 2]); +```php +$collection = collect([1, 1, 2, 2, 3, 4, 2]); - $unique = $collection->unique(); +$unique = $collection->unique(); - $unique->values()->all(); +$unique->values()->all(); - // [1, 2, 3, 4] +// [1, 2, 3, 4] +``` When dealing with nested arrays or objects, you may specify the key used to determine uniqueness: - $collection = collect([ - ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], - ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], - ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], - ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], - ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], - ]); +```php +$collection = collect([ + ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], + ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], + ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], + ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], + ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], +]); - $unique = $collection->unique('brand'); +$unique = $collection->unique('brand'); - $unique->values()->all(); +$unique->values()->all(); - /* - [ - ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], - ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], - ] - */ +/* + [ + ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], + ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], + ] +*/ +``` Finally, you may also pass your own closure to the `unique` method to specify which value should determine an item's uniqueness: - $unique = $collection->unique(function ($item) { - return $item['brand'].$item['type']; - }); +```php +$unique = $collection->unique(function (array $item) { + return $item['brand'].$item['type']; +}); - $unique->values()->all(); +$unique->values()->all(); - /* - [ - ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], - ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], - ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], - ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], - ] - */ +/* + [ + ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], + ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], + ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], + ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], + ] +*/ +``` -The `unique` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [`uniqueStrict`](#method-uniquestrict) method to filter using "strict" comparisons. +The `unique` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [uniqueStrict](#method-uniquestrict) method to filter using "strict" comparisons. -> {tip} This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-unique). +> [!NOTE] +> This method's behavior is modified when using [Eloquent Collections](/docs/{{version}}/eloquent-collections#method-unique). #### `uniqueStrict()` {.collection-method} -This method has the same signature as the [`unique`](#method-unique) method; however, all values are compared using "strict" comparisons. +This method has the same signature as the [unique](#method-unique) method; however, all values are compared using "strict" comparisons. #### `unless()` {.collection-method} -The `unless` method will execute the given callback unless the first argument given to the method evaluates to `true`: +The `unless` method will execute the given callback unless the first argument given to the method evaluates to `true`. The collection instance and the first argument given to the `unless` method will be provided to the closure: - $collection = collect([1, 2, 3]); +```php +$collection = collect([1, 2, 3]); - $collection->unless(true, function ($collection) { - return $collection->push(4); - }); +$collection->unless(true, function (Collection $collection, bool $value) { + return $collection->push(4); +}); - $collection->unless(false, function ($collection) { - return $collection->push(5); - }); +$collection->unless(false, function (Collection $collection, bool $value) { + return $collection->push(5); +}); - $collection->all(); +$collection->all(); - // [1, 2, 3, 5] +// [1, 2, 3, 5] +``` A second callback may be passed to the `unless` method. The second callback will be executed when the first argument given to the `unless` method evaluates to `true`: - $collection = collect([1, 2, 3]); +```php +$collection = collect([1, 2, 3]); - $collection->unless(true, function ($collection) { - return $collection->push(4); - }, function ($collection) { - return $collection->push(5); - }); +$collection->unless(true, function (Collection $collection, bool $value) { + return $collection->push(4); +}, function (Collection $collection, bool $value) { + return $collection->push(5); +}); - $collection->all(); +$collection->all(); - // [1, 2, 3, 5] +// [1, 2, 3, 5] +``` -For the inverse of `unless`, see the [`when`](#method-when) method. +For the inverse of `unless`, see the [when](#method-when) method. #### `unlessEmpty()` {.collection-method} -Alias for the [`whenNotEmpty`](#method-whennotempty) method. +Alias for the [whenNotEmpty](#method-whennotempty) method. #### `unlessNotEmpty()` {.collection-method} -Alias for the [`whenEmpty`](#method-whenempty) method. +Alias for the [whenEmpty](#method-whenempty) method. #### `unwrap()` {.collection-method} The static `unwrap` method returns the collection's underlying items from the given value when applicable: - Collection::unwrap(collect('John Doe')); +```php +Collection::unwrap(collect('John Doe')); - // ['John Doe'] +// ['John Doe'] - Collection::unwrap(['John Doe']); +Collection::unwrap(['John Doe']); + +// ['John Doe'] + +Collection::unwrap('John Doe'); + +// 'John Doe' +``` - // ['John Doe'] + +#### `value()` {.collection-method} - Collection::unwrap('John Doe'); +The `value` method retrieves a given value from the first element of the collection: - // 'John Doe' +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Speaker', 'price' => 400], +]); + +$value = $collection->value('price'); + +// 200 +``` #### `values()` {.collection-method} The `values` method returns a new collection with the keys reset to consecutive integers: - $collection = collect([ - 10 => ['product' => 'Desk', 'price' => 200], - 11 => ['product' => 'Desk', 'price' => 200], - ]); +```php +$collection = collect([ + 10 => ['product' => 'Desk', 'price' => 200], + 11 => ['product' => 'Desk', 'price' => 200], +]); - $values = $collection->values(); +$values = $collection->values(); - $values->all(); +$values->all(); - /* - [ - 0 => ['product' => 'Desk', 'price' => 200], - 1 => ['product' => 'Desk', 'price' => 200], - ] - */ +/* + [ + 0 => ['product' => 'Desk', 'price' => 200], + 1 => ['product' => 'Desk', 'price' => 200], + ] +*/ +``` #### `when()` {.collection-method} -The `when` method will execute the given callback when the first argument given to the method evaluates to `true`: +The `when` method will execute the given callback when the first argument given to the method evaluates to `true`. The collection instance and the first argument given to the `when` method will be provided to the closure: - $collection = collect([1, 2, 3]); +```php +$collection = collect([1, 2, 3]); - $collection->when(true, function ($collection) { - return $collection->push(4); - }); +$collection->when(true, function (Collection $collection, bool $value) { + return $collection->push(4); +}); - $collection->when(false, function ($collection) { - return $collection->push(5); - }); +$collection->when(false, function (Collection $collection, bool $value) { + return $collection->push(5); +}); - $collection->all(); +$collection->all(); - // [1, 2, 3, 4] +// [1, 2, 3, 4] +``` A second callback may be passed to the `when` method. The second callback will be executed when the first argument given to the `when` method evaluates to `false`: - $collection = collect([1, 2, 3]); +```php +$collection = collect([1, 2, 3]); - $collection->when(false, function ($collection) { - return $collection->push(4); - }, function ($collection) { - return $collection->push(5); - }); +$collection->when(false, function (Collection $collection, bool $value) { + return $collection->push(4); +}, function (Collection $collection, bool $value) { + return $collection->push(5); +}); - $collection->all(); +$collection->all(); - // [1, 2, 3, 5] +// [1, 2, 3, 5] +``` -For the inverse of `when`, see the [`unless`](#method-unless) method. +For the inverse of `when`, see the [unless](#method-unless) method. #### `whenEmpty()` {.collection-method} The `whenEmpty` method will execute the given callback when the collection is empty: - $collection = collect(['Michael', 'Tom']); +```php +$collection = collect(['Michael', 'Tom']); - $collection->whenEmpty(function ($collection) { - return $collection->push('Adam'); - }); - - $collection->all(); +$collection->whenEmpty(function (Collection $collection) { + return $collection->push('Adam'); +}); - // ['Michael', 'Tom'] +$collection->all(); +// ['Michael', 'Tom'] - $collection = collect(); +$collection = collect(); - $collection->whenEmpty(function ($collection) { - return $collection->push('Adam'); - }); +$collection->whenEmpty(function (Collection $collection) { + return $collection->push('Adam'); +}); - $collection->all(); +$collection->all(); - // ['Adam'] +// ['Adam'] +``` A second closure may be passed to the `whenEmpty` method that will be executed when the collection is not empty: - $collection = collect(['Michael', 'Tom']); +```php +$collection = collect(['Michael', 'Tom']); - $collection->whenEmpty(function ($collection) { - return $collection->push('Adam'); - }, function ($collection) { - return $collection->push('Taylor'); - }); +$collection->whenEmpty(function (Collection $collection) { + return $collection->push('Adam'); +}, function (Collection $collection) { + return $collection->push('Taylor'); +}); - $collection->all(); +$collection->all(); - // ['Michael', 'Tom', 'Taylor'] +// ['Michael', 'Tom', 'Taylor'] +``` -For the inverse of `whenEmpty`, see the [`whenNotEmpty`](#method-whennotempty) method. +For the inverse of `whenEmpty`, see the [whenNotEmpty](#method-whennotempty) method. #### `whenNotEmpty()` {.collection-method} The `whenNotEmpty` method will execute the given callback when the collection is not empty: - $collection = collect(['michael', 'tom']); +```php +$collection = collect(['Michael', 'Tom']); - $collection->whenNotEmpty(function ($collection) { - return $collection->push('adam'); - }); +$collection->whenNotEmpty(function (Collection $collection) { + return $collection->push('Adam'); +}); - $collection->all(); +$collection->all(); - // ['michael', 'tom', 'adam'] +// ['Michael', 'Tom', 'Adam'] +$collection = collect(); - $collection = collect(); +$collection->whenNotEmpty(function (Collection $collection) { + return $collection->push('Adam'); +}); - $collection->whenNotEmpty(function ($collection) { - return $collection->push('adam'); - }); - - $collection->all(); +$collection->all(); - // [] +// [] +``` A second closure may be passed to the `whenNotEmpty` method that will be executed when the collection is empty: - $collection = collect(); +```php +$collection = collect(); - $collection->whenNotEmpty(function ($collection) { - return $collection->push('adam'); - }, function ($collection) { - return $collection->push('taylor'); - }); +$collection->whenNotEmpty(function (Collection $collection) { + return $collection->push('Adam'); +}, function (Collection $collection) { + return $collection->push('Taylor'); +}); - $collection->all(); +$collection->all(); - // ['taylor'] +// ['Taylor'] +``` -For the inverse of `whenNotEmpty`, see the [`whenEmpty`](#method-whenempty) method. +For the inverse of `whenNotEmpty`, see the [whenEmpty](#method-whenempty) method. #### `where()` {.collection-method} The `where` method filters the collection by a given key / value pair: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Chair', 'price' => 100], - ['product' => 'Bookcase', 'price' => 150], - ['product' => 'Door', 'price' => 100], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Chair', 'price' => 100], + ['product' => 'Bookcase', 'price' => 150], + ['product' => 'Door', 'price' => 100], +]); - $filtered = $collection->where('price', 100); +$filtered = $collection->where('price', 100); - $filtered->all(); +$filtered->all(); - /* - [ - ['product' => 'Chair', 'price' => 100], - ['product' => 'Door', 'price' => 100], - ] - */ +/* + [ + ['product' => 'Chair', 'price' => 100], + ['product' => 'Door', 'price' => 100], + ] +*/ +``` -The `where` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [`whereStrict`](#method-wherestrict) method to filter using "strict" comparisons. +The `where` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [whereStrict](#method-wherestrict) method to filter using "strict" comparisons, or the [whereNull](#method-wherenull) and [whereNotNull](#method-wherenotnull) methods to filter for `null` values. -Optionally, you may pass a comparison operator as the second parameter. +Optionally, you may pass a comparison operator as the second parameter. Supported operators are: '===', '!==', '!=', '==', '=', '<>', '>', '<', '>=', and '<=': - $collection = collect([ - ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'], - ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'], - ['name' => 'Sue', 'deleted_at' => null], - ]); +```php +$collection = collect([ + ['name' => 'Jim', 'platform' => 'Mac'], + ['name' => 'Sally', 'platform' => 'Mac'], + ['name' => 'Sue', 'platform' => 'Linux'], +]); - $filtered = $collection->where('deleted_at', '!=', null); +$filtered = $collection->where('platform', '!=', 'Linux'); - $filtered->all(); +$filtered->all(); - /* - [ - ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'], - ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'], - ] - */ +/* + [ + ['name' => 'Jim', 'platform' => 'Mac'], + ['name' => 'Sally', 'platform' => 'Mac'], + ] +*/ +``` #### `whereStrict()` {.collection-method} -This method has the same signature as the [`where`](#method-where) method; however, all values are compared using "strict" comparisons. +This method has the same signature as the [where](#method-where) method; however, all values are compared using "strict" comparisons. #### `whereBetween()` {.collection-method} The `whereBetween` method filters the collection by determining if a specified item value is within a given range: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Chair', 'price' => 80], - ['product' => 'Bookcase', 'price' => 150], - ['product' => 'Pencil', 'price' => 30], - ['product' => 'Door', 'price' => 100], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Chair', 'price' => 80], + ['product' => 'Bookcase', 'price' => 150], + ['product' => 'Pencil', 'price' => 30], + ['product' => 'Door', 'price' => 100], +]); - $filtered = $collection->whereBetween('price', [100, 200]); +$filtered = $collection->whereBetween('price', [100, 200]); - $filtered->all(); +$filtered->all(); - /* - [ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Bookcase', 'price' => 150], - ['product' => 'Door', 'price' => 100], - ] - */ +/* + [ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Bookcase', 'price' => 150], + ['product' => 'Door', 'price' => 100], + ] +*/ +``` #### `whereIn()` {.collection-method} The `whereIn` method removes elements from the collection that do not have a specified item value that is contained within the given array: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Chair', 'price' => 100], - ['product' => 'Bookcase', 'price' => 150], - ['product' => 'Door', 'price' => 100], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Chair', 'price' => 100], + ['product' => 'Bookcase', 'price' => 150], + ['product' => 'Door', 'price' => 100], +]); - $filtered = $collection->whereIn('price', [150, 200]); +$filtered = $collection->whereIn('price', [150, 200]); - $filtered->all(); +$filtered->all(); - /* - [ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Bookcase', 'price' => 150], - ] - */ +/* + [ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Bookcase', 'price' => 150], + ] +*/ +``` -The `whereIn` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [`whereInStrict`](#method-whereinstrict) method to filter using "strict" comparisons. +The `whereIn` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [whereInStrict](#method-whereinstrict) method to filter using "strict" comparisons. #### `whereInStrict()` {.collection-method} -This method has the same signature as the [`whereIn`](#method-wherein) method; however, all values are compared using "strict" comparisons. +This method has the same signature as the [whereIn](#method-wherein) method; however, all values are compared using "strict" comparisons. #### `whereInstanceOf()` {.collection-method} The `whereInstanceOf` method filters the collection by a given class type: - use App\Models\User; - use App\Models\Post; +```php +use App\Models\User; +use App\Models\Post; - $collection = collect([ - new User, - new User, - new Post, - ]); +$collection = collect([ + new User, + new User, + new Post, +]); - $filtered = $collection->whereInstanceOf(User::class); +$filtered = $collection->whereInstanceOf(User::class); - $filtered->all(); +$filtered->all(); - // [App\Models\User, App\Models\User] +// [App\Models\User, App\Models\User] +``` #### `whereNotBetween()` {.collection-method} The `whereNotBetween` method filters the collection by determining if a specified item value is outside of a given range: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Chair', 'price' => 80], - ['product' => 'Bookcase', 'price' => 150], - ['product' => 'Pencil', 'price' => 30], - ['product' => 'Door', 'price' => 100], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Chair', 'price' => 80], + ['product' => 'Bookcase', 'price' => 150], + ['product' => 'Pencil', 'price' => 30], + ['product' => 'Door', 'price' => 100], +]); - $filtered = $collection->whereNotBetween('price', [100, 200]); +$filtered = $collection->whereNotBetween('price', [100, 200]); - $filtered->all(); +$filtered->all(); - /* - [ - ['product' => 'Chair', 'price' => 80], - ['product' => 'Pencil', 'price' => 30], - ] - */ +/* + [ + ['product' => 'Chair', 'price' => 80], + ['product' => 'Pencil', 'price' => 30], + ] +*/ +``` #### `whereNotIn()` {.collection-method} The `whereNotIn` method removes elements from the collection that have a specified item value that is contained within the given array: - $collection = collect([ - ['product' => 'Desk', 'price' => 200], - ['product' => 'Chair', 'price' => 100], - ['product' => 'Bookcase', 'price' => 150], - ['product' => 'Door', 'price' => 100], - ]); +```php +$collection = collect([ + ['product' => 'Desk', 'price' => 200], + ['product' => 'Chair', 'price' => 100], + ['product' => 'Bookcase', 'price' => 150], + ['product' => 'Door', 'price' => 100], +]); - $filtered = $collection->whereNotIn('price', [150, 200]); +$filtered = $collection->whereNotIn('price', [150, 200]); - $filtered->all(); +$filtered->all(); - /* - [ - ['product' => 'Chair', 'price' => 100], - ['product' => 'Door', 'price' => 100], - ] - */ +/* + [ + ['product' => 'Chair', 'price' => 100], + ['product' => 'Door', 'price' => 100], + ] +*/ +``` -The `whereNotIn` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [`whereNotInStrict`](#method-wherenotinstrict) method to filter using "strict" comparisons. +The `whereNotIn` method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the [whereNotInStrict](#method-wherenotinstrict) method to filter using "strict" comparisons. #### `whereNotInStrict()` {.collection-method} -This method has the same signature as the [`whereNotIn`](#method-wherenotin) method; however, all values are compared using "strict" comparisons. +This method has the same signature as the [whereNotIn](#method-wherenotin) method; however, all values are compared using "strict" comparisons. #### `whereNotNull()` {.collection-method} The `whereNotNull` method returns items from the collection where the given key is not `null`: - $collection = collect([ - ['name' => 'Desk'], - ['name' => null], - ['name' => 'Bookcase'], - ]); +```php +$collection = collect([ + ['name' => 'Desk'], + ['name' => null], + ['name' => 'Bookcase'], + ['name' => 0], + ['name' => ''], +]); - $filtered = $collection->whereNotNull('name'); +$filtered = $collection->whereNotNull('name'); - $filtered->all(); +$filtered->all(); - /* - [ - ['name' => 'Desk'], - ['name' => 'Bookcase'], - ] - */ +/* + [ + ['name' => 'Desk'], + ['name' => 'Bookcase'], + ['name' => 0], + ['name' => ''], + ] +*/ +``` #### `whereNull()` {.collection-method} The `whereNull` method returns items from the collection where the given key is `null`: - $collection = collect([ - ['name' => 'Desk'], - ['name' => null], - ['name' => 'Bookcase'], - ]); - - $filtered = $collection->whereNull('name'); +```php +$collection = collect([ + ['name' => 'Desk'], + ['name' => null], + ['name' => 'Bookcase'], + ['name' => 0], + ['name' => ''], +]); - $filtered->all(); +$filtered = $collection->whereNull('name'); - /* - [ - ['name' => null], - ] - */ +$filtered->all(); +/* + [ + ['name' => null], + ] +*/ +``` #### `wrap()` {.collection-method} The static `wrap` method wraps the given value in a collection when applicable: - use Illuminate\Support\Collection; +```php +use Illuminate\Support\Collection; - $collection = Collection::wrap('John Doe'); +$collection = Collection::wrap('John Doe'); - $collection->all(); +$collection->all(); - // ['John Doe'] +// ['John Doe'] - $collection = Collection::wrap(['John Doe']); +$collection = Collection::wrap(['John Doe']); - $collection->all(); +$collection->all(); - // ['John Doe'] +// ['John Doe'] - $collection = Collection::wrap(collect('John Doe')); +$collection = Collection::wrap(collect('John Doe')); - $collection->all(); +$collection->all(); - // ['John Doe'] +// ['John Doe'] +``` #### `zip()` {.collection-method} The `zip` method merges together the values of the given array with the values of the original collection at their corresponding index: - $collection = collect(['Chair', 'Desk']); +```php +$collection = collect(['Chair', 'Desk']); - $zipped = $collection->zip([100, 200]); +$zipped = $collection->zip([100, 200]); - $zipped->all(); +$zipped->all(); - // [['Chair', 100], ['Desk', 200]] +// [['Chair', 100], ['Desk', 200]] +``` ## Higher Order Messages -Collections also provide support for "higher order messages", which are short-cuts for performing common actions on collections. The collection methods that provide higher order messages are: [`average`](#method-average), [`avg`](#method-avg), [`contains`](#method-contains), [`each`](#method-each), [`every`](#method-every), [`filter`](#method-filter), [`first`](#method-first), [`flatMap`](#method-flatmap), [`groupBy`](#method-groupby), [`keyBy`](#method-keyby), [`map`](#method-map), [`max`](#method-max), [`min`](#method-min), [`partition`](#method-partition), [`reject`](#method-reject), [`skipUntil`](#method-skipuntil), [`skipWhile`](#method-skipwhile), [`some`](#method-some), [`sortBy`](#method-sortby), [`sortByDesc`](#method-sortbydesc), [`sum`](#method-sum), [`takeUntil`](#method-takeuntil), [`takeWhile`](#method-takewhile), and [`unique`](#method-unique). +Collections also provide support for "higher order messages", which are short-cuts for performing common actions on collections. The collection methods that provide higher order messages are: [average](#method-average), [avg](#method-avg), [contains](#method-contains), [each](#method-each), [every](#method-every), [filter](#method-filter), [first](#method-first), [flatMap](#method-flatmap), [groupBy](#method-groupby), [keyBy](#method-keyby), [map](#method-map), [max](#method-max), [min](#method-min), [partition](#method-partition), [reject](#method-reject), [skipUntil](#method-skipuntil), [skipWhile](#method-skipwhile), [some](#method-some), [sortBy](#method-sortby), [sortByDesc](#method-sortbydesc), [sum](#method-sum), [takeUntil](#method-takeuntil), [takeWhile](#method-takewhile), and [unique](#method-unique). Each higher order message can be accessed as a dynamic property on a collection instance. For instance, let's use the `each` higher order message to call a method on each object within a collection: - use App\Models\User; +```php +use App\Models\User; - $users = User::where('votes', '>', 500)->get(); +$users = User::where('votes', '>', 500)->get(); - $users->each->markAsVip(); +$users->each->markAsVip(); +``` Likewise, we can use the `sum` higher order message to gather the total number of "votes" for a collection of users: - $users = User::where('group', 'Development')->get(); +```php +$users = User::where('group', 'Development')->get(); - return $users->sum->votes; +return $users->sum->votes; +``` ## Lazy Collections @@ -3188,68 +4036,94 @@ Likewise, we can use the `sum` higher order message to gather the total number o ### Introduction -> {note} Before learning more about Laravel's lazy collections, take some time to familiarize yourself with [PHP generators](https://www.php.net/manual/en/language.generators.overview.php). +> [!WARNING] +> Before learning more about Laravel's lazy collections, take some time to familiarize yourself with [PHP generators](https://www.php.net/manual/en/language.generators.overview.php). To supplement the already powerful `Collection` class, the `LazyCollection` class leverages PHP's [generators](https://www.php.net/manual/en/language.generators.overview.php) to allow you to work with very large datasets while keeping memory usage low. For example, imagine your application needs to process a multi-gigabyte log file while taking advantage of Laravel's collection methods to parse the logs. Instead of reading the entire file into memory at once, lazy collections may be used to keep only a small part of the file in memory at a given time: - use App\Models\LogEntry; - use Illuminate\Support\LazyCollection; +```php +use App\Models\LogEntry; +use Illuminate\Support\LazyCollection; - LazyCollection::make(function () { - $handle = fopen('log.txt', 'r'); +LazyCollection::make(function () { + $handle = fopen('log.txt', 'r'); - while (($line = fgets($handle)) !== false) { - yield $line; - } - })->chunk(4)->map(function ($lines) { - return LogEntry::fromLines($lines); - })->each(function (LogEntry $logEntry) { - // Process the log entry... - }); + while (($line = fgets($handle)) !== false) { + yield $line; + } + + fclose($handle); +})->chunk(4)->map(function (array $lines) { + return LogEntry::fromLines($lines); +})->each(function (LogEntry $logEntry) { + // Process the log entry... +}); +``` Or, imagine you need to iterate through 10,000 Eloquent models. When using traditional Laravel collections, all 10,000 Eloquent models must be loaded into memory at the same time: - use App\Models\User; +```php +use App\Models\User; - $users = User::all()->filter(function ($user) { - return $user->id > 500; - }); +$users = User::all()->filter(function (User $user) { + return $user->id > 500; +}); +``` However, the query builder's `cursor` method returns a `LazyCollection` instance. This allows you to still only run a single query against the database but also only keep one Eloquent model loaded in memory at a time. In this example, the `filter` callback is not executed until we actually iterate over each user individually, allowing for a drastic reduction in memory usage: - use App\Models\User; +```php +use App\Models\User; - $users = User::cursor()->filter(function ($user) { - return $user->id > 500; - }); +$users = User::cursor()->filter(function (User $user) { + return $user->id > 500; +}); - foreach ($users as $user) { - echo $user->id; - } +foreach ($users as $user) { + echo $user->id; +} +``` ### Creating Lazy Collections To create a lazy collection instance, you should pass a PHP generator function to the collection's `make` method: - use Illuminate\Support\LazyCollection; +```php +use Illuminate\Support\LazyCollection; - LazyCollection::make(function () { - $handle = fopen('log.txt', 'r'); +LazyCollection::make(function () { + $handle = fopen('log.txt', 'r'); - while (($line = fgets($handle)) !== false) { - yield $line; - } - }); + while (($line = fgets($handle)) !== false) { + yield $line; + } + + fclose($handle); +}); +``` ### The Enumerable Contract Almost all methods available on the `Collection` class are also available on the `LazyCollection` class. Both of these classes implement the `Illuminate\Support\Enumerable` contract, which defines the following methods: -
+ + +
[all](#method-all) [average](#method-average) @@ -3278,6 +4152,7 @@ Almost all methods available on the `Collection` class are also available on the [except](#method-except) [filter](#method-filter) [first](#method-first) +[firstOrFail](#method-first-or-fail) [firstWhere](#method-first-where) [flatMap](#method-flatmap) [flatten](#method-flatten) @@ -3288,6 +4163,7 @@ Almost all methods available on the `Collection` class are also available on the [has](#method-has) [implode](#method-implode) [intersect](#method-intersect) +[intersectAssoc](#method-intersectAssoc) [intersectByKeys](#method-intersectbykeys) [isEmpty](#method-isempty) [isNotEmpty](#method-isnotempty) @@ -3324,6 +4200,7 @@ Almost all methods available on the `Collection` class are also available on the [shuffle](#method-shuffle) [skip](#method-skip) [slice](#method-slice) +[sole](#method-sole) [some](#method-some) [sort](#method-sort) [sortBy](#method-sortby) @@ -3362,7 +4239,8 @@ Almost all methods available on the `Collection` class are also available on the
-> {note} Methods that mutate the collection (such as `shift`, `pop`, `prepend` etc.) are **not** available on the `LazyCollection` class. +> [!WARNING] +> Methods that mutate the collection (such as `shift`, `pop`, `prepend` etc.) are **not** available on the `LazyCollection` class. ### Lazy Collection Methods @@ -3374,61 +4252,111 @@ In addition to the methods defined in the `Enumerable` contract, the `LazyCollec The `takeUntilTimeout` method returns a new lazy collection that will enumerate values until the specified time. After that time, the collection will then stop enumerating: - $lazyCollection = LazyCollection::times(INF) - ->takeUntilTimeout(now()->addMinute()); +```php +$lazyCollection = LazyCollection::times(INF) + ->takeUntilTimeout(now()->addMinute()); - $lazyCollection->each(function ($number) { - dump($number); +$lazyCollection->each(function (int $number) { + dump($number); - sleep(1); - }); + sleep(1); +}); - // 1 - // 2 - // ... - // 58 - // 59 +// 1 +// 2 +// ... +// 58 +// 59 +``` To illustrate the usage of this method, imagine an application that submits invoices from the database using a cursor. You could define a [scheduled task](/docs/{{version}}/scheduling) that runs every 15 minutes and only processes invoices for a maximum of 14 minutes: - use App\Models\Invoice; - use Illuminate\Support\Carbon; +```php +use App\Models\Invoice; +use Illuminate\Support\Carbon; - Invoice::pending()->cursor() - ->takeUntilTimeout( - Carbon::createFromTimestamp(LARAVEL_START)->add(14, 'minutes') - ) - ->each(fn ($invoice) => $invoice->submit()); +Invoice::pending()->cursor() + ->takeUntilTimeout( + Carbon::createFromTimestamp(LARAVEL_START)->add(14, 'minutes') + ) + ->each(fn (Invoice $invoice) => $invoice->submit()); +``` #### `tapEach()` {.collection-method} While the `each` method calls the given callback for each item in the collection right away, the `tapEach` method only calls the given callback as the items are being pulled out of the list one by one: - // Nothing has been dumped so far... - $lazyCollection = LazyCollection::times(INF)->tapEach(function ($value) { - dump($value); - }); +```php +// Nothing has been dumped so far... +$lazyCollection = LazyCollection::times(INF)->tapEach(function (int $value) { + dump($value); +}); - // Three items are dumped... - $array = $lazyCollection->take(3)->all(); +// Three items are dumped... +$array = $lazyCollection->take(3)->all(); - // 1 - // 2 - // 3 +// 1 +// 2 +// 3 +``` + + +#### `throttle()` {.collection-method} + +The `throttle` method will throttle the lazy collection such that each value is returned after the specified number of seconds. This method is especially useful for situations where you may be interacting with external APIs that rate limit incoming requests: + +```php +use App\Models\User; + +User::where('vip', true) + ->cursor() + ->throttle(seconds: 1) + ->each(function (User $user) { + // Call external API... + }); +``` #### `remember()` {.collection-method} The `remember` method returns a new lazy collection that will remember any values that have already been enumerated and will not retrieve them again on subsequent collection enumerations: - // No query has been executed yet... - $users = User::cursor()->remember(); +```php +// No query has been executed yet... +$users = User::cursor()->remember(); + +// The query is executed... +// The first 5 users are hydrated from the database... +$users->take(5)->all(); - // The query is executed... - // The first 5 users are hydrated from the database... - $users->take(5)->all(); +// First 5 users come from the collection's cache... +// The rest are hydrated from the database... +$users->take(20)->all(); +``` + + +#### `withHeartbeat()` {.collection-method} + +The `withHeartbeat` method allows you to execute a callback at regular time intervals while a lazy collection is being enumerated. This is particularly useful for long-running operations that require periodic maintenance tasks, such as extending locks or sending progress updates: + +```php +use Carbon\CarbonInterval; +use Illuminate\Support\Facades\Cache; - // First 5 users come from the collection's cache... - // The rest are hydrated from the database... - $users->take(20)->all(); +$lock = Cache::lock('generate-reports', seconds: 60 * 5); + +if ($lock->get()) { + try { + Report::where('status', 'pending') + ->lazy() + ->withHeartbeat( + CarbonInterval::minutes(4), + fn () => $lock->extend(CarbonInterval::minutes(5)) + ) + ->each(fn ($report) => $report->process()); + } finally { + $lock->release(); + } +} +``` diff --git a/concurrency.md b/concurrency.md new file mode 100644 index 00000000000..9a412ee2b60 --- /dev/null +++ b/concurrency.md @@ -0,0 +1,67 @@ +# Concurrency + +- [Introduction](#introduction) +- [Running Concurrent Tasks](#running-concurrent-tasks) +- [Deferring Concurrent Tasks](#deferring-concurrent-tasks) + + +## Introduction + +Sometimes you may need to execute several slow tasks which do not depend on one another. In many cases, significant performance improvements can be realized by executing the tasks concurrently. Laravel's `Concurrency` facade provides a simple, convenient API for executing closures concurrently. + + +#### How it Works + +Laravel achieves concurrency by serializing the given closures and dispatching them to a hidden Artisan CLI command, which unserializes the closures and invokes it within its own PHP process. After the closure has been invoked, the resulting value is serialized back to the parent process. + +The `Concurrency` facade supports three drivers: `process` (the default), `fork`, and `sync`. + +The `fork` driver offers improved performance compared to the default `process` driver, but it may only be used within PHP's CLI context, as PHP does not support forking during web requests. Before using the `fork` driver, you need to install the `spatie/fork` package: + +```shell +composer require spatie/fork +``` + +The `sync` driver is primarily useful during testing when you want to disable all concurrency and simply execute the given closures in sequence within the parent process. + + +## Running Concurrent Tasks + +To run concurrent tasks, you may invoke the `Concurrency` facade's `run` method. The `run` method accepts an array of closures which should be executed simultaneously in child PHP processes: + +```php +use Illuminate\Support\Facades\Concurrency; +use Illuminate\Support\Facades\DB; + +[$userCount, $orderCount] = Concurrency::run([ + fn () => DB::table('users')->count(), + fn () => DB::table('orders')->count(), +]); +``` + +To use a specific driver, you may use the `driver` method: + +```php +$results = Concurrency::driver('fork')->run(...); +``` + +Or, to change the default concurrency driver, you should publish the `concurrency` configuration file via the `config:publish` Artisan command and update the `default` option within the file: + +```shell +php artisan config:publish concurrency +``` + + +## Deferring Concurrent Tasks + +If you would like to execute an array of closures concurrently, but are not interested in the results returned by those closures, you should consider using the `defer` method. When the `defer` method is invoked, the given closures are not executed immediately. Instead, Laravel will execute the closures concurrently after the HTTP response has been sent to the user: + +```php +use App\Services\Metrics; +use Illuminate\Support\Facades\Concurrency; + +Concurrency::defer([ + fn () => Metrics::report('users'), + fn () => Metrics::report('orders'), +]); +``` diff --git a/configuration.md b/configuration.md index ba2622647cb..2e56183b1f5 100644 --- a/configuration.md +++ b/configuration.md @@ -4,9 +4,11 @@ - [Environment Configuration](#environment-configuration) - [Environment Variable Types](#environment-variable-types) - [Retrieving Environment Configuration](#retrieving-environment-configuration) - - [Determining The Current Environment](#determining-the-current-environment) + - [Determining the Current Environment](#determining-the-current-environment) + - [Encrypting Environment Files](#encrypting-environment-files) - [Accessing Configuration Values](#accessing-configuration-values) - [Configuration Caching](#configuration-caching) +- [Configuration Publishing](#configuration-publishing) - [Debug Mode](#debug-mode) - [Maintenance Mode](#maintenance-mode) @@ -15,7 +17,28 @@ All of the configuration files for the Laravel framework are stored in the `config` directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you. -These configuration files allow you to configure things like your database connection information, your mail server information, as well as various other core configuration values such as your application timezone and encryption key. +These configuration files allow you to configure things like your database connection information, your mail server information, as well as various other core configuration values such as your application URL and encryption key. + + +#### The `about` Command + +Laravel can display an overview of your application's configuration, drivers, and environment via the `about` Artisan command. + +```shell +php artisan about +``` + +If you're only interested in a particular section of the application overview output, you may filter for that section using the `--only` option: + +```shell +php artisan about --only=environment +``` + +Or, to explore a specific configuration file's values in detail, you may use the `config:show` Artisan command: + +```shell +php artisan config:show database +``` ## Environment Configuration @@ -24,37 +47,44 @@ It is often helpful to have different configuration values based on the environm To make this a cinch, Laravel utilizes the [DotEnv](https://github.com/vlucas/phpdotenv) PHP library. In a fresh Laravel installation, the root directory of your application will contain a `.env.example` file that defines many common environment variables. During the Laravel installation process, this file will automatically be copied to `.env`. -Laravel's default `.env` file contains some common configuration values that may differ based on whether your application is running locally or on a production web server. These values are then retrieved from various Laravel configuration files within the `config` directory using Laravel's `env` function. +Laravel's default `.env` file contains some common configuration values that may differ based on whether your application is running locally or on a production web server. These values are then read by the configuration files within the `config` directory using Laravel's `env` function. -If you are developing with a team, you may wish to continue including a `.env.example` file with your application. By putting placeholder values in the example configuration file, other developers on your team can clearly see which environment variables are needed to run your application. +If you are developing with a team, you may wish to continue including and updating the `.env.example` file with your application. By putting placeholder values in the example configuration file, other developers on your team can clearly see which environment variables are needed to run your application. -> {tip} Any variable in your `.env` file can be overridden by external environment variables such as server-level or system-level environment variables. +> [!NOTE] +> Any variable in your `.env` file can be overridden by external environment variables such as server-level or system-level environment variables. #### Environment File Security Your `.env` file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration. Furthermore, this would be a security risk in the event an intruder gains access to your source control repository, since any sensitive credentials would get exposed. +However, it is possible to encrypt your environment file using Laravel's built-in [environment encryption](#encrypting-environment-files). Encrypted environment files may be placed in source control safely. + #### Additional Environment Files -Before loading your application's environment variables, Laravel determines if either the `APP_ENV` environment variable has been externally provided or if the `--env` CLI argument has been specified. If so, Laravel will attempt to load an `.env.[APP_ENV]` file if it exists. If it does not exist, the default `.env` file will be loaded. +Before loading your application's environment variables, Laravel determines if an `APP_ENV` environment variable has been externally provided or if the `--env` CLI argument has been specified. If so, Laravel will attempt to load an `.env.[APP_ENV]` file if it exists. If it does not exist, the default `.env` file will be loaded. ### Environment Variable Types All variables in your `.env` files are typically parsed as strings, so some reserved values have been created to allow you to return a wider range of types from the `env()` function: -`.env` Value | `env()` Value -------------- | ------------- -true | (bool) true -(true) | (bool) true -false | (bool) false -(false) | (bool) false -empty | (string) '' -(empty) | (string) '' -null | (null) null -(null) | (null) null +
+ +| `.env` Value | `env()` Value | +| ------------ | ------------- | +| true | (bool) true | +| (true) | (bool) true | +| false | (bool) false | +| (false) | (bool) false | +| empty | (string) '' | +| (empty) | (string) '' | +| null | (null) null | +| (null) | (null) null | + +
If you need to define an environment variable with a value that contains spaces, you may do so by enclosing the value in double quotes: @@ -65,46 +95,138 @@ APP_NAME="My Application" ### Retrieving Environment Configuration -All of the variables listed in this file will be loaded into the `$_ENV` PHP super-global when your application receives a request. However, you may use the `env` helper to retrieve values from these variables in your configuration files. In fact, if you review the Laravel configuration files, you will notice many of the options are already using this helper: +All of the variables listed in the `.env` file will be loaded into the `$_ENV` PHP super-global when your application receives a request. However, you may use the `env` function to retrieve values from these variables in your configuration files. In fact, if you review the Laravel configuration files, you will notice many of the options are already using this function: - 'debug' => env('APP_DEBUG', false), +```php +'debug' => (bool) env('APP_DEBUG', false), +``` The second value passed to the `env` function is the "default value". This value will be returned if no environment variable exists for the given key. -### Determining The Current Environment +### Determining the Current Environment The current application environment is determined via the `APP_ENV` variable from your `.env` file. You may access this value via the `environment` method on the `App` [facade](/docs/{{version}}/facades): - use Illuminate\Support\Facades\App; +```php +use Illuminate\Support\Facades\App; - $environment = App::environment(); +$environment = App::environment(); +``` You may also pass arguments to the `environment` method to determine if the environment matches a given value. The method will return `true` if the environment matches any of the given values: - if (App::environment('local')) { - // The environment is local - } +```php +if (App::environment('local')) { + // The environment is local +} + +if (App::environment(['local', 'staging'])) { + // The environment is either local OR staging... +} +``` + +> [!NOTE] +> The current application environment detection can be overridden by defining a server-level `APP_ENV` environment variable. + + +### Encrypting Environment Files + +Unencrypted environment files should never be stored in source control. However, Laravel allows you to encrypt your environment files so that they may safely be added to source control with the rest of your application. + + +#### Encryption + +To encrypt an environment file, you may use the `env:encrypt` command: + +```shell +php artisan env:encrypt +``` + +Running the `env:encrypt` command will encrypt your `.env` file and place the encrypted contents in an `.env.encrypted` file. The decryption key is presented in the output of the command and should be stored in a secure password manager. If you would like to provide your own encryption key you may use the `--key` option when invoking the command: + +```shell +php artisan env:encrypt --key=3UVsEgGVK36XN82KKeyLFMhvosbZN1aF +``` + +> [!NOTE] +> The length of the key provided should match the key length required by the encryption cipher being used. By default, Laravel will use the `AES-256-CBC` cipher which requires a 32 character key. You are free to use any cipher supported by Laravel's [encrypter](/docs/{{version}}/encryption) by passing the `--cipher` option when invoking the command. + +If your application has multiple environment files, such as `.env` and `.env.staging`, you may specify the environment file that should be encrypted by providing the environment name via the `--env` option: + +```shell +php artisan env:encrypt --env=staging +``` + + +#### Decryption + +To decrypt an environment file, you may use the `env:decrypt` command. This command requires a decryption key, which Laravel will retrieve from the `LARAVEL_ENV_ENCRYPTION_KEY` environment variable: + +```shell +php artisan env:decrypt +``` + +Or, the key may be provided directly to the command via the `--key` option: + +```shell +php artisan env:decrypt --key=3UVsEgGVK36XN82KKeyLFMhvosbZN1aF +``` + +When the `env:decrypt` command is invoked, Laravel will decrypt the contents of the `.env.encrypted` file and place the decrypted contents in the `.env` file. + +The `--cipher` option may be provided to the `env:decrypt` command in order to use a custom encryption cipher: + +```shell +php artisan env:decrypt --key=qUWuNRdfuImXcKxZ --cipher=AES-128-CBC +``` + +If your application has multiple environment files, such as `.env` and `.env.staging`, you may specify the environment file that should be decrypted by providing the environment name via the `--env` option: + +```shell +php artisan env:decrypt --env=staging +``` - if (App::environment(['local', 'staging'])) { - // The environment is either local OR staging... - } +In order to overwrite an existing environment file, you may provide the `--force` option to the `env:decrypt` command: -> {tip} The current application environment detection can be overridden by defining a server-level `APP_ENV` environment variable. +```shell +php artisan env:decrypt --force +``` ## Accessing Configuration Values -You may easily access your configuration values using the global `config` helper function from anywhere in your application. The configuration values may be accessed using "dot" syntax, which includes the name of the file and option you wish to access. A default value may also be specified and will be returned if the configuration option does not exist: +You may easily access your configuration values using the `Config` facade or global `config` function from anywhere in your application. The configuration values may be accessed using "dot" syntax, which includes the name of the file and option you wish to access. A default value may also be specified and will be returned if the configuration option does not exist: + +```php +use Illuminate\Support\Facades\Config; - $value = config('app.timezone'); +$value = Config::get('app.timezone'); - // Retrieve a default value if the configuration value does not exist... - $value = config('app.timezone', 'Asia/Seoul'); +$value = config('app.timezone'); -To set configuration values at runtime, pass an array to the `config` helper: +// Retrieve a default value if the configuration value does not exist... +$value = config('app.timezone', 'Asia/Seoul'); +``` + +To set configuration values at runtime, you may invoke the `Config` facade's `set` method or pass an array to the `config` function: - config(['app.timezone' => 'America/Chicago']); +```php +Config::set('app.timezone', 'America/Chicago'); + +config(['app.timezone' => 'America/Chicago']); +``` + +To assist with static analysis, the `Config` facade also provides typed configuration retrieval methods. If the retrieved configuration value does not match the expected type, an exception will be thrown: + +```php +Config::string('config-key'); +Config::integer('config-key'); +Config::float('config-key'); +Config::boolean('config-key'); +Config::array('config-key'); +Config::collection('config-key'); +``` ## Configuration Caching @@ -113,14 +235,39 @@ To give your application a speed boost, you should cache all of your configurati You should typically run the `php artisan config:cache` command as part of your production deployment process. The command should not be run during local development as configuration options will frequently need to be changed during the course of your application's development. -> {note} If you execute the `config:cache` command during your deployment process, you should be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded; therefore, the `env` function will only return external, system level environment variables. +Once the configuration has been cached, your application's `.env` file will not be loaded by the framework during requests or Artisan commands; therefore, the `env` function will only return external, system level environment variables. + +For this reason, you should ensure you are only calling the `env` function from within your application's configuration (`config`) files. You can see many examples of this by examining Laravel's default configuration files. Configuration values may be accessed from anywhere in your application using the `config` function [described above](#accessing-configuration-values). + +The `config:clear` command may be used to purge the cached configuration: + +```shell +php artisan config:clear +``` + +> [!WARNING] +> If you execute the `config:cache` command during your deployment process, you should be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded; therefore, the `env` function will only return external, system level environment variables. + + +## Configuration Publishing + +Most of Laravel's configuration files are already published in your application's `config` directory; however, certain configuration files like `cors.php` and `view.php` are not published by default, as most applications will never need to modify them. + +However, you may use the `config:publish` Artisan command to publish any configuration files that are not published by default: + +```shell +php artisan config:publish + +php artisan config:publish --all +``` ## Debug Mode The `debug` option in your `config/app.php` configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the `APP_DEBUG` environment variable, which is stored in your `.env` file. -For local development, you should set the `APP_DEBUG` environment variable to `true`. **In your production environment, this value should always be `false`. If the variable is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.** +> [!WARNING] +> For local development, you should set the `APP_DEBUG` environment variable to `true`. **In your production environment, this value should always be `false`. If the variable is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.** ## Maintenance Mode @@ -148,7 +295,7 @@ php artisan down --retry=60 #### Bypassing Maintenance Mode -Even while in maintenance mode, you may use the `secret` option to specify a maintenance mode bypass token: +To allow maintenance mode to be bypassed using a secret token, you may use the `secret` option to specify a maintenance mode bypass token: ```shell php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515" @@ -160,12 +307,31 @@ After placing the application in maintenance mode, you may navigate to the appli https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515 ``` +If you would like Laravel to generate the secret token for you, you may use the `with-secret` option. The secret will be displayed to you once the application is in maintenance mode: + +```shell +php artisan down --with-secret +``` + When accessing this hidden route, you will then be redirected to the `/` route of the application. Once the cookie has been issued to your browser, you will be able to browse the application normally as if it was not in maintenance mode. -> {tip} Your maintenance mode secret should typically consist of alpha-numeric characters and, optionally, dashes. You should avoid using characters that have special meaning in URLs such as `?`. +> [!NOTE] +> Your maintenance mode secret should typically consist of alpha-numeric characters and, optionally, dashes. You should avoid using characters that have special meaning in URLs such as `?` or `&`. + + +#### Maintenance Mode on Multiple Servers + +By default, Laravel determines if your application is in maintenance mode using a file-based system. This means to activate maintenance mode, the `php artisan down` command has to be executed on each server hosting your application. + +Alternatively, Laravel offers a cache-based method for handling maintenance mode. This method requires running the `php artisan down` command on just one server. To use this approach, modify the maintenance mode variables in your application's `.env` file. You should select a cache `store` that is accessible by all of your servers. This ensures the maintenance mode status is consistently maintained across every server: + +```ini +APP_MAINTENANCE_DRIVER=cache +APP_MAINTENANCE_STORE=database +``` -#### Pre-Rendering The Maintenance Mode View +#### Pre-Rendering the Maintenance Mode View If you utilize the `php artisan down` command during deployment, your users may still occasionally encounter errors if they access the application while your Composer dependencies or other infrastructure components are updating. This occurs because a significant part of the Laravel framework must boot in order to determine your application is in maintenance mode and render the maintenance mode view using the templating engine. @@ -193,14 +359,15 @@ To disable maintenance mode, use the `up` command: php artisan up ``` -> {tip} You may customize the default maintenance mode template by defining your own template at `resources/views/errors/503.blade.php`. +> [!NOTE] +> You may customize the default maintenance mode template by defining your own template at `resources/views/errors/503.blade.php`. -#### Maintenance Mode & Queues +#### Maintenance Mode and Queues While your application is in maintenance mode, no [queued jobs](/docs/{{version}}/queues) will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode. -#### Alternatives To Maintenance Mode +#### Alternatives to Maintenance Mode -Since maintenance mode requires your application to have several seconds of downtime, consider alternatives like [Laravel Vapor](https://vapor.laravel.com) and [Envoyer](https://envoyer.io) to accomplish zero-downtime deployment with Laravel. +Since maintenance mode requires your application to have several seconds of downtime, consider running your applications on a fully-managed platform like [Laravel Cloud](https://cloud.laravel.com) to accomplish zero-downtime deployment with Laravel. diff --git a/console-tests.md b/console-tests.md index 871ab7fb204..a020c22c253 100644 --- a/console-tests.md +++ b/console-tests.md @@ -3,6 +3,7 @@ - [Introduction](#introduction) - [Success / Failure Expectations](#success-failure-expectations) - [Input / Output Expectations](#input-output-expectations) +- [Console Events](#console-events) ## Introduction @@ -14,79 +15,211 @@ In addition to simplifying HTTP testing, Laravel provides a simple API for testi To get started, let's explore how to make assertions regarding an Artisan command's exit code. To accomplish this, we will use the `artisan` method to invoke an Artisan command from our test. Then, we will use the `assertExitCode` method to assert that the command completed with a given exit code: - /** - * Test a console command. - * - * @return void - */ - public function test_console_command() - { - $this->artisan('inspire')->assertExitCode(0); - } +```php tab=Pest +test('console command', function () { + $this->artisan('inspire')->assertExitCode(0); +}); +``` + +```php tab=PHPUnit +/** + * Test a console command. + */ +public function test_console_command(): void +{ + $this->artisan('inspire')->assertExitCode(0); +} +``` You may use the `assertNotExitCode` method to assert that the command did not exit with a given exit code: - $this->artisan('inspire')->assertNotExitCode(1); +```php +$this->artisan('inspire')->assertNotExitCode(1); +``` Of course, all terminal commands typically exit with a status code of `0` when they are successful and a non-zero exit code when they are not successful. Therefore, for convenience, you may utilize the `assertSuccessful` and `assertFailed` assertions to assert that a given command exited with a successful exit code or not: - $this->artisan('inspire')->assertSuccessful(); +```php +$this->artisan('inspire')->assertSuccessful(); - $this->artisan('inspire')->assertFailed(); +$this->artisan('inspire')->assertFailed(); +``` ## Input / Output Expectations Laravel allows you to easily "mock" user input for your console commands using the `expectsQuestion` method. In addition, you may specify the exit code and text that you expect to be output by the console command using the `assertExitCode` and `expectsOutput` methods. For example, consider the following console command: - Artisan::command('question', function () { - $name = $this->ask('What is your name?'); - - $language = $this->choice('Which language do you prefer?', [ - 'PHP', - 'Ruby', - 'Python', - ]); - - $this->line('Your name is '.$name.' and you prefer '.$language.'.'); - }); - -You may test this command with the following test which utilizes the `expectsQuestion`, `expectsOutput`, `doesntExpectOutput`, and `assertExitCode` methods: - - /** - * Test a console command. - * - * @return void - */ - public function test_console_command() - { - $this->artisan('question') - ->expectsQuestion('What is your name?', 'Taylor Otwell') - ->expectsQuestion('Which language do you prefer?', 'PHP') - ->expectsOutput('Your name is Taylor Otwell and you prefer PHP.') - ->doesntExpectOutput('Your name is Taylor Otwell and you prefer Ruby.') - ->assertExitCode(0); - } +```php +Artisan::command('question', function () { + $name = $this->ask('What is your name?'); + + $language = $this->choice('Which language do you prefer?', [ + 'PHP', + 'Ruby', + 'Python', + ]); + + $this->line('Your name is '.$name.' and you prefer '.$language.'.'); +}); +``` + +You may test this command with the following test: + +```php tab=Pest +test('console command', function () { + $this->artisan('question') + ->expectsQuestion('What is your name?', 'Taylor Otwell') + ->expectsQuestion('Which language do you prefer?', 'PHP') + ->expectsOutput('Your name is Taylor Otwell and you prefer PHP.') + ->doesntExpectOutput('Your name is Taylor Otwell and you prefer Ruby.') + ->assertExitCode(0); +}); +``` + +```php tab=PHPUnit +/** + * Test a console command. + */ +public function test_console_command(): void +{ + $this->artisan('question') + ->expectsQuestion('What is your name?', 'Taylor Otwell') + ->expectsQuestion('Which language do you prefer?', 'PHP') + ->expectsOutput('Your name is Taylor Otwell and you prefer PHP.') + ->doesntExpectOutput('Your name is Taylor Otwell and you prefer Ruby.') + ->assertExitCode(0); +} +``` + +If you are utilizing the `search` or `multisearch` functions provided by [Laravel Prompts](/docs/{{version}}/prompts), you may use the `expectsSearch` assertion to mock the user's input, search results, and selection: + +```php tab=Pest +test('console command', function () { + $this->artisan('example') + ->expectsSearch('What is your name?', search: 'Tay', answers: [ + 'Taylor Otwell', + 'Taylor Swift', + 'Darian Taylor' + ], answer: 'Taylor Otwell') + ->assertExitCode(0); +}); +``` + +```php tab=PHPUnit +/** + * Test a console command. + */ +public function test_console_command(): void +{ + $this->artisan('example') + ->expectsSearch('What is your name?', search: 'Tay', answers: [ + 'Taylor Otwell', + 'Taylor Swift', + 'Darian Taylor' + ], answer: 'Taylor Otwell') + ->assertExitCode(0); +} +``` + +You may also assert that a console command does not generate any output using the `doesntExpectOutput` method: + +```php tab=Pest +test('console command', function () { + $this->artisan('example') + ->doesntExpectOutput() + ->assertExitCode(0); +}); +``` + +```php tab=PHPUnit +/** + * Test a console command. + */ +public function test_console_command(): void +{ + $this->artisan('example') + ->doesntExpectOutput() + ->assertExitCode(0); +} +``` + +The `expectsOutputToContain` and `doesntExpectOutputToContain` methods may be used to make assertions against a portion of the output: + +```php tab=Pest +test('console command', function () { + $this->artisan('example') + ->expectsOutputToContain('Taylor') + ->assertExitCode(0); +}); +``` + +```php tab=PHPUnit +/** + * Test a console command. + */ +public function test_console_command(): void +{ + $this->artisan('example') + ->expectsOutputToContain('Taylor') + ->assertExitCode(0); +} +``` #### Confirmation Expectations When writing a command which expects confirmation in the form of a "yes" or "no" answer, you may utilize the `expectsConfirmation` method: - $this->artisan('module:import') - ->expectsConfirmation('Do you really wish to run this command?', 'no') - ->assertExitCode(1); +```php +$this->artisan('module:import') + ->expectsConfirmation('Do you really wish to run this command?', 'no') + ->assertExitCode(1); +``` #### Table Expectations If your command displays a table of information using Artisan's `table` method, it can be cumbersome to write output expectations for the entire table. Instead, you may use the `expectsTable` method. This method accepts the table's headers as its first argument and the table's data as its second argument: - $this->artisan('users:all') - ->expectsTable([ - 'ID', - 'Email', - ], [ - [1, 'taylor@example.com'], - [2, 'abigail@example.com'], - ]); +```php +$this->artisan('users:all') + ->expectsTable([ + 'ID', + 'Email', + ], [ + [1, 'taylor@example.com'], + [2, 'abigail@example.com'], + ]); +``` + + +## Console Events + +By default, the `Illuminate\Console\Events\CommandStarting` and `Illuminate\Console\Events\CommandFinished` events are not dispatched while running your application's tests. However, you can enable these events for a given test class by adding the `Illuminate\Foundation\Testing\WithConsoleEvents` trait to the class: + +```php tab=Pest +use(WithConsoleEvents::class); + +// ... +``` + +```php tab=PHPUnit + @@ -25,49 +27,36 @@ The Laravel service container is a powerful tool for managing class dependencies Let's look at a simple example: - users = $users; - } - - /** - * Show the profile for the given user. - * - * @param int $id - * @return Response - */ - public function show($id) - { - $user = $this->users->find($id); - - return view('user.profile', ['user' => $user]); - } + return view('podcasts.show', [ + 'podcast' => $this->apple->findPodcast($id) + ]); } +} +``` -In this example, the `UserController` needs to retrieve users from a data source. So, we will **inject** a service that is able to retrieve users. In this context, our `UserRepository` most likely uses [Eloquent](/docs/{{version}}/eloquent) to retrieve user information from the database. However, since the repository is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the `UserRepository` when testing our application. +In this example, the `PodcastController` needs to retrieve podcasts from a data source such as Apple Music. So, we will **inject** a service that is able to retrieve podcasts. Since the service is injected, we are able to easily "mock", or create a dummy implementation of the `AppleMusic` service when testing our application. A deep understanding of the Laravel service container is essential to building a powerful, large application, as well as for contributing to the Laravel core itself. @@ -76,31 +65,35 @@ A deep understanding of the Laravel service container is essential to building a If a class has no dependencies or only depends on other concrete classes (not interfaces), the container does not need to be instructed on how to resolve that class. For example, you may place the following code in your `routes/web.php` file: - -### When To Use The Container +### When to Utilize the Container Thanks to zero configuration resolution, you will often type-hint dependencies on routes, controllers, event listeners, and elsewhere without ever manually interacting with the container. For example, you might type-hint the `Illuminate\Http\Request` object on your route definition so that you can easily access the current request. Even though we never have to interact with the container to write this code, it is managing the injection of these dependencies behind the scenes: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/', function (Request $request) { - // ... - }); +Route::get('/', function (Request $request) { + // ... +}); +``` In many cases, thanks to automatic dependency injection and [facades](/docs/{{version}}/facades), you can build Laravel applications without **ever** manually binding or resolving anything from the container. **So, when would you ever manually interact with the container?** Let's examine two situations. @@ -119,231 +112,486 @@ Almost all of your service container bindings will be registered within [service Within a service provider, you always have access to the container via the `$this->app` property. We can register a binding using the `bind` method, passing the class or interface name that we wish to register along with a closure that returns an instance of the class: - use App\Services\Transistor; - use App\Services\PodcastParser; +```php +use App\Services\Transistor; +use App\Services\PodcastParser; +use Illuminate\Contracts\Foundation\Application; - $this->app->bind(Transistor::class, function ($app) { - return new Transistor($app->make(PodcastParser::class)); - }); +$this->app->bind(Transistor::class, function (Application $app) { + return new Transistor($app->make(PodcastParser::class)); +}); +``` Note that we receive the container itself as an argument to the resolver. We can then use the container to resolve sub-dependencies of the object we are building. As mentioned, you will typically be interacting with the container within service providers; however, if you would like to interact with the container outside of a service provider, you may do so via the `App` [facade](/docs/{{version}}/facades): - use App\Services\Transistor; - use Illuminate\Support\Facades\App; +```php +use App\Services\Transistor; +use Illuminate\Contracts\Foundation\Application; +use Illuminate\Support\Facades\App; - App::bind(Transistor::class, function ($app) { - // ... - }); +App::bind(Transistor::class, function (Application $app) { + // ... +}); +``` + +You may use the `bindIf` method to register a container binding only if a binding has not already been registered for the given type: + +```php +$this->app->bindIf(Transistor::class, function (Application $app) { + return new Transistor($app->make(PodcastParser::class)); +}); +``` -> {tip} There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection. +For convenience, you may omit providing the class or interface name that you wish to register as a separate argument and instead allow Laravel to infer the type from the return type of the closure you provide to the `bind` method: + +```php +App::bind(function (Application $app): Transistor { + return new Transistor($app->make(PodcastParser::class)); +}); +``` + +> [!NOTE] +> There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection. #### Binding A Singleton The `singleton` method binds a class or interface into the container that should only be resolved one time. Once a singleton binding is resolved, the same object instance will be returned on subsequent calls into the container: - use App\Services\Transistor; - use App\Services\PodcastParser; +```php +use App\Services\Transistor; +use App\Services\PodcastParser; +use Illuminate\Contracts\Foundation\Application; - $this->app->singleton(Transistor::class, function ($app) { - return new Transistor($app->make(PodcastParser::class)); - }); +$this->app->singleton(Transistor::class, function (Application $app) { + return new Transistor($app->make(PodcastParser::class)); +}); +``` + +You may use the `singletonIf` method to register a singleton container binding only if a binding has not already been registered for the given type: + +```php +$this->app->singletonIf(Transistor::class, function (Application $app) { + return new Transistor($app->make(PodcastParser::class)); +}); +``` + + +#### Singleton Attribute + +Alternatively, you may mark an interface or class with the `#[Singleton]` attribute to indicate to the container that it should be resolved one time: + +```php + #### Binding Scoped Singletons The `scoped` method binds a class or interface into the container that should only be resolved one time within a given Laravel request / job lifecycle. While this method is similar to the `singleton` method, instances registered using the `scoped` method will be flushed whenever the Laravel application starts a new "lifecycle", such as when a [Laravel Octane](/docs/{{version}}/octane) worker processes a new request or when a Laravel [queue worker](/docs/{{version}}/queues) processes a new job: - use App\Services\Transistor; - use App\Services\PodcastParser; +```php +use App\Services\Transistor; +use App\Services\PodcastParser; +use Illuminate\Contracts\Foundation\Application; - $this->app->scoped(Transistor::class, function ($app) { - return new Transistor($app->make(PodcastParser::class)); - }); +$this->app->scoped(Transistor::class, function (Application $app) { + return new Transistor($app->make(PodcastParser::class)); +}); +``` + +You may use the `scopedIf` method to register a scoped container binding only if a binding has not already been registered for the given type: + +```php +$this->app->scopedIf(Transistor::class, function (Application $app) { + return new Transistor($app->make(PodcastParser::class)); +}); +``` + + +#### Scoped Attribute + +Alternatively, you may mark an interface or class with the `#[Scoped]` attribute to indicate to the container that it should be resolved one time within a given Laravel request / job lifecycle: + +```php + #### Binding Instances You may also bind an existing object instance into the container using the `instance` method. The given instance will always be returned on subsequent calls into the container: - use App\Services\Transistor; - use App\Services\PodcastParser; +```php +use App\Services\Transistor; +use App\Services\PodcastParser; - $service = new Transistor(new PodcastParser); +$service = new Transistor(new PodcastParser); - $this->app->instance(Transistor::class, $service); +$this->app->instance(Transistor::class, $service); +``` -### Binding Interfaces To Implementations +### Binding Interfaces to Implementations A very powerful feature of the service container is its ability to bind an interface to a given implementation. For example, let's assume we have an `EventPusher` interface and a `RedisEventPusher` implementation. Once we have coded our `RedisEventPusher` implementation of this interface, we can register it with the service container like so: - use App\Contracts\EventPusher; - use App\Services\RedisEventPusher; +```php +use App\Contracts\EventPusher; +use App\Services\RedisEventPusher; - $this->app->bind(EventPusher::class, RedisEventPusher::class); +$this->app->bind(EventPusher::class, RedisEventPusher::class); +``` This statement tells the container that it should inject the `RedisEventPusher` when a class needs an implementation of `EventPusher`. Now we can type-hint the `EventPusher` interface in the constructor of a class that is resolved by the container. Remember, controllers, event listeners, middleware, and various other types of classes within Laravel applications are always resolved using the container: - use App\Contracts\EventPusher; +```php +use App\Contracts\EventPusher; - /** - * Create a new class instance. - * - * @param \App\Contracts\EventPusher $pusher - * @return void - */ - public function __construct(EventPusher $pusher) - { - $this->pusher = $pusher; - } +/** + * Create a new class instance. + */ +public function __construct( + protected EventPusher $pusher, +) {} +``` + + +#### Bind Attribute + +Laravel also provides a `Bind` attribute for added convenience. You can apply this attribute to any interface to tell Laravel which implementation should be automatically injected whenever that interface is requested. When using the `Bind` attribute, there is no need to perform any additional service registration in your application's service providers. + +In addition, multiple `Bind` attributes may be placed on an interface in order to configure a different implementation that should be injected for a given set of environments: + +```php + ### Contextual Binding Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, two controllers may depend on different implementations of the `Illuminate\Contracts\Filesystem\Filesystem` [contract](/docs/{{version}}/contracts). Laravel provides a simple, fluent interface for defining this behavior: - use App\Http\Controllers\PhotoController; - use App\Http\Controllers\UploadController; - use App\Http\Controllers\VideoController; - use Illuminate\Contracts\Filesystem\Filesystem; - use Illuminate\Support\Facades\Storage; +```php +use App\Http\Controllers\PhotoController; +use App\Http\Controllers\UploadController; +use App\Http\Controllers\VideoController; +use Illuminate\Contracts\Filesystem\Filesystem; +use Illuminate\Support\Facades\Storage; + +$this->app->when(PhotoController::class) + ->needs(Filesystem::class) + ->give(function () { + return Storage::disk('local'); + }); + +$this->app->when([VideoController::class, UploadController::class]) + ->needs(Filesystem::class) + ->give(function () { + return Storage::disk('s3'); + }); +``` + + +### Contextual Attributes + +Since contextual binding is often used to inject implementations of drivers or configuration values, Laravel offers a variety of contextual binding attributes that allow to inject these types of values without manually defining the contextual bindings in your service providers. + +For example, the `Storage` attribute may be used to inject a specific [storage disk](/docs/{{version}}/filesystem): + +```php +middleware('auth'); +``` + + +#### Defining Custom Attributes + +You can create your own contextual attributes by implementing the `Illuminate\Contracts\Container\ContextualAttribute` contract. The container will call your attribute's `resolve` method, which should resolve the value that should be injected into the class utilizing the attribute. In the example below, we will re-implement Laravel's built-in `Config` attribute: + +```php +app->when(PhotoController::class) - ->needs(Filesystem::class) - ->give(function () { - return Storage::disk('local'); - }); +namespace App\Attributes; - $this->app->when([VideoController::class, UploadController::class]) - ->needs(Filesystem::class) - ->give(function () { - return Storage::disk('s3'); - }); +use Attribute; +use Illuminate\Contracts\Container\Container; +use Illuminate\Contracts\Container\ContextualAttribute; + +#[Attribute(Attribute::TARGET_PARAMETER)] +class Config implements ContextualAttribute +{ + /** + * Create a new attribute instance. + */ + public function __construct(public string $key, public mixed $default = null) + { + } + + /** + * Resolve the configuration value. + * + * @param self $attribute + * @param \Illuminate\Contracts\Container\Container $container + * @return mixed + */ + public static function resolve(self $attribute, Container $container) + { + return $container->make('config')->get($attribute->key, $attribute->default); + } +} +``` ### Binding Primitives Sometimes you may have a class that receives some injected classes, but also needs an injected primitive value such as an integer. You may easily use contextual binding to inject any value your class may need: - $this->app->when('App\Http\Controllers\UserController') - ->needs('$variableName') - ->give($value); +```php +use App\Http\Controllers\UserController; + +$this->app->when(UserController::class) + ->needs('$variableName') + ->give($value); +``` Sometimes a class may depend on an array of [tagged](#tagging) instances. Using the `giveTagged` method, you may easily inject all of the container bindings with that tag: - $this->app->when(ReportAggregator::class) - ->needs('$reports') - ->giveTagged('reports'); +```php +$this->app->when(ReportAggregator::class) + ->needs('$reports') + ->giveTagged('reports'); +``` If you need to inject a value from one of your application's configuration files, you may use the `giveConfig` method: - $this->app->when(ReportAggregator::class) - ->needs('$timezone') - ->giveConfig('app.timezone'); +```php +$this->app->when(ReportAggregator::class) + ->needs('$timezone') + ->giveConfig('app.timezone'); +``` ### Binding Typed Variadics Occasionally, you may have a class that receives an array of typed objects using a variadic constructor argument: - logger = $logger; - $this->filters = $filters; - } +class Firewall +{ + /** + * The filter instances. + * + * @var array + */ + protected $filters; + + /** + * Create a new class instance. + */ + public function __construct( + protected Logger $logger, + Filter ...$filters, + ) { + $this->filters = $filters; } +} +``` Using contextual binding, you may resolve this dependency by providing the `give` method with a closure that returns an array of resolved `Filter` instances: - $this->app->when(Firewall::class) - ->needs(Filter::class) - ->give(function ($app) { - return [ - $app->make(NullFilter::class), - $app->make(ProfanityFilter::class), - $app->make(TooLongFilter::class), - ]; - }); +```php +$this->app->when(Firewall::class) + ->needs(Filter::class) + ->give(function (Application $app) { + return [ + $app->make(NullFilter::class), + $app->make(ProfanityFilter::class), + $app->make(TooLongFilter::class), + ]; + }); +``` For convenience, you may also just provide an array of class names to be resolved by the container whenever `Firewall` needs `Filter` instances: - $this->app->when(Firewall::class) - ->needs(Filter::class) - ->give([ - NullFilter::class, - ProfanityFilter::class, - TooLongFilter::class, - ]); +```php +$this->app->when(Firewall::class) + ->needs(Filter::class) + ->give([ + NullFilter::class, + ProfanityFilter::class, + TooLongFilter::class, + ]); +``` #### Variadic Tag Dependencies Sometimes a class may have a variadic dependency that is type-hinted as a given class (`Report ...$reports`). Using the `needs` and `giveTagged` methods, you may easily inject all of the container bindings with that [tag](#tagging) for the given dependency: - $this->app->when(ReportAggregator::class) - ->needs(Report::class) - ->giveTagged('reports'); +```php +$this->app->when(ReportAggregator::class) + ->needs(Report::class) + ->giveTagged('reports'); +``` ### Tagging Occasionally, you may need to resolve all of a certain "category" of binding. For example, perhaps you are building a report analyzer that receives an array of many different `Report` interface implementations. After registering the `Report` implementations, you can assign them a tag using the `tag` method: - $this->app->bind(CpuReport::class, function () { - // - }); +```php +$this->app->bind(CpuReport::class, function () { + // ... +}); - $this->app->bind(MemoryReport::class, function () { - // - }); +$this->app->bind(MemoryReport::class, function () { + // ... +}); - $this->app->tag([CpuReport::class, MemoryReport::class], 'reports'); +$this->app->tag([CpuReport::class, MemoryReport::class], 'reports'); +``` Once the services have been tagged, you may easily resolve them all via the container's `tagged` method: - $this->app->bind(ReportAnalyzer::class, function ($app) { - return new ReportAnalyzer($app->tagged('reports')); - }); +```php +$this->app->bind(ReportAnalyzer::class, function (Application $app) { + return new ReportAnalyzer($app->tagged('reports')); +}); +``` ### Extending Bindings -The `extend` method allows the modification of resolved services. For example, when a service is resolved, you may run additional code to decorate or configure the service. The `extend` method accepts a closure, which should return the modified service, as its only argument. The closure receives the service being resolved and the container instance: +The `extend` method allows the modification of resolved services. For example, when a service is resolved, you may run additional code to decorate or configure the service. The `extend` method accepts two arguments, the service class you're extending and a closure that should return the modified service. The closure receives the service being resolved and the container instance: - $this->app->extend(Service::class, function ($service, $app) { - return new DecoratedService($service); - }); +```php +$this->app->extend(Service::class, function (Service $service, Application $app) { + return new DecoratedService($service); +}); +``` ## Resolving @@ -353,153 +601,189 @@ The `extend` method allows the modification of resolved services. For example, w You may use the `make` method to resolve a class instance from the container. The `make` method accepts the name of the class or interface you wish to resolve: - use App\Services\Transistor; +```php +use App\Services\Transistor; - $transistor = $this->app->make(Transistor::class); +$transistor = $this->app->make(Transistor::class); +``` -If some of your class' dependencies are not resolvable via the container, you may inject them by passing them as an associative array into the `makeWith` method. For example, we may manually pass the `$id` constructor argument required by the `Transistor` service: +If some of your class's dependencies are not resolvable via the container, you may inject them by passing them as an associative array into the `makeWith` method. For example, we may manually pass the `$id` constructor argument required by the `Transistor` service: - use App\Services\Transistor; +```php +use App\Services\Transistor; - $transistor = $this->app->makeWith(Transistor::class, ['id' => 1]); +$transistor = $this->app->makeWith(Transistor::class, ['id' => 1]); +``` -If you are outside of a service provider in a location of your code that does not have access to the `$app` variable, you may use the `App` [facade](/docs/{{version}}/facades) to resolve a class instance from the container: +The `bound` method may be used to determine if a class or interface has been explicitly bound in the container: - use App\Services\Transistor; - use Illuminate\Support\Facades\App; +```php +if ($this->app->bound(Transistor::class)) { + // ... +} +``` - $transistor = App::make(Transistor::class); +If you are outside of a service provider in a location of your code that does not have access to the `$app` variable, you may use the `App` [facade](/docs/{{version}}/facades) or the `app` [helper](/docs/{{version}}/helpers#method-app) to resolve a class instance from the container: -If you would like to have the Laravel container instance itself injected into a class that is being resolved by the container, you may type-hint the `Illuminate\Container\Container` class on your class' constructor: +```php +use App\Services\Transistor; +use Illuminate\Support\Facades\App; - use Illuminate\Container\Container; +$transistor = App::make(Transistor::class); - /** - * Create a new class instance. - * - * @param \Illuminate\Container\Container $container - * @return void - */ - public function __construct(Container $container) - { - $this->container = $container; - } +$transistor = app(Transistor::class); +``` + +If you would like to have the Laravel container instance itself injected into a class that is being resolved by the container, you may type-hint the `Illuminate\Container\Container` class on your class's constructor: + +```php +use Illuminate\Container\Container; + +/** + * Create a new class instance. + */ +public function __construct( + protected Container $container, +) {} +``` ### Automatic Injection Alternatively, and importantly, you may type-hint the dependency in the constructor of a class that is resolved by the container, including [controllers](/docs/{{version}}/controllers), [event listeners](/docs/{{version}}/events), [middleware](/docs/{{version}}/middleware), and more. Additionally, you may type-hint dependencies in the `handle` method of [queued jobs](/docs/{{version}}/queues). In practice, this is how most of your objects should be resolved by the container. -For example, you may type-hint a repository defined by your application in a controller's constructor. The repository will automatically be resolved and injected into the class: +For example, you may type-hint a service defined by your application in a controller's constructor. The service will automatically be resolved and injected into the class: - users = $users; - } - - /** - * Show the user with the given ID. - * - * @param int $id - * @return \Illuminate\Http\Response - */ - public function show($id) - { - // - } + return $this->apple->findPodcast($id); } +} +``` -## Method Invocation & Injection +## Method Invocation and Injection Sometimes you may wish to invoke a method on an object instance while allowing the container to automatically inject that method's dependencies. For example, given the following class: - ## Container Events The service container fires an event each time it resolves an object. You may listen to this event using the `resolving` method: - use App\Services\Transistor; +```php +use App\Services\Transistor; +use Illuminate\Contracts\Foundation\Application; - $this->app->resolving(Transistor::class, function ($transistor, $app) { - // Called when container resolves objects of type "Transistor"... - }); +$this->app->resolving(Transistor::class, function (Transistor $transistor, Application $app) { + // Called when container resolves objects of type "Transistor"... +}); - $this->app->resolving(function ($object, $app) { - // Called when container resolves object of any type... - }); +$this->app->resolving(function (mixed $object, Application $app) { + // Called when container resolves object of any type... +}); +``` As you can see, the object being resolved will be passed to the callback, allowing you to set any additional properties on the object before it is given to its consumer. + +### Rebinding + +The `rebinding` method allows you to listen for when a service is re-bound to the container, meaning it is registered again or overridden after its initial binding. This can be useful when you need to update dependencies or modify behavior each time a specific binding is updated: + +```php +use App\Contracts\PodcastPublisher; +use App\Services\SpotifyPublisher; +use App\Services\TransistorPublisher; +use Illuminate\Contracts\Foundation\Application; + +$this->app->bind(PodcastPublisher::class, SpotifyPublisher::class); + +$this->app->rebinding( + PodcastPublisher::class, + function (Application $app, PodcastPublisher $newInstance) { + // + }, +); + +// New binding will trigger rebinding closure... +$this->app->bind(PodcastPublisher::class, TransistorPublisher::class); +``` + ## PSR-11 Laravel's service container implements the [PSR-11](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md) interface. Therefore, you may type-hint the PSR-11 container interface to obtain an instance of the Laravel container: - use App\Services\Transistor; - use Psr\Container\ContainerInterface; +```php +use App\Services\Transistor; +use Psr\Container\ContainerInterface; - Route::get('/', function (ContainerInterface $container) { - $service = $container->get(Transistor::class); +Route::get('/', function (ContainerInterface $container) { + $service = $container->get(Transistor::class); - // - }); + // ... +}); +``` An exception is thrown if the given identifier can't be resolved. The exception will be an instance of `Psr\Container\NotFoundExceptionInterface` if the identifier was never bound. If the identifier was bound but was unable to be resolved, an instance of `Psr\Container\ContainerExceptionInterface` will be thrown. diff --git a/context.md b/context.md new file mode 100644 index 00000000000..4ccf8c03576 --- /dev/null +++ b/context.md @@ -0,0 +1,453 @@ +# Context + +- [Introduction](#introduction) + - [How it Works](#how-it-works) +- [Capturing Context](#capturing-context) + - [Stacks](#stacks) +- [Retrieving Context](#retrieving-context) + - [Determining Item Existence](#determining-item-existence) +- [Removing Context](#removing-context) +- [Hidden Context](#hidden-context) +- [Events](#events) + - [Dehydrating](#dehydrating) + - [Hydrated](#hydrated) + + +## Introduction + +Laravel's "context" capabilities enable you to capture, retrieve, and share information throughout requests, jobs, and commands executing within your application. This captured information is also included in logs written by your application, giving you deeper insight into the surrounding code execution history that occurred before a log entry was written and allowing you to trace execution flows throughout a distributed system. + + +### How it Works + +The best way to understand Laravel's context capabilities is to see it in action using the built-in logging features. To get started, you may [add information to the context](#capturing-context) using the `Context` facade. In this example, we will use a [middleware](/docs/{{version}}/middleware) to add the request URL and a unique trace ID to the context on every incoming request: + +```php +url()); + Context::add('trace_id', Str::uuid()->toString()); + + return $next($request); + } +} +``` + +Information added to the context is automatically appended as metadata to any [log entries](/docs/{{version}}/logging) that are written throughout the request. Appending context as metadata allows information passed to individual log entries to be differentiated from the information shared via `Context`. For example, imagine we write the following log entry: + +```php +Log::info('User authenticated.', ['auth_id' => Auth::id()]); +``` + +The written log will contain the `auth_id` passed to the log entry, but it will also contain the context's `url` and `trace_id` as metadata: + +```text +User authenticated. {"auth_id":27} {"url":"https://example.com/login","trace_id":"e04e1a11-e75c-4db3-b5b5-cfef4ef56697"} +``` + +Information added to the context is also made available to jobs dispatched to the queue. For example, imagine we dispatch a `ProcessPodcast` job to the queue after adding some information to the context: + +```php +// In our middleware... +Context::add('url', $request->url()); +Context::add('trace_id', Str::uuid()->toString()); + +// In our controller... +ProcessPodcast::dispatch($podcast); +``` + +When the job is dispatched, any information currently stored in the context is captured and shared with the job. The captured information is then hydrated back into the current context while the job is executing. So, if our job's handle method was to write to the log: + +```php +class ProcessPodcast implements ShouldQueue +{ + use Queueable; + + // ... + + /** + * Execute the job. + */ + public function handle(): void + { + Log::info('Processing podcast.', [ + 'podcast_id' => $this->podcast->id, + ]); + + // ... + } +} +``` + +The resulting log entry would contain the information that was added to the context during the request that originally dispatched the job: + +```text +Processing podcast. {"podcast_id":95} {"url":"https://example.com/login","trace_id":"e04e1a11-e75c-4db3-b5b5-cfef4ef56697"} +``` + +Although we have focused on the built-in logging related features of Laravel's context, the following documentation will illustrate how context allows you to share information across the HTTP request / queued job boundary and even how to add [hidden context data](#hidden-context) that is not written with log entries. + + +## Capturing Context + +You may store information in the current context using the `Context` facade's `add` method: + +```php +use Illuminate\Support\Facades\Context; + +Context::add('key', 'value'); +``` + +To add multiple items at once, you may pass an associative array to the `add` method: + +```php +Context::add([ + 'first_key' => 'value', + 'second_key' => 'value', +]); +``` + +The `add` method will override any existing value that shares the same key. If you only wish to add information to the context if the key does not already exist, you may use the `addIf` method: + +```php +Context::add('key', 'first'); + +Context::get('key'); +// "first" + +Context::addIf('key', 'second'); + +Context::get('key'); +// "first" +``` + +Context also provides convenient methods for incrementing or decrementing a given key. Both of these methods accept at least one argument: the key to track. A second argument may be provided to specify the amount by which the key should be incremented or decremented: + +```php +Context::increment('records_added'); +Context::increment('records_added', 5); + +Context::decrement('records_added'); +Context::decrement('records_added', 5); +``` + + +#### Conditional Context + +The `when` method may be used to add data to the context based on a given condition. The first closure provided to the `when` method will be invoked if the given condition evaluates to `true`, while the second closure will be invoked if the condition evaluates to `false`: + +```php +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Context; + +Context::when( + Auth::user()->isAdmin(), + fn ($context) => $context->add('permissions', Auth::user()->permissions), + fn ($context) => $context->add('permissions', []), +); +``` + + +#### Scoped Context + +The `scope` method provides a way to temporarily modify the context during the execution of a given callback and restore the context to its original state when the callback finishes executing. Additionally, you can pass extra data that should be merged into the context (as the second and third arguments) while the closure executes. + +```php +use Illuminate\Support\Facades\Context; +use Illuminate\Support\Facades\Log; + +Context::add('trace_id', 'abc-999'); +Context::addHidden('user_id', 123); + +Context::scope( + function () { + Context::add('action', 'adding_friend'); + + $userId = Context::getHidden('user_id'); + + Log::debug("Adding user [{$userId}] to friends list."); + // Adding user [987] to friends list. {"trace_id":"abc-999","user_name":"taylor_otwell","action":"adding_friend"} + }, + data: ['user_name' => 'taylor_otwell'], + hidden: ['user_id' => 987], +); + +Context::all(); +// [ +// 'trace_id' => 'abc-999', +// ] + +Context::allHidden(); +// [ +// 'user_id' => 123, +// ] +``` + +> [!WARNING] +> If an object within the context is modified inside the scoped closure, that mutation will be reflected outside of the scope. + + +### Stacks + +Context offers the ability to create "stacks", which are lists of data stored in the order that they were added. You can add information to a stack by invoking the `push` method: + +```php +use Illuminate\Support\Facades\Context; + +Context::push('breadcrumbs', 'first_value'); + +Context::push('breadcrumbs', 'second_value', 'third_value'); + +Context::get('breadcrumbs'); +// [ +// 'first_value', +// 'second_value', +// 'third_value', +// ] +``` + +Stacks can be useful to capture historical information about a request, such as events that are happening throughout your application. For example, you could create an event listener to push to a stack every time a query is executed, capturing the query SQL and duration as a tuple: + +```php +use Illuminate\Support\Facades\Context; +use Illuminate\Support\Facades\DB; + +// In AppServiceProvider.php... +DB::listen(function ($event) { + Context::push('queries', [$event->time, $event->sql]); +}); +``` + +You may determine if a value is in a stack using the `stackContains` and `hiddenStackContains` methods: + +```php +if (Context::stackContains('breadcrumbs', 'first_value')) { + // +} + +if (Context::hiddenStackContains('secrets', 'first_value')) { + // +} +``` + +The `stackContains` and `hiddenStackContains` methods also accept a closure as their second argument, allowing more control over the value comparison operation: + +```php +use Illuminate\Support\Facades\Context; +use Illuminate\Support\Str; + +return Context::stackContains('breadcrumbs', function ($value) { + return Str::startsWith($value, 'query_'); +}); +``` + + +## Retrieving Context + +You may retrieve information from the context using the `Context` facade's `get` method: + +```php +use Illuminate\Support\Facades\Context; + +$value = Context::get('key'); +``` + +The `only` and `except` methods may be used to retrieve a subset of the information in the context: + +```php +$data = Context::only(['first_key', 'second_key']); + +$data = Context::except(['first_key']); +``` + +The `pull` method may be used to retrieve information from the context and immediately remove it from the context: + +```php +$value = Context::pull('key'); +``` + +If context data is stored in a [stack](#stacks), you may pop items from the stack using the `pop` method: + +```php +Context::push('breadcrumbs', 'first_value', 'second_value'); + +Context::pop('breadcrumbs'); +// second_value + +Context::get('breadcrumbs'); +// ['first_value'] +``` + +The `remember` and `rememberHidden` methods may be used to retrieve information from the context, while setting the context value to the value returned by the given closure if the requested information doesn't exist: + +```php +$permissions = Context::remember( + 'user-permissions', + fn () => $user->permissions, +); +``` + +If you would like to retrieve all of the information stored in the context, you may invoke the `all` method: + +```php +$data = Context::all(); +``` + + +### Determining Item Existence + +You may use the `has` and `missing` methods to determine if the context has any value stored for the given key: + +```php +use Illuminate\Support\Facades\Context; + +if (Context::has('key')) { + // ... +} + +if (Context::missing('key')) { + // ... +} +``` + +The `has` method will return `true` regardless of the value stored. So, for example, a key with a `null` value will be considered present: + +```php +Context::add('key', null); + +Context::has('key'); +// true +``` + + +## Removing Context + +The `forget` method may be used to remove a key and its value from the current context: + +```php +use Illuminate\Support\Facades\Context; + +Context::add(['first_key' => 1, 'second_key' => 2]); + +Context::forget('first_key'); + +Context::all(); + +// ['second_key' => 2] +``` + +You may forget several keys at once by providing an array to the `forget` method: + +```php +Context::forget(['first_key', 'second_key']); +``` + + +## Hidden Context + +Context offers the ability to store "hidden" data. This hidden information is not appended to logs, and is not accessible via the data retrieval methods documented above. Context provides a different set of methods to interact with hidden context information: + +```php +use Illuminate\Support\Facades\Context; + +Context::addHidden('key', 'value'); + +Context::getHidden('key'); +// 'value' + +Context::get('key'); +// null +``` + +The "hidden" methods mirror the functionality of the non-hidden methods documented above: + +```php +Context::addHidden(/* ... */); +Context::addHiddenIf(/* ... */); +Context::pushHidden(/* ... */); +Context::getHidden(/* ... */); +Context::pullHidden(/* ... */); +Context::popHidden(/* ... */); +Context::onlyHidden(/* ... */); +Context::exceptHidden(/* ... */); +Context::allHidden(/* ... */); +Context::hasHidden(/* ... */); +Context::missingHidden(/* ... */); +Context::forgetHidden(/* ... */); +``` + + +## Events + +Context dispatches two events that allow you to hook into the hydration and dehydration process of the context. + +To illustrate how these events may be used, imagine that in a middleware of your application you set the `app.locale` configuration value based on the incoming HTTP request's `Accept-Language` header. Context's events allow you to capture this value during the request and restore it on the queue, ensuring notifications sent on the queue have the correct `app.locale` value. We can use context's events and [hidden](#hidden-context) data to achieve this, which the following documentation will illustrate. + + +### Dehydrating + +Whenever a job is dispatched to the queue the data in the context is "dehydrated" and captured alongside the job's payload. The `Context::dehydrating` method allows you to register a closure that will be invoked during the dehydration process. Within this closure, you may make changes to the data that will be shared with the queued job. + +Typically, you should register `dehydrating` callbacks within the `boot` method of your application's `AppServiceProvider` class: + +```php +use Illuminate\Log\Context\Repository; +use Illuminate\Support\Facades\Config; +use Illuminate\Support\Facades\Context; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Context::dehydrating(function (Repository $context) { + $context->addHidden('locale', Config::get('app.locale')); + }); +} +``` + +> [!NOTE] +> You should not use the `Context` facade within the `dehydrating` callback, as that will change the context of the current process. Ensure you only make changes to the repository passed to the callback. + + +### Hydrated + +Whenever a queued job begins executing on the queue, any context that was shared with the job will be "hydrated" back into the current context. The `Context::hydrated` method allows you to register a closure that will be invoked during the hydration process. + +Typically, you should register `hydrated` callbacks within the `boot` method of your application's `AppServiceProvider` class: + +```php +use Illuminate\Log\Context\Repository; +use Illuminate\Support\Facades\Config; +use Illuminate\Support\Facades\Context; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Context::hydrated(function (Repository $context) { + if ($context->hasHidden('locale')) { + Config::set('app.locale', $context->getHidden('locale')); + } + }); +} +``` + +> [!NOTE] +> You should not use the `Context` facade within the `hydrated` callback and instead ensure you only make changes to the repository passed to the callback. diff --git a/contracts.md b/contracts.md index 635c7eba54c..f33ad86969a 100644 --- a/contracts.md +++ b/contracts.md @@ -1,9 +1,9 @@ # Contracts - [Introduction](#introduction) - - [Contracts Vs. Facades](#contracts-vs-facades) -- [When To Use Contracts](#when-to-use-contracts) -- [How To Use Contracts](#how-to-use-contracts) + - [Contracts vs. Facades](#contracts-vs-facades) +- [When to Use Contracts](#when-to-use-contracts) +- [How to Use Contracts](#how-to-use-contracts) - [Contract Reference](#contract-reference) @@ -11,26 +11,26 @@ Laravel's "contracts" are a set of interfaces that define the core services provided by the framework. For example, an `Illuminate\Contracts\Queue\Queue` contract defines the methods needed for queueing jobs, while the `Illuminate\Contracts\Mail\Mailer` contract defines the methods needed for sending e-mail. -Each contract has a corresponding implementation provided by the framework. For example, Laravel provides a queue implementation with a variety of drivers, and a mailer implementation that is powered by [Symfony Mailer](https://symfony.com/doc/6.0/mailer.html). +Each contract has a corresponding implementation provided by the framework. For example, Laravel provides a queue implementation with a variety of drivers, and a mailer implementation that is powered by [Symfony Mailer](https://symfony.com/doc/current/mailer.html). All of the Laravel contracts live in [their own GitHub repository](https://github.com/illuminate/contracts). This provides a quick reference point for all available contracts, as well as a single, decoupled package that may be utilized when building packages that interact with Laravel services. -### Contracts Vs. Facades +### Contracts vs. Facades Laravel's [facades](/docs/{{version}}/facades) and helper functions provide a simple way of utilizing Laravel's services without needing to type-hint and resolve contracts out of the service container. In most cases, each facade has an equivalent contract. Unlike facades, which do not require you to require them in your class' constructor, contracts allow you to define explicit dependencies for your classes. Some developers prefer to explicitly define their dependencies in this way and therefore prefer to use contracts, while other developers enjoy the convenience of facades. **In general, most applications can use facades without issue during development.** -## When To Use Contracts +## When to Use Contracts The decision to use contracts or facades will come down to personal taste and the tastes of your development team. Both contracts and facades can be used to create robust, well-tested Laravel applications. Contracts and facades are not mutually exclusive. Some parts of your applications may use facades while others depend on contracts. As long as you are keeping your class' responsibilities focused, you will notice very few practical differences between using contracts and facades. In general, most applications can use facades without issue during development. If you are building a package that integrates with multiple PHP frameworks you may wish to use the `illuminate/contracts` package to define your integration with Laravel's services without the need to require Laravel's concrete implementations in your package's `composer.json` file. -## How To Use Contracts +## How to Use Contracts So, how do you get an implementation of a contract? It's actually quite simple. @@ -38,45 +38,33 @@ Many types of classes in Laravel are resolved through the [service container](/d For example, take a look at this event listener: - redis = $redis; - } - - /** - * Handle the event. - * - * @param \App\Events\OrderWasPlaced $event - * @return void - */ - public function handle(OrderWasPlaced $event) - { - // - } + // ... } +} +``` When the event listener is resolved, the service container will read the type-hints on the constructor of the class, and inject the appropriate value. To learn more about registering things in the service container, check out [its documentation](/docs/{{version}}/container). @@ -85,84 +73,87 @@ When the event listener is resolved, the service container will read the type-hi This table provides a quick reference to all of the Laravel contracts and their equivalent facades: -Contract | References Facade -------------- | ------------- -[Illuminate\Contracts\Auth\Access\Authorizable](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Access/Authorizable.php) |   -[Illuminate\Contracts\Auth\Access\Gate](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Access/Gate.php) | `Gate` -[Illuminate\Contracts\Auth\Authenticatable](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Authenticatable.php) |   -[Illuminate\Contracts\Auth\CanResetPassword](https://github.com/illuminate/contracts/blob/{{version}}/Auth/CanResetPassword.php) |   -[Illuminate\Contracts\Auth\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Factory.php) | `Auth` -[Illuminate\Contracts\Auth\Guard](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Guard.php) | `Auth::guard()` -[Illuminate\Contracts\Auth\PasswordBroker](https://github.com/illuminate/contracts/blob/{{version}}/Auth/PasswordBroker.php) | `Password::broker()` -[Illuminate\Contracts\Auth\PasswordBrokerFactory](https://github.com/illuminate/contracts/blob/{{version}}/Auth/PasswordBrokerFactory.php) | `Password` -[Illuminate\Contracts\Auth\StatefulGuard](https://github.com/illuminate/contracts/blob/{{version}}/Auth/StatefulGuard.php) |   -[Illuminate\Contracts\Auth\SupportsBasicAuth](https://github.com/illuminate/contracts/blob/{{version}}/Auth/SupportsBasicAuth.php) |   -[Illuminate\Contracts\Auth\UserProvider](https://github.com/illuminate/contracts/blob/{{version}}/Auth/UserProvider.php) |   -[Illuminate\Contracts\Bus\Dispatcher](https://github.com/illuminate/contracts/blob/{{version}}/Bus/Dispatcher.php) | `Bus` -[Illuminate\Contracts\Bus\QueueingDispatcher](https://github.com/illuminate/contracts/blob/{{version}}/Bus/QueueingDispatcher.php) | `Bus::dispatchToQueue()` -[Illuminate\Contracts\Broadcasting\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Broadcasting/Factory.php) | `Broadcast` -[Illuminate\Contracts\Broadcasting\Broadcaster](https://github.com/illuminate/contracts/blob/{{version}}/Broadcasting/Broadcaster.php) | `Broadcast::connection()` -[Illuminate\Contracts\Broadcasting\ShouldBroadcast](https://github.com/illuminate/contracts/blob/{{version}}/Broadcasting/ShouldBroadcast.php) |   -[Illuminate\Contracts\Broadcasting\ShouldBroadcastNow](https://github.com/illuminate/contracts/blob/{{version}}/Broadcasting/ShouldBroadcastNow.php) |   -[Illuminate\Contracts\Cache\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Cache/Factory.php) | `Cache` -[Illuminate\Contracts\Cache\Lock](https://github.com/illuminate/contracts/blob/{{version}}/Cache/Lock.php) |   -[Illuminate\Contracts\Cache\LockProvider](https://github.com/illuminate/contracts/blob/{{version}}/Cache/LockProvider.php) |   -[Illuminate\Contracts\Cache\Repository](https://github.com/illuminate/contracts/blob/{{version}}/Cache/Repository.php) | `Cache::driver()` -[Illuminate\Contracts\Cache\Store](https://github.com/illuminate/contracts/blob/{{version}}/Cache/Store.php) |   -[Illuminate\Contracts\Config\Repository](https://github.com/illuminate/contracts/blob/{{version}}/Config/Repository.php) | `Config` -[Illuminate\Contracts\Console\Application](https://github.com/illuminate/contracts/blob/{{version}}/Console/Application.php) |   -[Illuminate\Contracts\Console\Kernel](https://github.com/illuminate/contracts/blob/{{version}}/Console/Kernel.php) | `Artisan` -[Illuminate\Contracts\Container\Container](https://github.com/illuminate/contracts/blob/{{version}}/Container/Container.php) | `App` -[Illuminate\Contracts\Cookie\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Cookie/Factory.php) | `Cookie` -[Illuminate\Contracts\Cookie\QueueingFactory](https://github.com/illuminate/contracts/blob/{{version}}/Cookie/QueueingFactory.php) | `Cookie::queue()` -[Illuminate\Contracts\Database\ModelIdentifier](https://github.com/illuminate/contracts/blob/{{version}}/Database/ModelIdentifier.php) |   -[Illuminate\Contracts\Debug\ExceptionHandler](https://github.com/illuminate/contracts/blob/{{version}}/Debug/ExceptionHandler.php) |   -[Illuminate\Contracts\Encryption\Encrypter](https://github.com/illuminate/contracts/blob/{{version}}/Encryption/Encrypter.php) | `Crypt` -[Illuminate\Contracts\Events\Dispatcher](https://github.com/illuminate/contracts/blob/{{version}}/Events/Dispatcher.php) | `Event` -[Illuminate\Contracts\Filesystem\Cloud](https://github.com/illuminate/contracts/blob/{{version}}/Filesystem/Cloud.php) | `Storage::cloud()` -[Illuminate\Contracts\Filesystem\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Filesystem/Factory.php) | `Storage` -[Illuminate\Contracts\Filesystem\Filesystem](https://github.com/illuminate/contracts/blob/{{version}}/Filesystem/Filesystem.php) | `Storage::disk()` -[Illuminate\Contracts\Foundation\Application](https://github.com/illuminate/contracts/blob/{{version}}/Foundation/Application.php) | `App` -[Illuminate\Contracts\Hashing\Hasher](https://github.com/illuminate/contracts/blob/{{version}}/Hashing/Hasher.php) | `Hash` -[Illuminate\Contracts\Http\Kernel](https://github.com/illuminate/contracts/blob/{{version}}/Http/Kernel.php) |   -[Illuminate\Contracts\Mail\MailQueue](https://github.com/illuminate/contracts/blob/{{version}}/Mail/MailQueue.php) | `Mail::queue()` -[Illuminate\Contracts\Mail\Mailable](https://github.com/illuminate/contracts/blob/{{version}}/Mail/Mailable.php) |   -[Illuminate\Contracts\Mail\Mailer](https://github.com/illuminate/contracts/blob/{{version}}/Mail/Mailer.php) | `Mail` -[Illuminate\Contracts\Notifications\Dispatcher](https://github.com/illuminate/contracts/blob/{{version}}/Notifications/Dispatcher.php) | `Notification` -[Illuminate\Contracts\Notifications\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Notifications/Factory.php) | `Notification` -[Illuminate\Contracts\Pagination\LengthAwarePaginator](https://github.com/illuminate/contracts/blob/{{version}}/Pagination/LengthAwarePaginator.php) |   -[Illuminate\Contracts\Pagination\Paginator](https://github.com/illuminate/contracts/blob/{{version}}/Pagination/Paginator.php) |   -[Illuminate\Contracts\Pipeline\Hub](https://github.com/illuminate/contracts/blob/{{version}}/Pipeline/Hub.php) |   -[Illuminate\Contracts\Pipeline\Pipeline](https://github.com/illuminate/contracts/blob/{{version}}/Pipeline/Pipeline.php) |   -[Illuminate\Contracts\Queue\EntityResolver](https://github.com/illuminate/contracts/blob/{{version}}/Queue/EntityResolver.php) |   -[Illuminate\Contracts\Queue\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Queue/Factory.php) | `Queue` -[Illuminate\Contracts\Queue\Job](https://github.com/illuminate/contracts/blob/{{version}}/Queue/Job.php) |   -[Illuminate\Contracts\Queue\Monitor](https://github.com/illuminate/contracts/blob/{{version}}/Queue/Monitor.php) | `Queue` -[Illuminate\Contracts\Queue\Queue](https://github.com/illuminate/contracts/blob/{{version}}/Queue/Queue.php) | `Queue::connection()` -[Illuminate\Contracts\Queue\QueueableCollection](https://github.com/illuminate/contracts/blob/{{version}}/Queue/QueueableCollection.php) |   -[Illuminate\Contracts\Queue\QueueableEntity](https://github.com/illuminate/contracts/blob/{{version}}/Queue/QueueableEntity.php) |   -[Illuminate\Contracts\Queue\ShouldQueue](https://github.com/illuminate/contracts/blob/{{version}}/Queue/ShouldQueue.php) |   -[Illuminate\Contracts\Redis\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Redis/Factory.php) | `Redis` -[Illuminate\Contracts\Routing\BindingRegistrar](https://github.com/illuminate/contracts/blob/{{version}}/Routing/BindingRegistrar.php) | `Route` -[Illuminate\Contracts\Routing\Registrar](https://github.com/illuminate/contracts/blob/{{version}}/Routing/Registrar.php) | `Route` -[Illuminate\Contracts\Routing\ResponseFactory](https://github.com/illuminate/contracts/blob/{{version}}/Routing/ResponseFactory.php) | `Response` -[Illuminate\Contracts\Routing\UrlGenerator](https://github.com/illuminate/contracts/blob/{{version}}/Routing/UrlGenerator.php) | `URL` -[Illuminate\Contracts\Routing\UrlRoutable](https://github.com/illuminate/contracts/blob/{{version}}/Routing/UrlRoutable.php) |   -[Illuminate\Contracts\Session\Session](https://github.com/illuminate/contracts/blob/{{version}}/Session/Session.php) | `Session::driver()` -[Illuminate\Contracts\Support\Arrayable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Arrayable.php) |   -[Illuminate\Contracts\Support\Htmlable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Htmlable.php) |   -[Illuminate\Contracts\Support\Jsonable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Jsonable.php) |   -[Illuminate\Contracts\Support\MessageBag](https://github.com/illuminate/contracts/blob/{{version}}/Support/MessageBag.php) |   -[Illuminate\Contracts\Support\MessageProvider](https://github.com/illuminate/contracts/blob/{{version}}/Support/MessageProvider.php) |   -[Illuminate\Contracts\Support\Renderable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Renderable.php) |   -[Illuminate\Contracts\Support\Responsable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Responsable.php) |   -[Illuminate\Contracts\Translation\Loader](https://github.com/illuminate/contracts/blob/{{version}}/Translation/Loader.php) |   -[Illuminate\Contracts\Translation\Translator](https://github.com/illuminate/contracts/blob/{{version}}/Translation/Translator.php) | `Lang` -[Illuminate\Contracts\Validation\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Validation/Factory.php) | `Validator` -[Illuminate\Contracts\Validation\ImplicitRule](https://github.com/illuminate/contracts/blob/{{version}}/Validation/ImplicitRule.php) |   -[Illuminate\Contracts\Validation\Rule](https://github.com/illuminate/contracts/blob/{{version}}/Validation/Rule.php) |   -[Illuminate\Contracts\Validation\ValidatesWhenResolved](https://github.com/illuminate/contracts/blob/{{version}}/Validation/ValidatesWhenResolved.php) |   -[Illuminate\Contracts\Validation\Validator](https://github.com/illuminate/contracts/blob/{{version}}/Validation/Validator.php) | `Validator::make()` -[Illuminate\Contracts\View\Engine](https://github.com/illuminate/contracts/blob/{{version}}/View/Engine.php) |   -[Illuminate\Contracts\View\Factory](https://github.com/illuminate/contracts/blob/{{version}}/View/Factory.php) | `View` -[Illuminate\Contracts\View\View](https://github.com/illuminate/contracts/blob/{{version}}/View/View.php) | `View::make()` +
+ +| Contract | References Facade | +| --- | --- | +| [Illuminate\Contracts\Auth\Access\Authorizable](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Access/Authorizable.php) |   | +| [Illuminate\Contracts\Auth\Access\Gate](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Access/Gate.php) | `Gate` | +| [Illuminate\Contracts\Auth\Authenticatable](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Authenticatable.php) |   | +| [Illuminate\Contracts\Auth\CanResetPassword](https://github.com/illuminate/contracts/blob/{{version}}/Auth/CanResetPassword.php) |   | +| [Illuminate\Contracts\Auth\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Factory.php) | `Auth` | +| [Illuminate\Contracts\Auth\Guard](https://github.com/illuminate/contracts/blob/{{version}}/Auth/Guard.php) | `Auth::guard()` | +| [Illuminate\Contracts\Auth\PasswordBroker](https://github.com/illuminate/contracts/blob/{{version}}/Auth/PasswordBroker.php) | `Password::broker()` | +| [Illuminate\Contracts\Auth\PasswordBrokerFactory](https://github.com/illuminate/contracts/blob/{{version}}/Auth/PasswordBrokerFactory.php) | `Password` | +| [Illuminate\Contracts\Auth\StatefulGuard](https://github.com/illuminate/contracts/blob/{{version}}/Auth/StatefulGuard.php) |   | +| [Illuminate\Contracts\Auth\SupportsBasicAuth](https://github.com/illuminate/contracts/blob/{{version}}/Auth/SupportsBasicAuth.php) |   | +| [Illuminate\Contracts\Auth\UserProvider](https://github.com/illuminate/contracts/blob/{{version}}/Auth/UserProvider.php) |   | +| [Illuminate\Contracts\Broadcasting\Broadcaster](https://github.com/illuminate/contracts/blob/{{version}}/Broadcasting/Broadcaster.php) | `Broadcast::connection()` | +| [Illuminate\Contracts\Broadcasting\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Broadcasting/Factory.php) | `Broadcast` | +| [Illuminate\Contracts\Broadcasting\ShouldBroadcast](https://github.com/illuminate/contracts/blob/{{version}}/Broadcasting/ShouldBroadcast.php) |   | +| [Illuminate\Contracts\Broadcasting\ShouldBroadcastNow](https://github.com/illuminate/contracts/blob/{{version}}/Broadcasting/ShouldBroadcastNow.php) |   | +| [Illuminate\Contracts\Bus\Dispatcher](https://github.com/illuminate/contracts/blob/{{version}}/Bus/Dispatcher.php) | `Bus` | +| [Illuminate\Contracts\Bus\QueueingDispatcher](https://github.com/illuminate/contracts/blob/{{version}}/Bus/QueueingDispatcher.php) | `Bus::dispatchToQueue()` | +| [Illuminate\Contracts\Cache\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Cache/Factory.php) | `Cache` | +| [Illuminate\Contracts\Cache\Lock](https://github.com/illuminate/contracts/blob/{{version}}/Cache/Lock.php) |   | +| [Illuminate\Contracts\Cache\LockProvider](https://github.com/illuminate/contracts/blob/{{version}}/Cache/LockProvider.php) |   | +| [Illuminate\Contracts\Cache\Repository](https://github.com/illuminate/contracts/blob/{{version}}/Cache/Repository.php) | `Cache::driver()` | +| [Illuminate\Contracts\Cache\Store](https://github.com/illuminate/contracts/blob/{{version}}/Cache/Store.php) |   | +| [Illuminate\Contracts\Config\Repository](https://github.com/illuminate/contracts/blob/{{version}}/Config/Repository.php) | `Config` | +| [Illuminate\Contracts\Console\Application](https://github.com/illuminate/contracts/blob/{{version}}/Console/Application.php) |   | +| [Illuminate\Contracts\Console\Kernel](https://github.com/illuminate/contracts/blob/{{version}}/Console/Kernel.php) | `Artisan` | +| [Illuminate\Contracts\Container\Container](https://github.com/illuminate/contracts/blob/{{version}}/Container/Container.php) | `App` | +| [Illuminate\Contracts\Cookie\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Cookie/Factory.php) | `Cookie` | +| [Illuminate\Contracts\Cookie\QueueingFactory](https://github.com/illuminate/contracts/blob/{{version}}/Cookie/QueueingFactory.php) | `Cookie::queue()` | +| [Illuminate\Contracts\Database\ModelIdentifier](https://github.com/illuminate/contracts/blob/{{version}}/Database/ModelIdentifier.php) |   | +| [Illuminate\Contracts\Debug\ExceptionHandler](https://github.com/illuminate/contracts/blob/{{version}}/Debug/ExceptionHandler.php) |   | +| [Illuminate\Contracts\Encryption\Encrypter](https://github.com/illuminate/contracts/blob/{{version}}/Encryption/Encrypter.php) | `Crypt` | +| [Illuminate\Contracts\Events\Dispatcher](https://github.com/illuminate/contracts/blob/{{version}}/Events/Dispatcher.php) | `Event` | +| [Illuminate\Contracts\Filesystem\Cloud](https://github.com/illuminate/contracts/blob/{{version}}/Filesystem/Cloud.php) | `Storage::cloud()` | +| [Illuminate\Contracts\Filesystem\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Filesystem/Factory.php) | `Storage` | +| [Illuminate\Contracts\Filesystem\Filesystem](https://github.com/illuminate/contracts/blob/{{version}}/Filesystem/Filesystem.php) | `Storage::disk()` | +| [Illuminate\Contracts\Foundation\Application](https://github.com/illuminate/contracts/blob/{{version}}/Foundation/Application.php) | `App` | +| [Illuminate\Contracts\Hashing\Hasher](https://github.com/illuminate/contracts/blob/{{version}}/Hashing/Hasher.php) | `Hash` | +| [Illuminate\Contracts\Http\Kernel](https://github.com/illuminate/contracts/blob/{{version}}/Http/Kernel.php) |   | +| [Illuminate\Contracts\Mail\Mailable](https://github.com/illuminate/contracts/blob/{{version}}/Mail/Mailable.php) |   | +| [Illuminate\Contracts\Mail\Mailer](https://github.com/illuminate/contracts/blob/{{version}}/Mail/Mailer.php) | `Mail` | +| [Illuminate\Contracts\Mail\MailQueue](https://github.com/illuminate/contracts/blob/{{version}}/Mail/MailQueue.php) | `Mail::queue()` | +| [Illuminate\Contracts\Notifications\Dispatcher](https://github.com/illuminate/contracts/blob/{{version}}/Notifications/Dispatcher.php) | `Notification`| +| [Illuminate\Contracts\Notifications\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Notifications/Factory.php) | `Notification` | +| [Illuminate\Contracts\Pagination\LengthAwarePaginator](https://github.com/illuminate/contracts/blob/{{version}}/Pagination/LengthAwarePaginator.php) |   | +| [Illuminate\Contracts\Pagination\Paginator](https://github.com/illuminate/contracts/blob/{{version}}/Pagination/Paginator.php) |   | +| [Illuminate\Contracts\Pipeline\Hub](https://github.com/illuminate/contracts/blob/{{version}}/Pipeline/Hub.php) |   | +| [Illuminate\Contracts\Pipeline\Pipeline](https://github.com/illuminate/contracts/blob/{{version}}/Pipeline/Pipeline.php) | `Pipeline` | +| [Illuminate\Contracts\Queue\EntityResolver](https://github.com/illuminate/contracts/blob/{{version}}/Queue/EntityResolver.php) |   | +| [Illuminate\Contracts\Queue\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Queue/Factory.php) | `Queue` | +| [Illuminate\Contracts\Queue\Job](https://github.com/illuminate/contracts/blob/{{version}}/Queue/Job.php) |   | +| [Illuminate\Contracts\Queue\Monitor](https://github.com/illuminate/contracts/blob/{{version}}/Queue/Monitor.php) | `Queue` | +| [Illuminate\Contracts\Queue\Queue](https://github.com/illuminate/contracts/blob/{{version}}/Queue/Queue.php) | `Queue::connection()` | +| [Illuminate\Contracts\Queue\QueueableCollection](https://github.com/illuminate/contracts/blob/{{version}}/Queue/QueueableCollection.php) |   | +| [Illuminate\Contracts\Queue\QueueableEntity](https://github.com/illuminate/contracts/blob/{{version}}/Queue/QueueableEntity.php) |   | +| [Illuminate\Contracts\Queue\ShouldQueue](https://github.com/illuminate/contracts/blob/{{version}}/Queue/ShouldQueue.php) |   | +| [Illuminate\Contracts\Redis\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Redis/Factory.php) | `Redis` | +| [Illuminate\Contracts\Routing\BindingRegistrar](https://github.com/illuminate/contracts/blob/{{version}}/Routing/BindingRegistrar.php) | `Route` | +| [Illuminate\Contracts\Routing\Registrar](https://github.com/illuminate/contracts/blob/{{version}}/Routing/Registrar.php) | `Route` | +| [Illuminate\Contracts\Routing\ResponseFactory](https://github.com/illuminate/contracts/blob/{{version}}/Routing/ResponseFactory.php) | `Response` | +| [Illuminate\Contracts\Routing\UrlGenerator](https://github.com/illuminate/contracts/blob/{{version}}/Routing/UrlGenerator.php) | `URL` | +| [Illuminate\Contracts\Routing\UrlRoutable](https://github.com/illuminate/contracts/blob/{{version}}/Routing/UrlRoutable.php) |   | +| [Illuminate\Contracts\Session\Session](https://github.com/illuminate/contracts/blob/{{version}}/Session/Session.php) | `Session::driver()` | +| [Illuminate\Contracts\Support\Arrayable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Arrayable.php) |   | +| [Illuminate\Contracts\Support\Htmlable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Htmlable.php) |   | +| [Illuminate\Contracts\Support\Jsonable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Jsonable.php) |   | +| [Illuminate\Contracts\Support\MessageBag](https://github.com/illuminate/contracts/blob/{{version}}/Support/MessageBag.php) |   | +| [Illuminate\Contracts\Support\MessageProvider](https://github.com/illuminate/contracts/blob/{{version}}/Support/MessageProvider.php) |   | +| [Illuminate\Contracts\Support\Renderable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Renderable.php) |   | +| [Illuminate\Contracts\Support\Responsable](https://github.com/illuminate/contracts/blob/{{version}}/Support/Responsable.php) |   | +| [Illuminate\Contracts\Translation\Loader](https://github.com/illuminate/contracts/blob/{{version}}/Translation/Loader.php) |   | +| [Illuminate\Contracts\Translation\Translator](https://github.com/illuminate/contracts/blob/{{version}}/Translation/Translator.php) | `Lang` | +| [Illuminate\Contracts\Validation\Factory](https://github.com/illuminate/contracts/blob/{{version}}/Validation/Factory.php) | `Validator` | +| [Illuminate\Contracts\Validation\ValidatesWhenResolved](https://github.com/illuminate/contracts/blob/{{version}}/Validation/ValidatesWhenResolved.php) |   | +| [Illuminate\Contracts\Validation\ValidationRule](https://github.com/illuminate/contracts/blob/{{version}}/Validation/ValidationRule.php) |   | +| [Illuminate\Contracts\Validation\Validator](https://github.com/illuminate/contracts/blob/{{version}}/Validation/Validator.php) | `Validator::make()` | +| [Illuminate\Contracts\View\Engine](https://github.com/illuminate/contracts/blob/{{version}}/View/Engine.php) |   | +| [Illuminate\Contracts\View\Factory](https://github.com/illuminate/contracts/blob/{{version}}/View/Factory.php) | `View` | +| [Illuminate\Contracts\View\View](https://github.com/illuminate/contracts/blob/{{version}}/View/View.php) | `View::make()` | + +
diff --git a/contributions.md b/contributions.md index 2e6720e1342..3f76bc0bf21 100644 --- a/contributions.md +++ b/contributions.md @@ -14,12 +14,14 @@ ## Bug Reports -To encourage active collaboration, Laravel strongly encourages pull requests, not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a failing test. Pull requests will only be reviewed when marked as "ready for review" (not in the "draft" state) and all tests for new features are passing. Lingering, non-active pull requests left in the "draft" state will be closed after a few days. +To encourage active collaboration, Laravel strongly encourages pull requests, not just bug reports. Pull requests will only be reviewed when marked as "ready for review" (not in the "draft" state) and all tests for new features are passing. Lingering, non-active pull requests left in the "draft" state will be closed after a few days. However, if you file a bug report, your issue should contain a title and a clear description of the issue. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a bug report is to make it easy for yourself - and others - to replicate the bug and develop a fix. Remember, bug reports are created in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the bug report will automatically see any activity or that others will jump to fix it. Creating a bug report serves to help yourself and others start on the path of fixing the problem. If you want to chip in, you can help out by fixing [any bugs listed in our issue trackers](https://github.com/issues?q=is%3Aopen+is%3Aissue+label%3Abug+user%3Alaravel). You must be authenticated with GitHub to view all of Laravel's issues. +If you notice improper DocBlock, PHPStan, or IDE warnings while using Laravel, do not create a GitHub issue. Instead, please submit a pull request to fix the problem. + The Laravel source code is managed on GitHub, and there are repositories for each of the Laravel projects:
@@ -32,18 +34,23 @@ The Laravel source code is managed on GitHub, and there are repositories for eac - [Laravel Cashier Paddle](https://github.com/laravel/cashier-paddle) - [Laravel Echo](https://github.com/laravel/echo) - [Laravel Envoy](https://github.com/laravel/envoy) +- [Laravel Folio](https://github.com/laravel/folio) - [Laravel Framework](https://github.com/laravel/framework) -- [Laravel Homestead](https://github.com/laravel/homestead) -- [Laravel Homestead Build Scripts](https://github.com/laravel/settler) +- [Laravel Homestead](https://github.com/laravel/homestead) ([Build Scripts](https://github.com/laravel/settler)) - [Laravel Horizon](https://github.com/laravel/horizon) -- [Laravel Jetstream](https://github.com/laravel/jetstream) - [Laravel Passport](https://github.com/laravel/passport) +- [Laravel Pennant](https://github.com/laravel/pennant) +- [Laravel Pint](https://github.com/laravel/pint) +- [Laravel Prompts](https://github.com/laravel/prompts) +- [Laravel Reverb](https://github.com/laravel/reverb) - [Laravel Sail](https://github.com/laravel/sail) - [Laravel Sanctum](https://github.com/laravel/sanctum) - [Laravel Scout](https://github.com/laravel/scout) - [Laravel Socialite](https://github.com/laravel/socialite) - [Laravel Telescope](https://github.com/laravel/telescope) -- [Laravel Website](https://github.com/laravel/laravel.com-next) +- [Laravel Livewire Starter Kit](https://github.com/laravel/livewire-starter-kit) +- [Laravel React Starter Kit](https://github.com/laravel/react-starter-kit) +- [Laravel Vue Starter Kit](https://github.com/laravel/vue-starter-kit)
@@ -74,13 +81,11 @@ Informal discussion regarding bugs, new features, and implementation of existing ## Which Branch? -**All** bug fixes should be sent to the latest stable branch. Bug fixes should **never** be sent to the `master` branch unless they fix features that exist only in the upcoming release. - -**Minor** features that are **fully backward compatible** with the current release may be sent to the latest stable branch. +**All** bug fixes should be sent to the latest version that supports bug fixes (currently `12.x`). Bug fixes should **never** be sent to the `master` branch unless they fix features that exist only in the upcoming release. -**Major** new features should always be sent to the `master` branch, which contains the upcoming release. +**Minor** features that are **fully backward compatible** with the current release may be sent to the latest stable branch (currently `12.x`). -If you are unsure if your feature qualifies as a major or minor, please ask Taylor Otwell in the `#internals` channel of the [Laravel Discord server](https://discord.gg/laravel). +**Major** new features or features with breaking changes should always be sent to the `master` branch, which contains the upcoming release. ## Compiled Assets @@ -102,20 +107,50 @@ Laravel follows the [PSR-2](https://github.com/php-fig/fig-standards/blob/master Below is an example of a valid Laravel documentation block. Note that the `@param` attribute is followed by two spaces, the argument type, two more spaces, and finally the variable name: - /** - * Register a binding with the container. - * - * @param string|array $abstract - * @param \Closure|string|null $concrete - * @param bool $shared - * @return void - * - * @throws \Exception - */ - public function bind($abstract, $concrete = null, $shared = false) - { - // - } +```php +/** + * Register a binding with the container. + * + * @param string|array $abstract + * @param \Closure|string|null $concrete + * @param bool $shared + * @return void + * + * @throws \Exception + */ +public function bind($abstract, $concrete = null, $shared = false) +{ + // ... +} +``` + +When the `@param` or `@return` attributes are redundant due to the use of native types, they can be removed: + +```php +/** + * Execute the job. + */ +public function handle(AudioProcessor $processor): void +{ + // +} +``` + +However, when the native type is generic, please specify the generic type through the use of the `@param` or `@return` attributes: + +```php +/** + * Get the attachments for the message. + * + * @return array + */ +public function attachments(): array +{ + return [ + Attachment::fromStorage('/path/to/file'), + ]; +} +``` ### StyleCI diff --git a/controllers.md b/controllers.md index 15425185d9a..58fa9edf15e 100644 --- a/controllers.md +++ b/controllers.md @@ -13,7 +13,9 @@ - [Scoping Resource Routes](#restful-scoping-resource-routes) - [Localizing Resource URIs](#restful-localizing-resource-uris) - [Supplementing Resource Controllers](#restful-supplementing-resource-controllers) -- [Dependency Injection & Controllers](#dependency-injection-and-controllers) + - [Singleton Resource Controllers](#singleton-resource-controllers) + - [Middleware and Resource Controllers](#middleware-and-resource-controllers) +- [Dependency Injection and Controllers](#dependency-injection-and-controllers) ## Introduction @@ -26,71 +28,78 @@ Instead of defining all of your request handling logic as closures in your route ### Basic Controllers -Let's take a look at an example of a basic controller. Note that the controller extends the base controller class included with Laravel: `App\Http\Controllers\Controller`: +To quickly generate a new controller, you may run the `make:controller` Artisan command. By default, all of the controllers for your application are stored in the `app/Http/Controllers` directory: - User::findOrFail($id) - ]); - } + return view('user.profile', [ + 'user' => User::findOrFail($id) + ]); } +} +``` -You can define a route to this controller method like so: +Once you have written a controller class and method, you may define a route to the controller method like so: - use App\Http\Controllers\UserController; +```php +use App\Http\Controllers\UserController; - Route::get('/user/{id}', [UserController::class, 'show']); +Route::get('/user/{id}', [UserController::class, 'show']); +``` When an incoming request matches the specified route URI, the `show` method on the `App\Http\Controllers\UserController` class will be invoked and the route parameters will be passed to the method. -> {tip} Controllers are not **required** to extend a base class. However, you will not have access to convenient features such as the `middleware` and `authorize` methods. +> [!NOTE] +> Controllers are not **required** to extend a base class. However, it is sometimes convenient to extend a base controller class that contains methods that should be shared across all of your controllers. ### Single Action Controllers If a controller action is particularly complex, you might find it convenient to dedicate an entire controller class to that single action. To accomplish this, you may define a single `__invoke` method within the controller: - {tip} Controller stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization). +> [!NOTE] +> Controller stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization). ## Controller Middleware [Middleware](/docs/{{version}}/middleware) may be assigned to the controller's routes in your route files: - Route::get('profile', [UserController::class, 'show'])->middleware('auth'); +```php +Route::get('/profile', [UserController::class, 'show'])->middleware('auth'); +``` + +Or, you may find it convenient to specify middleware within your controller class. To do so, your controller should implement the `HasMiddleware` interface, which dictates that the controller should have a static `middleware` method. From this method, you may return an array of middleware that should be applied to the controller's actions: + +```php +middleware('auth'); - $this->middleware('log')->only('index'); - $this->middleware('subscribed')->except('store'); - } + return [ + 'auth', + new Middleware('log', only: ['index']), + new Middleware('subscribed', except: ['store']), + ]; } -Controllers also allow you to register middleware using a closure. This provides a convenient way to define an inline middleware for a single controller without defining an entire middleware class: + // ... +} +``` - $this->middleware(function ($request, $next) { - return $next($request); - }); +You may also define controller middleware as closures, which provides a convenient way to define an inline middleware without writing an entire middleware class: + +```php +use Closure; +use Illuminate\Http\Request; + +/** + * Get the middleware that should be assigned to the controller. + */ +public static function middleware(): array +{ + return [ + function (Request $request, Closure $next) { + return $next($request); + }, + ]; +} +``` ## Resource Controllers @@ -143,48 +179,84 @@ php artisan make:controller PhotoController --resource This command will generate a controller at `app/Http/Controllers/PhotoController.php`. The controller will contain a method for each of the available resource operations. Next, you may register a resource route that points to the controller: - use App\Http\Controllers\PhotoController; +```php +use App\Http\Controllers\PhotoController; - Route::resource('photos', PhotoController::class); +Route::resource('photos', PhotoController::class); +``` This single route declaration creates multiple routes to handle a variety of actions on the resource. The generated controller will already have methods stubbed for each of these actions. Remember, you can always get a quick overview of your application's routes by running the `route:list` Artisan command. You may even register many resource controllers at once by passing an array to the `resources` method: - Route::resources([ - 'photos' => PhotoController::class, - 'posts' => PostController::class, - ]); +```php +Route::resources([ + 'photos' => PhotoController::class, + 'posts' => PostController::class, +]); +``` - -#### Actions Handled By Resource Controller +The `softDeletableResources` method registers many resources controllers that all use the `withTrashed` method: -Verb | URI | Action | Route Name -----------|------------------------|--------------|--------------------- -GET | `/photos` | index | photos.index -GET | `/photos/create` | create | photos.create -POST | `/photos` | store | photos.store -GET | `/photos/{photo}` | show | photos.show -GET | `/photos/{photo}/edit` | edit | photos.edit -PUT/PATCH | `/photos/{photo}` | update | photos.update -DELETE | `/photos/{photo}` | destroy | photos.destroy +```php +Route::softDeletableResources([ + 'photos' => PhotoController::class, + 'posts' => PostController::class, +]); +``` + + +#### Actions Handled by Resource Controllers + +
+ +| Verb | URI | Action | Route Name | +| --------- | ---------------------- | ------- | -------------- | +| GET | `/photos` | index | photos.index | +| GET | `/photos/create` | create | photos.create | +| POST | `/photos` | store | photos.store | +| GET | `/photos/{photo}` | show | photos.show | +| GET | `/photos/{photo}/edit` | edit | photos.edit | +| PUT/PATCH | `/photos/{photo}` | update | photos.update | +| DELETE | `/photos/{photo}` | destroy | photos.destroy | + +
#### Customizing Missing Model Behavior -Typically, a 404 HTTP response will be generated if an implicitly bound resource model is not found. However, you may customize this behavior by calling the `missing` method when defining your resource route. The `missing` method accepts a closure that will be invoked if an implicitly bound model can not be found for any of the resource's routes: +Typically, a 404 HTTP response will be generated if an implicitly bound resource model is not found. However, you may customize this behavior by calling the `missing` method when defining your resource route. The `missing` method accepts a closure that will be invoked if an implicitly bound model cannot be found for any of the resource's routes: + +```php +use App\Http\Controllers\PhotoController; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Redirect; + +Route::resource('photos', PhotoController::class) + ->missing(function (Request $request) { + return Redirect::route('photos.index'); + }); +``` + + +#### Soft Deleted Models + +Typically, implicit model binding will not retrieve models that have been [soft deleted](/docs/{{version}}/eloquent#soft-deleting), and will instead return a 404 HTTP response. However, you can instruct the framework to allow soft deleted models by invoking the `withTrashed` method when defining your resource route: - use App\Http\Controllers\PhotoController; - use Illuminate\Http\Request; - use Illuminate\Support\Facades\Redirect; +```php +use App\Http\Controllers\PhotoController; - Route::resource('photos', PhotoController::class) - ->missing(function (Request $request) { - return Redirect::route('photos.index'); - }); +Route::resource('photos', PhotoController::class)->withTrashed(); +``` + +Calling `withTrashed` with no arguments will allow soft deleted models for the `show`, `edit`, and `update` resource routes. You may specify a subset of these routes by passing an array to the `withTrashed` method: + +```php +Route::resource('photos', PhotoController::class)->withTrashed(['show']); +``` -#### Specifying The Resource Model +#### Specifying the Resource Model If you are using [route model binding](/docs/{{version}}/routing#route-model-binding) and would like the resource controller's methods to type-hint a model instance, you may use the `--model` option when generating the controller: @@ -206,34 +278,40 @@ php artisan make:controller PhotoController --model=Photo --resource --requests When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions: - use App\Http\Controllers\PhotoController; +```php +use App\Http\Controllers\PhotoController; - Route::resource('photos', PhotoController::class)->only([ - 'index', 'show' - ]); +Route::resource('photos', PhotoController::class)->only([ + 'index', 'show' +]); - Route::resource('photos', PhotoController::class)->except([ - 'create', 'store', 'update', 'destroy' - ]); +Route::resource('photos', PhotoController::class)->except([ + 'create', 'store', 'update', 'destroy' +]); +``` #### API Resource Routes When declaring resource routes that will be consumed by APIs, you will commonly want to exclude routes that present HTML templates such as `create` and `edit`. For convenience, you may use the `apiResource` method to automatically exclude these two routes: - use App\Http\Controllers\PhotoController; +```php +use App\Http\Controllers\PhotoController; - Route::apiResource('photos', PhotoController::class); +Route::apiResource('photos', PhotoController::class); +``` You may register many API resource controllers at once by passing an array to the `apiResources` method: - use App\Http\Controllers\PhotoController; - use App\Http\Controllers\PostController; +```php +use App\Http\Controllers\PhotoController; +use App\Http\Controllers\PostController; - Route::apiResources([ - 'photos' => PhotoController::class, - 'posts' => PostController::class, - ]); +Route::apiResources([ + 'photos' => PhotoController::class, + 'posts' => PostController::class, +]); +``` To quickly generate an API resource controller that does not include the `create` or `edit` methods, use the `--api` switch when executing the `make:controller` command: @@ -246,13 +324,17 @@ php artisan make:controller PhotoController --api Sometimes you may need to define routes to a nested resource. For example, a photo resource may have multiple comments that may be attached to the photo. To nest the resource controllers, you may use "dot" notation in your route declaration: - use App\Http\Controllers\PhotoCommentController; +```php +use App\Http\Controllers\PhotoCommentController; - Route::resource('photos.comments', PhotoCommentController::class); +Route::resource('photos.comments', PhotoCommentController::class); +``` This route will register a nested resource that may be accessed with URIs like the following: - /photos/{photo}/comments/{comment} +```text +/photos/{photo}/comments/{comment} +``` #### Scoping Nested Resources @@ -264,188 +346,350 @@ Laravel's [implicit model binding](/docs/{{version}}/routing#implicit-model-bind Often, it is not entirely necessary to have both the parent and the child IDs within a URI since the child ID is already a unique identifier. When using unique identifiers such as auto-incrementing primary keys to identify your models in URI segments, you may choose to use "shallow nesting": - use App\Http\Controllers\CommentController; +```php +use App\Http\Controllers\CommentController; - Route::resource('photos.comments', CommentController::class)->shallow(); +Route::resource('photos.comments', CommentController::class)->shallow(); +``` This route definition will define the following routes: -Verb | URI | Action | Route Name -----------|-----------------------------------|--------------|--------------------- -GET | `/photos/{photo}/comments` | index | photos.comments.index -GET | `/photos/{photo}/comments/create` | create | photos.comments.create -POST | `/photos/{photo}/comments` | store | photos.comments.store -GET | `/comments/{comment}` | show | comments.show -GET | `/comments/{comment}/edit` | edit | comments.edit -PUT/PATCH | `/comments/{comment}` | update | comments.update -DELETE | `/comments/{comment}` | destroy | comments.destroy +
+ +| Verb | URI | Action | Route Name | +| --------- | --------------------------------- | ------- | ---------------------- | +| GET | `/photos/{photo}/comments` | index | photos.comments.index | +| GET | `/photos/{photo}/comments/create` | create | photos.comments.create | +| POST | `/photos/{photo}/comments` | store | photos.comments.store | +| GET | `/comments/{comment}` | show | comments.show | +| GET | `/comments/{comment}/edit` | edit | comments.edit | +| PUT/PATCH | `/comments/{comment}` | update | comments.update | +| DELETE | `/comments/{comment}` | destroy | comments.destroy | + +
### Naming Resource Routes By default, all resource controller actions have a route name; however, you can override these names by passing a `names` array with your desired route names: - use App\Http\Controllers\PhotoController; +```php +use App\Http\Controllers\PhotoController; - Route::resource('photos', PhotoController::class)->names([ - 'create' => 'photos.build' - ]); +Route::resource('photos', PhotoController::class)->names([ + 'create' => 'photos.build' +]); +``` ### Naming Resource Route Parameters By default, `Route::resource` will create the route parameters for your resource routes based on the "singularized" version of the resource name. You can easily override this on a per resource basis using the `parameters` method. The array passed into the `parameters` method should be an associative array of resource names and parameter names: - use App\Http\Controllers\AdminUserController; +```php +use App\Http\Controllers\AdminUserController; - Route::resource('users', AdminUserController::class)->parameters([ - 'users' => 'admin_user' - ]); +Route::resource('users', AdminUserController::class)->parameters([ + 'users' => 'admin_user' +]); +``` - The example above generates the following URI for the resource's `show` route: +The example above generates the following URI for the resource's `show` route: - /users/{admin_user} +```text +/users/{admin_user} +``` ### Scoping Resource Routes Laravel's [scoped implicit model binding](/docs/{{version}}/routing#implicit-model-binding-scoping) feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the `scoped` method when defining your nested resource, you may enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by: - use App\Http\Controllers\PhotoCommentController; +```php +use App\Http\Controllers\PhotoCommentController; - Route::resource('photos.comments', PhotoCommentController::class)->scoped([ - 'comment' => 'slug', - ]); +Route::resource('photos.comments', PhotoCommentController::class)->scoped([ + 'comment' => 'slug', +]); +``` This route will register a scoped nested resource that may be accessed with URIs like the following: - /photos/{photo}/comments/{comment:slug} +```text +/photos/{photo}/comments/{comment:slug} +``` When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the `Photo` model has a relationship named `comments` (the plural of the route parameter name) which can be used to retrieve the `Comment` model. ### Localizing Resource URIs -By default, `Route::resource` will create resource URIs using English verbs. If you need to localize the `create` and `edit` action verbs, you may use the `Route::resourceVerbs` method. This may be done at the beginning of the `boot` method within your application's `App\Providers\RouteServiceProvider`: - - /** - * Define your route model bindings, pattern filters, etc. - * - * @return void - */ - public function boot() - { - Route::resourceVerbs([ - 'create' => 'crear', - 'edit' => 'editar', - ]); - - // ... - } +By default, `Route::resource` will create resource URIs using English verbs and plural rules. If you need to localize the `create` and `edit` action verbs, you may use the `Route::resourceVerbs` method. This may be done at the beginning of the `boot` method within your application's `App\Providers\AppServiceProvider`: + +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Route::resourceVerbs([ + 'create' => 'crear', + 'edit' => 'editar', + ]); +} +``` -Once the verbs have been customized, a resource route registration such as `Route::resource('fotos', PhotoController::class)` will produce the following URIs: +Laravel's pluralizer supports [several different languages which you may configure based on your needs](/docs/{{version}}/localization#pluralization-language). Once the verbs and pluralization language have been customized, a resource route registration such as `Route::resource('publicacion', PublicacionController::class)` will produce the following URIs: - /fotos/crear +```text +/publicacion/crear - /fotos/{foto}/editar +/publicacion/{publicaciones}/editar +``` ### Supplementing Resource Controllers If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to the `Route::resource` method; otherwise, the routes defined by the `resource` method may unintentionally take precedence over your supplemental routes: - use App\Http\Controller\PhotoController; +```php +use App\Http\Controller\PhotoController; - Route::get('/photos/popular', [PhotoController::class, 'popular']); - Route::resource('photos', PhotoController::class); +Route::get('/photos/popular', [PhotoController::class, 'popular']); +Route::resource('photos', PhotoController::class); +``` + +> [!NOTE] +> Remember to keep your controllers focused. If you find yourself routinely needing methods outside of the typical set of resource actions, consider splitting your controller into two, smaller controllers. + + +### Singleton Resource Controllers + +Sometimes, your application will have resources that may only have a single instance. For example, a user's "profile" can be edited or updated, but a user may not have more than one "profile". Likewise, an image may have a single "thumbnail". These resources are called "singleton resources", meaning one and only one instance of the resource may exist. In these scenarios, you may register a "singleton" resource controller: + +```php +use App\Http\Controllers\ProfileController; +use Illuminate\Support\Facades\Route; + +Route::singleton('profile', ProfileController::class); +``` + +The singleton resource definition above will register the following routes. As you can see, "creation" routes are not registered for singleton resources, and the registered routes do not accept an identifier since only one instance of the resource may exist: + +
+ +| Verb | URI | Action | Route Name | +| --------- | --------------- | ------ | -------------- | +| GET | `/profile` | show | profile.show | +| GET | `/profile/edit` | edit | profile.edit | +| PUT/PATCH | `/profile` | update | profile.update | + +
+ +Singleton resources may also be nested within a standard resource: + +```php +Route::singleton('photos.thumbnail', ThumbnailController::class); +``` + +In this example, the `photos` resource would receive all of the [standard resource routes](#actions-handled-by-resource-controllers); however, the `thumbnail` resource would be a singleton resource with the following routes: + +
+ +| Verb | URI | Action | Route Name | +| --------- | -------------------------------- | ------ | ----------------------- | +| GET | `/photos/{photo}/thumbnail` | show | photos.thumbnail.show | +| GET | `/photos/{photo}/thumbnail/edit` | edit | photos.thumbnail.edit | +| PUT/PATCH | `/photos/{photo}/thumbnail` | update | photos.thumbnail.update | + +
+ + +#### Creatable Singleton Resources + +Occasionally, you may want to define creation and storage routes for a singleton resource. To accomplish this, you may invoke the `creatable` method when registering the singleton resource route: + +```php +Route::singleton('photos.thumbnail', ThumbnailController::class)->creatable(); +``` + +In this example, the following routes will be registered. As you can see, a `DELETE` route will also be registered for creatable singleton resources: + +
+ +| Verb | URI | Action | Route Name | +| --------- | ---------------------------------- | ------- | ------------------------ | +| GET | `/photos/{photo}/thumbnail/create` | create | photos.thumbnail.create | +| POST | `/photos/{photo}/thumbnail` | store | photos.thumbnail.store | +| GET | `/photos/{photo}/thumbnail` | show | photos.thumbnail.show | +| GET | `/photos/{photo}/thumbnail/edit` | edit | photos.thumbnail.edit | +| PUT/PATCH | `/photos/{photo}/thumbnail` | update | photos.thumbnail.update | +| DELETE | `/photos/{photo}/thumbnail` | destroy | photos.thumbnail.destroy | + +
+ +If you would like Laravel to register the `DELETE` route for a singleton resource but not register the creation or storage routes, you may utilize the `destroyable` method: + +```php +Route::singleton(...)->destroyable(); +``` + + +#### API Singleton Resources + +The `apiSingleton` method may be used to register a singleton resource that will be manipulated via an API, thus rendering the `create` and `edit` routes unnecessary: + +```php +Route::apiSingleton('profile', ProfileController::class); +``` + +Of course, API singleton resources may also be `creatable`, which will register `store` and `destroy` routes for the resource: + +```php +Route::apiSingleton('photos.thumbnail', ProfileController::class)->creatable(); +``` + +### Middleware and Resource Controllers -> {tip} Remember to keep your controllers focused. If you find yourself routinely needing methods outside of the typical set of resource actions, consider splitting your controller into two, smaller controllers. +Laravel allows you to assign middleware to all, or only specific, methods of resource routes using the `middleware`, `middlewareFor`, and `withoutMiddlewareFor` methods. These methods provide fine-grained control over which middleware is applied to each resource action. + +#### Applying Middleware to all Methods + +You may use the `middleware` method to assign middleware to all routes generated by a resource or singleton resource route: + +```php +Route::resource('users', UserController::class) + ->middleware(['auth', 'verified']); + +Route::singleton('profile', ProfileController::class) + ->middleware('auth'); +``` + +#### Applying Middleware to Specific Methods + +You may use the `middlewareFor` method to assign middleware to one or more specific methods of a given resource controller: + +```php +Route::resource('users', UserController::class) + ->middlewareFor('show', 'auth'); + +Route::apiResource('users', UserController::class) + ->middlewareFor(['show', 'update'], 'auth'); + +Route::resource('users', UserController::class) + ->middlewareFor('show', 'auth') + ->middlewareFor('update', 'auth'); + +Route::apiResource('users', UserController::class) + ->middlewareFor(['show', 'update'], ['auth', 'verified']); +``` + +The `middlewareFor` method may also be used in conjunction with singleton and API singleton resource controllers: + +```php +Route::singleton('profile', ProfileController::class) + ->middlewareFor('show', 'auth'); + +Route::apiSingleton('profile', ProfileController::class) + ->middlewareFor(['show', 'update'], 'auth'); +``` + +#### Excluding Middleware from Specific Methods + +You may use the `withoutMiddlewareFor` method to exclude middleware from specific methods of a resource controller: + +```php +Route::middleware(['auth', 'verified', 'subscribed'])->group(function () { + Route::resource('users', UserController::class) + ->withoutMiddlewareFor('index', ['auth', 'verified']) + ->withoutMiddlewareFor(['create', 'store'], 'verified') + ->withoutMiddlewareFor('destroy', 'subscribed'); +}); +``` -## Dependency Injection & Controllers +## Dependency Injection and Controllers #### Constructor Injection The Laravel [service container](/docs/{{version}}/container) is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The declared dependencies will automatically be resolved and injected into the controller instance: - users = $users; - } - } +class UserController extends Controller +{ + /** + * Create a new controller instance. + */ + public function __construct( + protected UserRepository $users, + ) {} +} +``` #### Method Injection In addition to constructor injection, you may also type-hint dependencies on your controller's methods. A common use-case for method injection is injecting the `Illuminate\Http\Request` instance into your controller methods: - name; - - // - } + $name = $request->name; + + // Store the user... + + return redirect('/users'); } +} +``` If your controller method is also expecting input from a route parameter, list your route arguments after your other dependencies. For example, if your route is defined like so: - use App\Http\Controllers\UserController; +```php +use App\Http\Controllers\UserController; - Route::put('/user/{id}', [UserController::class, 'update']); +Route::put('/user/{id}', [UserController::class, 'update']); +``` You may still type-hint the `Illuminate\Http\Request` and access your `id` parameter by defining your controller method as follows: - -#### An Explanation Of The Vulnerability +#### An Explanation of the Vulnerability In case you're not familiar with cross-site request forgeries, let's discuss an example of how this vulnerability can be exploited. Imagine your application has a `/user/email` route that accepts a `POST` request to change the authenticated user's email address. Most likely, this route expects an `email` input field to contain the email address the user would like to begin using. @@ -28,9 +28,9 @@ Without CSRF protection, a malicious website could create an HTML form that poin ``` - If the malicious website automatically submits the form when the page is loaded, the malicious user only needs to lure an unsuspecting user of your application to visit their website and their email address will be changed in your application. +If the malicious website automatically submits the form when the page is loaded, the malicious user only needs to lure an unsuspecting user of your application to visit their website and their email address will be changed in your application. - To prevent this vulnerability, we need to inspect every incoming `POST`, `PUT`, `PATCH`, or `DELETE` request for a secret session value that the malicious application is unable to access. +To prevent this vulnerability, we need to inspect every incoming `POST`, `PUT`, `PATCH`, or `DELETE` request for a secret session value that the malicious application is unable to access. ## Preventing CSRF Requests @@ -39,15 +39,17 @@ Laravel automatically generates a CSRF "token" for each active [user session](/d The current session's CSRF token can be accessed via the request's session or via the `csrf_token` helper function: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/token', function (Request $request) { - $token = $request->session()->token(); +Route::get('/token', function (Request $request) { + $token = $request->session()->token(); - $token = csrf_token(); + $token = csrf_token(); - // ... - }); + // ... +}); +``` Anytime you define a "POST", "PUT", "PATCH", or "DELETE" HTML form in your application, you should include a hidden CSRF `_token` field in the form so that the CSRF protection middleware can validate the request. For convenience, you may use the `@csrf` Blade directive to generate the hidden token input field: @@ -60,7 +62,7 @@ Anytime you define a "POST", "PUT", "PATCH", or "DELETE" HTML form in your appli ``` -The `App\Http\Middleware\VerifyCsrfToken` [middleware](/docs/{{version}}/middleware), which is included in the `web` middleware group by default, will automatically verify that the token in the request input matches the token stored in the session. When these two tokens match, we know that the authenticated user is the one initiating the request. +The `Illuminate\Foundation\Http\Middleware\ValidateCsrfToken` [middleware](/docs/{{version}}/middleware), which is included in the `web` middleware group by default, will automatically verify that the token in the request input matches the token stored in the session. When these two tokens match, we know that the authenticated user is the one initiating the request. ### CSRF Tokens & SPAs @@ -72,34 +74,25 @@ If you are building an SPA that is utilizing Laravel as an API backend, you shou Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using [Stripe](https://stripe.com) to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes. -Typically, you should place these kinds of routes outside of the `web` middleware group that the `App\Providers\RouteServiceProvider` applies to all routes in the `routes/web.php` file. However, you may also exclude the routes by adding their URIs to the `$except` property of the `VerifyCsrfToken` middleware: - - withMiddleware(function (Middleware $middleware): void { + $middleware->validateCsrfTokens(except: [ + 'stripe/*', + 'http://example.com/foo/bar', + 'http://example.com/foo/*', + ]); +}) +``` -> {tip} For convenience, the CSRF middleware is automatically disabled for all routes when [running tests](/docs/{{version}}/testing). +> [!NOTE] +> For convenience, the CSRF middleware is automatically disabled for all routes when [running tests](/docs/{{version}}/testing). ## X-CSRF-TOKEN -In addition to checking for the CSRF token as a POST parameter, the `App\Http\Middleware\VerifyCsrfToken` middleware will also check for the `X-CSRF-TOKEN` request header. You could, for example, store the token in an HTML `meta` tag: +In addition to checking for the CSRF token as a POST parameter, the `Illuminate\Foundation\Http\Middleware\ValidateCsrfToken` middleware, which is included in the `web` middleware group by default, will also check for the `X-CSRF-TOKEN` request header. You could, for example, store the token in an HTML `meta` tag: ```blade @@ -122,4 +115,5 @@ Laravel stores the current CSRF token in an encrypted `XSRF-TOKEN` cookie that i This cookie is primarily sent as a developer convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the `X-XSRF-TOKEN` header on same-origin requests. -> {tip} By default, the `resources/js/bootstrap.js` file includes the Axios HTTP library which will automatically send the `X-XSRF-TOKEN` header for you. +> [!NOTE] +> By default, the `resources/js/bootstrap.js` file includes the Axios HTTP library which will automatically send the `X-XSRF-TOKEN` header for you. diff --git a/database-testing.md b/database-testing.md index 1032b4180f9..8f1a7715bec 100644 --- a/database-testing.md +++ b/database-testing.md @@ -1,22 +1,8 @@ # Database Testing - [Introduction](#introduction) - - [Resetting The Database After Each Test](#resetting-the-database-after-each-test) -- [Defining Model Factories](#defining-model-factories) - - [Concept Overview](#concept-overview) - - [Generating Factories](#generating-factories) - - [Factory States](#factory-states) - - [Factory Callbacks](#factory-callbacks) -- [Creating Models Using Factories](#creating-models-using-factories) - - [Instantiating Models](#instantiating-models) - - [Persisting Models](#persisting-models) - - [Sequences](#sequences) -- [Factory Relationships](#factory-relationships) - - [Has Many Relationships](#has-many-relationships) - - [Belongs To Relationships](#belongs-to-relationships) - - [Many To Many Relationships](#many-to-many-relationships) - - [Polymorphic Relationships](#polymorphic-relationships) - - [Defining Relationships Within Factories](#defining-relationships-within-factories) + - [Resetting the Database After Each Test](#resetting-the-database-after-each-test) +- [Model Factories](#model-factories) - [Running Seeders](#running-seeders) - [Available Assertions](#available-assertions) @@ -26,642 +12,280 @@ Laravel provides a variety of helpful tools and assertions to make it easier to test your database driven applications. In addition, Laravel model factories and seeders make it painless to create test database records using your application's Eloquent models and relationships. We'll discuss all of these powerful features in the following documentation. -### Resetting The Database After Each Test +### Resetting the Database After Each Test Before proceeding much further, let's discuss how to reset your database after each of your tests so that data from a previous test does not interfere with subsequent tests. Laravel's included `Illuminate\Foundation\Testing\RefreshDatabase` trait will take care of this for you. Simply use the trait on your test class: - use(RefreshDatabase::class); - class ExampleTest extends TestCase - { - use RefreshDatabase; - - /** - * A basic functional test example. - * - * @return void - */ - public function test_basic_example() - { - $response = $this->get('/'); - - // ... - } - } - -The `Illuminate\Foundation\Testing\RefreshDatabase` trait does not migrate your database if your schema is up to date. Instead, it will only execute the test within a database transaction. Therefore, any records added to the database by test cases that do not use this trait may still exist in the database. - -If you would like to totally reset the database using migrations, you may use the `Illuminate\Foundation\Testing\DatabaseMigrations` trait instead. However, the `DatabaseMigrations` trait is significantly slower than the `RefreshDatabase` trait. - - -## Defining Model Factories - - -### Concept Overview - -First, let's talk about Eloquent model factories. When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a set of default attributes for each of your [Eloquent models](/docs/{{version}}/eloquent) using model factories. - -To see an example of how to write a factory, take a look at the `database/factories/UserFactory.php` file in your application. This factory is included with all new Laravel applications and contains the following factory definition: +test('basic example', function () { + $response = $this->get('/'); - namespace Database\Factories; - - use Illuminate\Database\Eloquent\Factories\Factory; - use Illuminate\Support\Str; - - class UserFactory extends Factory - { - /** - * Define the model's default state. - * - * @return array - */ - public function definition() - { - return [ - 'name' => $this->faker->name(), - 'email' => $this->faker->unique()->safeEmail(), - 'email_verified_at' => now(), - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password - 'remember_token' => Str::random(10), - ]; - } - } - -As you can see, in their most basic form, factories are classes that extend Laravel's base factory class and define `definition` method. The `definition` method returns the default set of attribute values that should be applied when creating a model using the factory. - -Via the `faker` property, factories have access to the [Faker](https://github.com/FakerPHP/Faker) PHP library, which allows you to conveniently generate various kinds of random data for testing. - -> {tip} You can set your application's Faker locale by adding a `faker_locale` option to your `config/app.php` configuration file. - - -### Generating Factories - -To create a factory, execute the `make:factory` [Artisan command](/docs/{{version}}/artisan): - -```shell -php artisan make:factory PostFactory + // ... +}); ``` -The new factory class will be placed in your `database/factories` directory. - - -#### Model & Factory Discovery Conventions +```php tab=PHPUnit + -### Factory States - -State manipulation methods allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your `Database\Factories\UserFactory` factory might contain a `suspended` state method that modifies one of its default attribute values. - -State transformation methods typically call the `state` method provided by Laravel's base factory class. The `state` method accepts a closure which will receive the array of raw attributes defined for the factory and should return an array of attributes to modify: - - /** - * Indicate that the user is suspended. - * - * @return \Illuminate\Database\Eloquent\Factories\Factory - */ - public function suspended() - { - return $this->state(function (array $attributes) { - return [ - 'account_status' => 'suspended', - ]; - }); - } - - -### Factory Callbacks - -Factory callbacks are registered using the `afterMaking` and `afterCreating` methods and allow you to perform additional tasks after making or creating a model. You should register these callbacks by defining a `configure` method on your factory class. This method will be automatically called by Laravel when the factory is instantiated: - - namespace Database\Factories; - - use App\Models\User; - use Illuminate\Database\Eloquent\Factories\Factory; - use Illuminate\Support\Str; - - class UserFactory extends Factory - { - /** - * Configure the model factory. - * - * @return $this - */ - public function configure() - { - return $this->afterMaking(function (User $user) { - // - })->afterCreating(function (User $user) { - // - }); - } + $response = $this->get('/'); // ... } +} +``` - -## Creating Models Using Factories - - -### Instantiating Models - -Once you have defined your factories, you may use the static `factory` method provided to your models by the `Illuminate\Database\Eloquent\Factories\HasFactory` trait in order to instantiate a factory instance for that model. Let's take a look at a few examples of creating models. First, we'll use the `make` method to create models without persisting them to the database: - - use App\Models\User; - - public function test_models_can_be_instantiated() - { - $user = User::factory()->make(); - - // Use model in tests... - } - -You may create a collection of many models using the `count` method: - - $users = User::factory()->count(3)->make(); - - -#### Applying States - -You may also apply any of your [states](#factory-states) to the models. If you would like to apply multiple state transformations to the models, you may simply call the state transformation methods directly: - - $users = User::factory()->count(5)->suspended()->make(); - - -#### Overriding Attributes - -If you would like to override some of the default values of your models, you may pass an array of values to the `make` method. Only the specified attributes will be replaced while the rest of the attributes remain set to their default values as specified by the factory: - - $user = User::factory()->make([ - 'name' => 'Abigail Otwell', - ]); - -Alternatively, the `state` method may be called directly on the factory instance to perform an inline state transformation: - - $user = User::factory()->state([ - 'name' => 'Abigail Otwell', - ])->make(); - -> {tip} [Mass assignment protection](/docs/{{version}}/eloquent#mass-assignment) is automatically disabled when creating models using factories. - - -### Persisting Models - -The `create` method instantiates model instances and persists them to the database using Eloquent's `save` method: - - use App\Models\User; - - public function test_models_can_be_persisted() - { - // Create a single App\Models\User instance... - $user = User::factory()->create(); - - // Create three App\Models\User instances... - $users = User::factory()->count(3)->create(); - - // Use model in tests... - } - -You may override the factory's default model attributes by passing an array of attributes to the `create` method: - - $user = User::factory()->create([ - 'name' => 'Abigail', - ]); - - -### Sequences - -Sometimes you may wish to alternate the value of a given model attribute for each created model. You may accomplish this by defining a state transformation as a sequence. For example, you may wish to alternate the value of an `admin` column between `Y` and `N` for each created user: - - use App\Models\User; - use Illuminate\Database\Eloquent\Factories\Sequence; - - $users = User::factory() - ->count(10) - ->state(new Sequence( - ['admin' => 'Y'], - ['admin' => 'N'], - )) - ->create(); - -In this example, five users will be created with an `admin` value of `Y` and five users will be created with an `admin` value of `N`. - -If necessary, you may include a closure as a sequence value. The closure will be invoked each time the sequence needs a new value: - - $users = User::factory() - ->count(10) - ->state(new Sequence( - fn ($sequence) => ['role' => UserRoles::all()->random()], - )) - ->create(); - -Within a sequence closure, you may access the `$index` or `$count` properties on the sequence instance that is injected into the closure. The `$index` property contains the number of iterations through the sequence that have occurred thus far, while the `$count` property contains the total number of times the sequence will be invoked: - - $users = User::factory() - ->count(10) - ->sequence(fn ($sequence) => ['name' => 'Name '.$sequence->index]) - ->create(); - - -## Factory Relationships - - -### Has Many Relationships - -Next, let's explore building Eloquent model relationships using Laravel's fluent factory methods. First, let's assume our application has an `App\Models\User` model and an `App\Models\Post` model. Also, let's assume that the `User` model defines a `hasMany` relationship with `Post`. We can create a user that has three posts using the `has` method provided by the Laravel's factories. The `has` method accepts a factory instance: - - use App\Models\Post; - use App\Models\User; - - $user = User::factory() - ->has(Post::factory()->count(3)) - ->create(); - -By convention, when passing a `Post` model to the `has` method, Laravel will assume that the `User` model must have a `posts` method that defines the relationship. If necessary, you may explicitly specify the name of the relationship that you would like to manipulate: - - $user = User::factory() - ->has(Post::factory()->count(3), 'posts') - ->create(); - -Of course, you may perform state manipulations on the related models. In addition, you may pass a closure based state transformation if your state change requires access to the parent model: - - $user = User::factory() - ->has( - Post::factory() - ->count(3) - ->state(function (array $attributes, User $user) { - return ['user_type' => $user->type]; - }) - ) - ->create(); - - -#### Using Magic Methods - -For convenience, you may use Laravel's magic factory relationship methods to build relationships. For example, the following example will use convention to determine that the related models should be created via a `posts` relationship method on the `User` model: - - $user = User::factory() - ->hasPosts(3) - ->create(); - -When using magic methods to create factory relationships, you may pass an array of attributes to override on the related models: - - $user = User::factory() - ->hasPosts(3, [ - 'published' => false, - ]) - ->create(); - -You may provide a closure based state transformation if your state change requires access to the parent model: - - $user = User::factory() - ->hasPosts(3, function (array $attributes, User $user) { - return ['user_type' => $user->type]; - }) - ->create(); +The `Illuminate\Foundation\Testing\RefreshDatabase` trait does not migrate your database if your schema is up to date. Instead, it will only execute the test within a database transaction. Therefore, any records added to the database by test cases that do not use this trait may still exist in the database. - -### Belongs To Relationships +If you would like to totally reset the database, you may use the `Illuminate\Foundation\Testing\DatabaseMigrations` or `Illuminate\Foundation\Testing\DatabaseTruncation` traits instead. However, both of these options are significantly slower than the `RefreshDatabase` trait. -Now that we have explored how to build "has many" relationships using factories, let's explore the inverse of the relationship. The `for` method may be used to define the parent model that factory created models belong to. For example, we can create three `App\Models\Post` model instances that belong to a single user: + +## Model Factories - use App\Models\Post; - use App\Models\User; +When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a set of default attributes for each of your [Eloquent models](/docs/{{version}}/eloquent) using [model factories](/docs/{{version}}/eloquent-factories). - $posts = Post::factory() - ->count(3) - ->for(User::factory()->state([ - 'name' => 'Jessica Archer', - ])) - ->create(); +To learn more about creating and utilizing model factories to create models, please consult the complete [model factory documentation](/docs/{{version}}/eloquent-factories). Once you have defined a model factory, you may utilize the factory within your test to create models: -If you already have a parent model instance that should be associated with the models you are creating, you may pass the model instance to the `for` method: +```php tab=Pest +use App\Models\User; +test('models can be instantiated', function () { $user = User::factory()->create(); - $posts = Post::factory() - ->count(3) - ->for($user) - ->create(); - - -#### Using Magic Methods - -For convenience, you may use Laravel's magic factory relationship methods to define "belongs to" relationships. For example, the following example will use convention to determine that the three posts should belong to the `user` relationship on the `Post` model: - - $posts = Post::factory() - ->count(3) - ->forUser([ - 'name' => 'Jessica Archer', - ]) - ->create(); - - -### Many To Many Relationships - -Like [has many relationships](#has-many-relationships), "many to many" relationships may be created using the `has` method: - - use App\Models\Role; - use App\Models\User; - - $user = User::factory() - ->has(Role::factory()->count(3)) - ->create(); - - -#### Pivot Table Attributes - -If you need to define attributes that should be set on the pivot / intermediate table linking the models, you may use the `hasAttached` method. This method accepts an array of pivot table attribute names and values as its second argument: - - use App\Models\Role; - use App\Models\User; - - $user = User::factory() - ->hasAttached( - Role::factory()->count(3), - ['active' => true] - ) - ->create(); - -You may provide a closure based state transformation if your state change requires access to the related model: - - $user = User::factory() - ->hasAttached( - Role::factory() - ->count(3) - ->state(function (array $attributes, User $user) { - return ['name' => $user->name.' Role']; - }), - ['active' => true] - ) - ->create(); - -If you already have model instances that you would like to be attached to the models you are creating, you may pass the model instances to the `hasAttached` method. In this example, the same three roles will be attached to all three users: - - $roles = Role::factory()->count(3)->create(); - - $user = User::factory() - ->count(3) - ->hasAttached($roles, ['active' => true]) - ->create(); - - -#### Using Magic Methods - -For convenience, you may use Laravel's magic factory relationship methods to define many to many relationships. For example, the following example will use convention to determine that the related models should be created via a `roles` relationship method on the `User` model: - - $user = User::factory() - ->hasRoles(1, [ - 'name' => 'Editor' - ]) - ->create(); - - -### Polymorphic Relationships - -[Polymorphic relationships](/docs/{{version}}/eloquent-relationships#polymorphic-relationships) may also be created using factories. Polymorphic "morph many" relationships are created in the same way as typical "has many" relationships. For example, if a `App\Models\Post` model has a `morphMany` relationship with a `App\Models\Comment` model: + // ... +}); +``` - use App\Models\Post; +```php tab=PHPUnit +use App\Models\User; - $post = Post::factory()->hasComments(3)->create(); +public function test_models_can_be_instantiated(): void +{ + $user = User::factory()->create(); - -#### Morph To Relationships + // ... +} +``` -Magic methods may not be used to create `morphTo` relationships. Instead, the `for` method must be used directly and the name of the relationship must be explicitly provided. For example, imagine that the `Comment` model has a `commentable` method that defines a `morphTo` relationship. In this situation, we may create three comments that belong to a single post by using the `for` method directly: + +## Running Seeders - $comments = Comment::factory()->count(3)->for( - Post::factory(), 'commentable' - )->create(); +If you would like to use [database seeders](/docs/{{version}}/seeding) to populate your database during a feature test, you may invoke the `seed` method. By default, the `seed` method will execute the `DatabaseSeeder`, which should execute all of your other seeders. Alternatively, you pass a specific seeder class name to the `seed` method: - -#### Polymorphic Many To Many Relationships +```php tab=Pest +use(RefreshDatabase::class); - $videos = Video::factory() - ->hasAttached( - Tag::factory()->count(3), - ['public' => true] - ) - ->create(); +test('orders can be created', function () { + // Run the DatabaseSeeder... + $this->seed(); -Of course, the magic `has` method may also be used to create polymorphic "many to many" relationships: + // Run a specific seeder... + $this->seed(OrderStatusSeeder::class); - $videos = Video::factory() - ->hasTags(3, ['public' => true]) - ->create(); + // ... - -### Defining Relationships Within Factories + // Run an array of specific seeders... + $this->seed([ + OrderStatusSeeder::class, + TransactionStatusSeeder::class, + // ... + ]); +}); +``` -To define a relationship within your model factory, you will typically assign a new factory instance to the foreign key of the relationship. This is normally done for the "inverse" relationships such as `belongsTo` and `morphTo` relationships. For example, if you would like to create a new user when creating a post, you may do the following: +```php tab=PHPUnit + User::factory(), - 'title' => $this->faker->title(), - 'content' => $this->faker->paragraph(), - ]; - } +use Database\Seeders\OrderStatusSeeder; +use Database\Seeders\TransactionStatusSeeder; +use Illuminate\Foundation\Testing\RefreshDatabase; +use Tests\TestCase; -If the relationship's columns depend on the factory that defines it you may assign a closure to an attribute. The closure will receive the factory's evaluated attribute array: +class ExampleTest extends TestCase +{ + use RefreshDatabase; /** - * Define the model's default state. - * - * @return array + * Test creating a new order. */ - public function definition() - { - return [ - 'user_id' => User::factory(), - 'user_type' => function (array $attributes) { - return User::find($attributes['user_id'])->type; - }, - 'title' => $this->faker->title(), - 'content' => $this->faker->paragraph(), - ]; - } - - -## Running Seeders - -If you would like to use [database seeders](/docs/{{version}}/seeding) to populate your database during a feature test, you may invoke the `seed` method. By default, the `seed` method will execute the `DatabaseSeeder`, which should execute all of your other seeders. Alternatively, you pass a specific seeder class name to the `seed` method: - - seed(); - /** - * Test creating a new order. - * - * @return void - */ - public function test_orders_can_be_created() - { - // Run the DatabaseSeeder... - $this->seed(); + // Run a specific seeder... + $this->seed(OrderStatusSeeder::class); - // Run a specific seeder... - $this->seed(OrderStatusSeeder::class); + // ... + // Run an array of specific seeders... + $this->seed([ + OrderStatusSeeder::class, + TransactionStatusSeeder::class, // ... - - // Run an array of specific seeders... - $this->seed([ - OrderStatusSeeder::class, - TransactionStatusSeeder::class, - // ... - ]); - } + ]); } +} +``` Alternatively, you may instruct Laravel to automatically seed the database before each test that uses the `RefreshDatabase` trait. You may accomplish this by defining a `$seed` property on your base test class: - ## Available Assertions -Laravel provides several database assertions for your [PHPUnit](https://phpunit.de/) feature tests. We'll discuss each of these assertions below. +Laravel provides several database assertions for your [Pest](https://pestphp.com) or [PHPUnit](https://phpunit.de) feature tests. We'll discuss each of these assertions below. #### assertDatabaseCount Assert that a table in the database contains the given number of records: - $this->assertDatabaseCount('users', 5); +```php +$this->assertDatabaseCount('users', 5); +``` + + +#### assertDatabaseEmpty + +Assert that a table in the database contains no records: + +```php +$this->assertDatabaseEmpty('users'); +``` #### assertDatabaseHas Assert that a table in the database contains records matching the given key / value query constraints: - $this->assertDatabaseHas('users', [ - 'email' => 'sally@example.com', - ]); +```php +$this->assertDatabaseHas('users', [ + 'email' => 'sally@example.com', +]); +``` #### assertDatabaseMissing Assert that a table in the database does not contain records matching the given key / value query constraints: - $this->assertDatabaseMissing('users', [ - 'email' => 'sally@example.com', - ]); +```php +$this->assertDatabaseMissing('users', [ + 'email' => 'sally@example.com', +]); +``` #### assertSoftDeleted The `assertSoftDeleted` method may be used to assert a given Eloquent model has been "soft deleted": - $this->assertSoftDeleted($user); +```php +$this->assertSoftDeleted($user); +``` + + +#### assertNotSoftDeleted + +The `assertNotSoftDeleted` method may be used to assert a given Eloquent model hasn't been "soft deleted": + +```php +$this->assertNotSoftDeleted($user); +``` #### assertModelExists -Assert that a given model exists in the database: +Assert that a given model or collection of models exist in the database: - use App\Models\User; +```php +use App\Models\User; - $user = User::factory()->create(); +$user = User::factory()->create(); - $this->assertModelExists($user); +$this->assertModelExists($user); +``` #### assertModelMissing -Assert that a given model does not exist in the database: +Assert that a given model or collection of models do not exist in the database: - use App\Models\User; +```php +use App\Models\User; - $user = User::factory()->create(); +$user = User::factory()->create(); - $user->delete(); +$user->delete(); - $this->assertModelMissing($user); +$this->assertModelMissing($user); +``` + + +#### expectsDatabaseQueryCount + +The `expectsDatabaseQueryCount` method may be invoked at the beginning of your test to specify the total number of database queries that you expect to be run during the test. If the actual number of executed queries does not exactly match this expectation, the test will fail: + +```php +$this->expectsDatabaseQueryCount(5); + +// Test... +``` diff --git a/database.md b/database.md index 26553e78656..040145ef7ec 100644 --- a/database.md +++ b/database.md @@ -2,27 +2,33 @@ - [Introduction](#introduction) - [Configuration](#configuration) - - [Read & Write Connections](#read-and-write-connections) + - [Read and Write Connections](#read-and-write-connections) - [Running SQL Queries](#running-queries) - [Using Multiple Database Connections](#using-multiple-database-connections) - - [Listening For Query Events](#listening-for-query-events) + - [Listening for Query Events](#listening-for-query-events) + - [Monitoring Cumulative Query Time](#monitoring-cumulative-query-time) - [Database Transactions](#database-transactions) -- [Connecting To The Database CLI](#connecting-to-the-database-cli) +- [Connecting to the Database CLI](#connecting-to-the-database-cli) +- [Inspecting Your Databases](#inspecting-your-databases) +- [Monitoring Your Databases](#monitoring-your-databases) ## Introduction -Almost every modern web application interacts with a database. Laravel makes interacting with databases extremely simple across a variety of supported databases using raw SQL, a [fluent query builder](/docs/{{version}}/queries), and the [Eloquent ORM](/docs/{{version}}/eloquent). Currently, Laravel provides first-party support for four databases: +Almost every modern web application interacts with a database. Laravel makes interacting with databases extremely simple across a variety of supported databases using raw SQL, a [fluent query builder](/docs/{{version}}/queries), and the [Eloquent ORM](/docs/{{version}}/eloquent). Currently, Laravel provides first-party support for five databases:
+- MariaDB 10.3+ ([Version Policy](https://mariadb.org/about/#maintenance-policy)) - MySQL 5.7+ ([Version Policy](https://en.wikipedia.org/wiki/MySQL#Release_history)) -- PostgreSQL 9.6+ ([Version Policy](https://www.postgresql.org/support/versioning/)) -- SQLite 3.8.8+ +- PostgreSQL 10.0+ ([Version Policy](https://www.postgresql.org/support/versioning/)) +- SQLite 3.26.0+ - SQL Server 2017+ ([Version Policy](https://docs.microsoft.com/en-us/lifecycle/products/?products=sql-server))
+Additionally, MongoDB is supported via the `mongodb/laravel-mongodb` package, which is officially maintained by MongoDB. Check out the [Laravel MongoDB](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/) documentation for more information. + ### Configuration @@ -40,12 +46,15 @@ DB_CONNECTION=sqlite DB_DATABASE=/absolute/path/to/database.sqlite ``` -To enable foreign key constraints for SQLite connections, you should set the `DB_FOREIGN_KEYS` environment variable to `true`: +By default, foreign key constraints are enabled for SQLite connections. If you would like to disable them, you should set the `DB_FOREIGN_KEYS` environment variable to `false`: ```ini -DB_FOREIGN_KEYS=true +DB_FOREIGN_KEYS=false ``` +> [!NOTE] +> If you use the [Laravel installer](/docs/{{version}}/installation#creating-a-laravel-project) to create your Laravel application and select SQLite as your database, Laravel will automatically create a `database/database.sqlite` file and run the default [database migrations](/docs/{{version}}/migrations) for you. + #### Microsoft SQL Server Configuration @@ -68,36 +77,45 @@ These URLs typically follow a standard schema convention: driver://username:password@host:port/database?options ``` -For convenience, Laravel supports these URLs as an alternative to configuring your database with multiple configuration options. If the `url` (or corresponding `DATABASE_URL` environment variable) configuration option is present, it will be used to extract the database connection and credential information. +For convenience, Laravel supports these URLs as an alternative to configuring your database with multiple configuration options. If the `url` (or corresponding `DB_URL` environment variable) configuration option is present, it will be used to extract the database connection and credential information. -### Read & Write Connections +### Read and Write Connections Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM. To see how read / write connections should be configured, let's look at this example: - 'mysql' => [ - 'read' => [ - 'host' => [ - '192.168.1.1', - '196.168.1.2', - ], +```php +'mysql' => [ + 'read' => [ + 'host' => [ + '192.168.1.1', + '196.168.1.2', ], - 'write' => [ - 'host' => [ - '196.168.1.3', - ], + ], + 'write' => [ + 'host' => [ + '196.168.1.3', ], - 'sticky' => true, - 'driver' => 'mysql', - 'database' => 'database', - 'username' => 'root', - 'password' => '', - 'charset' => 'utf8mb4', - 'collation' => 'utf8mb4_unicode_ci', - 'prefix' => '', ], + 'sticky' => true, + + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => env('DB_CHARSET', 'utf8mb4'), + 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], +], +``` Note that three keys have been added to the configuration array: `read`, `write` and `sticky`. The `read` and `write` keys have array values containing a single key: `host`. The rest of the database options for the `read` and `write` connections will be merged from the main `mysql` configuration array. @@ -114,103 +132,142 @@ The `sticky` option is an *optional* value that can be used to allow the immedia Once you have configured your database connection, you may run queries using the `DB` facade. The `DB` facade provides methods for each type of query: `select`, `update`, `insert`, `delete`, and `statement`. -#### Running A Select Query +#### Running a Select Query To run a basic SELECT query, you may use the `select` method on the `DB` facade: - $users]); - } + $users = DB::select('select * from users where active = ?', [1]); + + return view('user.index', ['users' => $users]); } +} +``` The first argument passed to the `select` method is the SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the `where` clause constraints. Parameter binding provides protection against SQL injection. The `select` method will always return an `array` of results. Each result within the array will be a PHP `stdClass` object representing a record from the database: - use Illuminate\Support\Facades\DB; +```php +use Illuminate\Support\Facades\DB; - $users = DB::select('select * from users'); +$users = DB::select('select * from users'); - foreach ($users as $user) { - echo $user->name; - } +foreach ($users as $user) { + echo $user->name; +} +``` + + +#### Selecting Scalar Values + +Sometimes your database query may result in a single, scalar value. Instead of being required to retrieve the query's scalar result from a record object, Laravel allows you to retrieve this value directly using the `scalar` method: + +```php +$burgers = DB::scalar( + "select count(case when food = 'burger' then 1 end) as burgers from menu" +); +``` + + +#### Selecting Multiple Result Sets + +If your application calls stored procedures that return multiple result sets, you may use the `selectResultSets` method to retrieve all of the result sets returned by the stored procedure: + +```php +[$options, $notifications] = DB::selectResultSets( + "CALL get_user_options_and_notifications(?)", $request->user()->id +); +``` #### Using Named Bindings Instead of using `?` to represent your parameter bindings, you may execute a query using named bindings: - $results = DB::select('select * from users where id = :id', ['id' => 1]); +```php +$results = DB::select('select * from users where id = :id', ['id' => 1]); +``` -#### Running An Insert Statement +#### Running an Insert Statement To execute an `insert` statement, you may use the `insert` method on the `DB` facade. Like `select`, this method accepts the SQL query as its first argument and bindings as its second argument: - use Illuminate\Support\Facades\DB; +```php +use Illuminate\Support\Facades\DB; - DB::insert('insert into users (id, name) values (?, ?)', [1, 'Marc']); +DB::insert('insert into users (id, name) values (?, ?)', [1, 'Marc']); +``` -#### Running An Update Statement +#### Running an Update Statement The `update` method should be used to update existing records in the database. The number of rows affected by the statement is returned by the method: - use Illuminate\Support\Facades\DB; +```php +use Illuminate\Support\Facades\DB; - $affected = DB::update( - 'update users set votes = 100 where name = ?', - ['Anita'] - ); +$affected = DB::update( + 'update users set votes = 100 where name = ?', + ['Anita'] +); +``` -#### Running A Delete Statement +#### Running a Delete Statement The `delete` method should be used to delete records from the database. Like `update`, the number of rows affected will be returned by the method: - use Illuminate\Support\Facades\DB; +```php +use Illuminate\Support\Facades\DB; - $deleted = DB::delete('delete from users'); +$deleted = DB::delete('delete from users'); +``` -#### Running A General Statement +#### Running a General Statement Some database statements do not return any value. For these types of operations, you may use the `statement` method on the `DB` facade: - DB::statement('drop table users'); +```php +DB::statement('drop table users'); +``` -#### Running An Unprepared Statement +#### Running an Unprepared Statement Sometimes you may want to execute an SQL statement without binding any values. You may use the `DB` facade's `unprepared` method to accomplish this: - DB::unprepared('update users set votes = 100 where name = "Dries"'); +```php +DB::unprepared('update users set votes = 100 where name = "Dries"'); +``` -> {note} Since unprepared statements do not bind parameters, they may be vulnerable to SQL injection. You should never allow user controlled values within an unprepared statement. +> [!WARNING] +> Since unprepared statements do not bind parameters, they may be vulnerable to SQL injection. You should never allow user controlled values within an unprepared statement. #### Implicit Commits When using the `DB` facade's `statement` and `unprepared` methods within transactions you must be careful to avoid statements that cause [implicit commits](https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html). These statements will cause the database engine to indirectly commit the entire transaction, leaving Laravel unaware of the database's transaction level. An example of such a statement is creating a database table: - DB::unprepared('create table a (col varchar(1) null)'); +```php +DB::unprepared('create table a (col varchar(1) null)'); +``` Please refer to the MySQL manual for [a list of all statements](https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html) that trigger implicit commits. @@ -219,100 +276,152 @@ Please refer to the MySQL manual for [a list of all statements](https://dev.mysq If your application defines multiple connections in your `config/database.php` configuration file, you may access each connection via the `connection` method provided by the `DB` facade. The connection name passed to the `connection` method should correspond to one of the connections listed in your `config/database.php` configuration file or configured at runtime using the `config` helper: - use Illuminate\Support\Facades\DB; +```php +use Illuminate\Support\Facades\DB; - $users = DB::connection('sqlite')->select(...); +$users = DB::connection('sqlite')->select(/* ... */); +``` You may access the raw, underlying PDO instance of a connection using the `getPdo` method on a connection instance: - $pdo = DB::connection()->getPdo(); +```php +$pdo = DB::connection()->getPdo(); +``` -### Listening For Query Events +### Listening for Query Events If you would like to specify a closure that is invoked for each SQL query executed by your application, you may use the `DB` facade's `listen` method. This method can be useful for logging queries or debugging. You may register your query listener closure in the `boot` method of a [service provider](/docs/{{version}}/providers): - sql; + // $query->bindings; + // $query->time; + // $query->toRawSql(); + }); + } +} +``` + + +### Monitoring Cumulative Query Time - namespace App\Providers; +A common performance bottleneck of modern web applications is the amount of time they spend querying databases. Thankfully, Laravel can invoke a closure or callback of your choice when it spends too much time querying the database during a single request. To get started, provide a query time threshold (in milliseconds) and closure to the `whenQueryingForLongerThan` method. You may invoke this method in the `boot` method of a [service provider](/docs/{{version}}/providers): - use Illuminate\Support\Facades\DB; - use Illuminate\Support\ServiceProvider; +```php +sql; - // $query->bindings; - // $query->time; - }); - } + DB::whenQueryingForLongerThan(500, function (Connection $connection, QueryExecuted $event) { + // Notify development team... + }); } +} +``` ## Database Transactions You may use the `transaction` method provided by the `DB` facade to run a set of operations within a database transaction. If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown. If the closure executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the `transaction` method: - use Illuminate\Support\Facades\DB; +```php +use Illuminate\Support\Facades\DB; - DB::transaction(function () { - DB::update('update users set votes = 1'); +DB::transaction(function () { + DB::update('update users set votes = 1'); - DB::delete('delete from posts'); - }); + DB::delete('delete from posts'); +}); +``` #### Handling Deadlocks The `transaction` method accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs. Once these attempts have been exhausted, an exception will be thrown: - use Illuminate\Support\Facades\DB; +```php +use Illuminate\Support\Facades\DB; - DB::transaction(function () { - DB::update('update users set votes = 1'); +DB::transaction(function () { + DB::update('update users set votes = 1'); - DB::delete('delete from posts'); - }, 5); + DB::delete('delete from posts'); +}, attempts: 5); +``` #### Manually Using Transactions If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the `beginTransaction` method provided by the `DB` facade: - use Illuminate\Support\Facades\DB; +```php +use Illuminate\Support\Facades\DB; - DB::beginTransaction(); +DB::beginTransaction(); +``` You can rollback the transaction via the `rollBack` method: - DB::rollBack(); +```php +DB::rollBack(); +``` Lastly, you can commit a transaction via the `commit` method: - DB::commit(); +```php +DB::commit(); +``` -> {tip} The `DB` facade's transaction methods control the transactions for both the [query builder](/docs/{{version}}/queries) and [Eloquent ORM](/docs/{{version}}/eloquent). +> [!NOTE] +> The `DB` facade's transaction methods control the transactions for both the [query builder](/docs/{{version}}/queries) and [Eloquent ORM](/docs/{{version}}/eloquent). -## Connecting To The Database CLI +## Connecting to the Database CLI If you would like to connect to your database's CLI, you may use the `db` Artisan command: @@ -326,3 +435,84 @@ If needed, you may specify a database connection name to connect to a database c php artisan db mysql ``` + +## Inspecting Your Databases + +Using the `db:show` and `db:table` Artisan commands, you can get valuable insight into your database and its associated tables. To see an overview of your database, including its size, type, number of open connections, and a summary of its tables, you may use the `db:show` command: + +```shell +php artisan db:show +``` + +You may specify which database connection should be inspected by providing the database connection name to the command via the `--database` option: + +```shell +php artisan db:show --database=pgsql +``` + +If you would like to include table row counts and database view details within the output of the command, you may provide the `--counts` and `--views` options, respectively. On large databases, retrieving row counts and view details can be slow: + +```shell +php artisan db:show --counts --views +``` + +In addition, you may use the following `Schema` methods to inspect your database: + +```php +use Illuminate\Support\Facades\Schema; + +$tables = Schema::getTables(); +$views = Schema::getViews(); +$columns = Schema::getColumns('users'); +$indexes = Schema::getIndexes('users'); +$foreignKeys = Schema::getForeignKeys('users'); +``` + +If you would like to inspect a database connection that is not your application's default connection, you may use the `connection` method: + +```php +$columns = Schema::connection('sqlite')->getColumns('users'); +``` + + +#### Table Overview + +If you would like to get an overview of an individual table within your database, you may execute the `db:table` Artisan command. This command provides a general overview of a database table, including its columns, types, attributes, keys, and indexes: + +```shell +php artisan db:table users +``` + + +## Monitoring Your Databases + +Using the `db:monitor` Artisan command, you can instruct Laravel to dispatch an `Illuminate\Database\Events\DatabaseBusy` event if your database is managing more than a specified number of open connections. + +To get started, you should schedule the `db:monitor` command to [run every minute](/docs/{{version}}/scheduling). The command accepts the names of the database connection configurations that you wish to monitor as well as the maximum number of open connections that should be tolerated before dispatching an event: + +```shell +php artisan db:monitor --databases=mysql,pgsql --max=100 +``` + +Scheduling this command alone is not enough to trigger a notification alerting you of the number of open connections. When the command encounters a database that has an open connection count that exceeds your threshold, a `DatabaseBusy` event will be dispatched. You should listen for this event within your application's `AppServiceProvider` in order to send a notification to you or your development team: + +```php +use App\Notifications\DatabaseApproachingMaxConnections; +use Illuminate\Database\Events\DatabaseBusy; +use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\Notification; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Event::listen(function (DatabaseBusy $event) { + Notification::route('mail', 'dev@example.com') + ->notify(new DatabaseApproachingMaxConnections( + $event->connectionName, + $event->connections + )); + }); +} +``` diff --git a/deployment.md b/deployment.md index 5f67cef82af..292e0be0221 100644 --- a/deployment.md +++ b/deployment.md @@ -4,13 +4,16 @@ - [Server Requirements](#server-requirements) - [Server Configuration](#server-configuration) - [Nginx](#nginx) + - [FrankenPHP](#frankenphp) + - [Directory Permissions](#directory-permissions) - [Optimization](#optimization) - - [Autoloader Optimization](#autoloader-optimization) - - [Optimizing Configuration Loading](#optimizing-configuration-loading) - - [Optimizing Route Loading](#optimizing-route-loading) - - [Optimizing View Loading](#optimizing-view-loading) + - [Caching Configuration](#optimizing-configuration-loading) + - [Caching Events](#caching-events) + - [Caching Routes](#optimizing-route-loading) + - [Caching Views](#optimizing-view-loading) - [Debug Mode](#debug-mode) -- [Deploying With Forge / Vapor](#deploying-with-forge-or-vapor) +- [The Health Route](#the-health-route) +- [Deploying With Laravel Cloud or Forge](#deploying-with-cloud-or-forge) ## Introduction @@ -24,16 +27,18 @@ The Laravel framework has a few system requirements. You should ensure that your
-- PHP >= 8.0 -- BCMath PHP Extension +- PHP >= 8.2 - Ctype PHP Extension +- cURL PHP Extension - DOM PHP Extension - Fileinfo PHP Extension -- JSON PHP Extension +- Filter PHP Extension +- Hash PHP Extension - Mbstring PHP Extension - OpenSSL PHP Extension - PCRE PHP Extension - PDO PHP Extension +- Session PHP Extension - Tokenizer PHP Extension - XML PHP Extension @@ -45,7 +50,7 @@ The Laravel framework has a few system requirements. You should ensure that your ### Nginx -If you are deploying your application to a server that is running Nginx, you may use the following configuration file as a starting point for configuring your web server. Most likely, this file will need to be customized depending on your server's configuration. **If you would like assistance in managing your server, consider using a first-party Laravel server management and deployment service such as [Laravel Forge](https://forge.laravel.com).** +If you are deploying your application to a server that is running Nginx, you may use the following configuration file as a starting point for configuring your web server. Most likely, this file will need to be customized depending on your server's configuration. **If you would like assistance in managing your server, consider using a fully-managed Laravel platform like [Laravel Cloud](https://cloud.laravel.com).** Please ensure, like the configuration below, your web server directs all requests to your application's `public/index.php` file. You should never attempt to move the `index.php` file to your project's root, as serving the application from the project root will expose many sensitive configuration files to the public Internet: @@ -72,10 +77,11 @@ server { error_page 404 /index.php; - location ~ \.php$ { - fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; + location ~ ^/index\.php(/|$) { + fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; + fastcgi_hide_header X-Powered-By; } location ~ /\.(?!well-known).* { @@ -84,22 +90,41 @@ server { } ``` + +### FrankenPHP + +[FrankenPHP](https://frankenphp.dev/) may also be used to serve your Laravel applications. FrankenPHP is a modern PHP application server written in Go. To serve a Laravel PHP application using FrankenPHP, you may simply invoke its `php-server` command: + +```shell +frankenphp php-server -r public/ +``` + +To take advantage of more powerful features supported by FrankenPHP, such as its [Laravel Octane](/docs/{{version}}/octane) integration, HTTP/3, modern compression, or the ability to package Laravel applications as standalone binaries, please consult FrankenPHP's [Laravel documentation](https://frankenphp.dev/docs/laravel/). + + +### Directory Permissions + +Laravel will need to write to the `bootstrap/cache` and `storage` directories, so you should ensure the web server process owner has permission to write to these directories. + ## Optimization - -### Autoloader Optimization +When deploying your application to production, there are a variety of files that should be cached, including your configuration, events, routes, and views. Laravel provides a single, convenient `optimize` Artisan command that will cache all of these files. This command should typically be invoked as part of your application's deployment process: + +```shell +php artisan optimize +``` -When deploying to production, make sure that you are optimizing Composer's class autoloader map so Composer can quickly find the proper file to load for a given class: +The `optimize:clear` method may be used to remove all of the cache files generated by the `optimize` command as well as all keys in the default cache driver: ```shell -composer install --optimize-autoloader --no-dev +php artisan optimize:clear ``` -> {tip} In addition to optimizing the autoloader, you should always be sure to include a `composer.lock` file in your project's source control repository. Your project's dependencies can be installed much faster when a `composer.lock` file is present. +In the following documentation, we will discuss each of the granular optimization commands that are executed by the `optimize` command. -### Optimizing Configuration Loading +### Caching Configuration When deploying your application to production, you should make sure that you run the `config:cache` Artisan command during your deployment process: @@ -109,10 +134,20 @@ php artisan config:cache This command will combine all of Laravel's configuration files into a single, cached file, which greatly reduces the number of trips the framework must make to the filesystem when loading your configuration values. -> {note} If you execute the `config:cache` command during your deployment process, you should be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded and all calls to the `env` function for `.env` variables will return `null`. +> [!WARNING] +> If you execute the `config:cache` command during your deployment process, you should be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded and all calls to the `env` function for `.env` variables will return `null`. + + +### Caching Events + +You should cache your application's auto-discovered event to listener mappings during your deployment process. This can be accomplished by invoking the `event:cache` Artisan command during deployment: + +```shell +php artisan event:cache +``` -### Optimizing Route Loading +### Caching Routes If you are building a large application with many routes, you should make sure that you are running the `route:cache` Artisan command during your deployment process: @@ -123,7 +158,7 @@ php artisan route:cache This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes. -### Optimizing View Loading +### Caching Views When deploying your application to production, you should make sure that you run the `view:cache` Artisan command during your deployment process: @@ -136,21 +171,42 @@ This command precompiles all your Blade views so they are not compiled on demand ## Debug Mode -The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file. +The debug option in your `config/app.php` configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the `APP_DEBUG` environment variable, which is stored in your application's `.env` file. + +> [!WARNING] +> **In your production environment, this value should always be `false`. If the `APP_DEBUG` variable is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.** + + +## The Health Route -**In your production environment, this value should always be `false`. If the `APP_DEBUG` variable is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.** +Laravel includes a built-in health check route that can be used to monitor the status of your application. In production, this route may be used to report the status of your application to an uptime monitor, load balancer, or orchestration system such as Kubernetes. + +By default, the health check route is served at `/up` and will return a 200 HTTP response if the application has booted without exceptions. Otherwise, a 500 HTTP response will be returned. You may configure the URI for this route in your application's `bootstrap/app` file: + +```php +->withRouting( + web: __DIR__.'/../routes/web.php', + commands: __DIR__.'/../routes/console.php', + health: '/up', // [tl! remove] + health: '/status', // [tl! add] +) +``` - -## Deploying With Forge / Vapor +When HTTP requests are made to this route, Laravel will also dispatch a `Illuminate\Foundation\Events\DiagnosingHealth` event, allowing you to perform additional health checks relevant to your application. Within a [listener](/docs/{{version}}/events) for this event, you may check your application's database or cache status. If you detect a problem with your application, you may simply throw an exception from the listener. + + +## Deploying With Laravel Cloud or Forge + + +#### Laravel Cloud + +If you would like a fully-managed, auto-scaling deployment platform tuned for Laravel, check out [Laravel Cloud](https://cloud.laravel.com). Laravel Cloud is a robust deployment platform for Laravel, offering managed compute, databases, caches, and object storage. + +Launch your Laravel application on Cloud and fall in love with the scalable simplicity. Laravel Cloud is fine-tuned by Laravel's creators to work seamlessly with the framework so you can keep writing your Laravel applications exactly like you're used to. #### Laravel Forge -If you aren't quite ready to manage your own server configuration or aren't comfortable configuring all of the various services needed to run a robust Laravel application, [Laravel Forge](https://forge.laravel.com) is a wonderful alternative. +If you prefer to manage your own servers but aren't comfortable configuring all of the various services needed to run a robust Laravel application, [Laravel Forge](https://forge.laravel.com) is a VPS server management platform for Laravel applications. Laravel Forge can create servers on various infrastructure providers such as DigitalOcean, Linode, AWS, and more. In addition, Forge installs and manages all of the tools needed to build robust Laravel applications, such as Nginx, MySQL, Redis, Memcached, Beanstalk, and more. - - -#### Laravel Vapor - -If you would like a totally serverless, auto-scaling deployment platform tuned for Laravel, check out [Laravel Vapor](https://vapor.laravel.com). Laravel Vapor is a serverless deployment platform for Laravel, powered by AWS. Launch your Laravel infrastructure on Vapor and fall in love with the scalable simplicity of serverless. Laravel Vapor is fine-tuned by Laravel's creators to work seamlessly with the framework so you can keep writing your Laravel applications exactly like you're used to. diff --git a/documentation.md b/documentation.md index 5da7f822cba..933c8531f59 100644 --- a/documentation.md +++ b/documentation.md @@ -6,6 +6,7 @@ - [Installation](/docs/{{version}}/installation) - [Configuration](/docs/{{version}}/configuration) - [Directory Structure](/docs/{{version}}/structure) + - [Frontend](/docs/{{version}}/frontend) - [Starter Kits](/docs/{{version}}/starter-kits) - [Deployment](/docs/{{version}}/deployment) - ## Architecture Concepts @@ -22,6 +23,7 @@ - [Responses](/docs/{{version}}/responses) - [Views](/docs/{{version}}/views) - [Blade Templates](/docs/{{version}}/blade) + - [Asset Bundling](/docs/{{version}}/vite) - [URL Generation](/docs/{{version}}/urls) - [Session](/docs/{{version}}/session) - [Validation](/docs/{{version}}/validation) @@ -32,7 +34,8 @@ - [Broadcasting](/docs/{{version}}/broadcasting) - [Cache](/docs/{{version}}/cache) - [Collections](/docs/{{version}}/collections) - - [Compiling Assets](/docs/{{version}}/mix) + - [Concurrency](/docs/{{version}}/concurrency) + - [Context](/docs/{{version}}/context) - [Contracts](/docs/{{version}}/contracts) - [Events](/docs/{{version}}/events) - [File Storage](/docs/{{version}}/filesystem) @@ -42,8 +45,10 @@ - [Mail](/docs/{{version}}/mail) - [Notifications](/docs/{{version}}/notifications) - [Package Development](/docs/{{version}}/packages) + - [Processes](/docs/{{version}}/processes) - [Queues](/docs/{{version}}/queues) - [Rate Limiting](/docs/{{version}}/rate-limiting) + - [Strings](/docs/{{version}}/strings) - [Task Scheduling](/docs/{{version}}/scheduling) - ## Security - [Authentication](/docs/{{version}}/authentication) @@ -59,6 +64,7 @@ - [Migrations](/docs/{{version}}/migrations) - [Seeding](/docs/{{version}}/seeding) - [Redis](/docs/{{version}}/redis) + - [MongoDB](/docs/{{version}}/mongodb) - ## Eloquent ORM - [Getting Started](/docs/{{version}}/eloquent) - [Relationships](/docs/{{version}}/eloquent-relationships) @@ -66,6 +72,7 @@ - [Mutators / Casts](/docs/{{version}}/eloquent-mutators) - [API Resources](/docs/{{version}}/eloquent-resources) - [Serialization](/docs/{{version}}/eloquent-serialization) + - [Factories](/docs/{{version}}/eloquent-factories) - ## Testing - [Getting Started](/docs/{{version}}/testing) - [HTTP Tests](/docs/{{version}}/http-tests) @@ -74,21 +81,28 @@ - [Database](/docs/{{version}}/database-testing) - [Mocking](/docs/{{version}}/mocking) - ## Packages - - [Breeze](/docs/{{version}}/starter-kits#laravel-breeze) - [Cashier (Stripe)](/docs/{{version}}/billing) - [Cashier (Paddle)](/docs/{{version}}/cashier-paddle) - [Dusk](/docs/{{version}}/dusk) - [Envoy](/docs/{{version}}/envoy) - [Fortify](/docs/{{version}}/fortify) + - [Folio](/docs/{{version}}/folio) - [Homestead](/docs/{{version}}/homestead) - [Horizon](/docs/{{version}}/horizon) - - [Jetstream](https://jetstream.laravel.com) + - [MCP](/docs/{{version}}/mcp) + - [Mix](/docs/{{version}}/mix) - [Octane](/docs/{{version}}/octane) - [Passport](/docs/{{version}}/passport) + - [Pennant](/docs/{{version}}/pennant) + - [Pint](/docs/{{version}}/pint) + - [Precognition](/docs/{{version}}/precognition) + - [Prompts](/docs/{{version}}/prompts) + - [Pulse](/docs/{{version}}/pulse) + - [Reverb](/docs/{{version}}/reverb) - [Sail](/docs/{{version}}/sail) - [Sanctum](/docs/{{version}}/sanctum) - [Scout](/docs/{{version}}/scout) - [Socialite](/docs/{{version}}/socialite) - [Telescope](/docs/{{version}}/telescope) - [Valet](/docs/{{version}}/valet) -- [API Documentation](/api/9.x) +- [API Documentation](https://api.laravel.com/docs/12.x) diff --git a/dusk.md b/dusk.md index 7990b33cbc5..4cd5416a295 100644 --- a/dusk.md +++ b/dusk.md @@ -6,7 +6,7 @@ - [Using Other Browsers](#using-other-browsers) - [Getting Started](#getting-started) - [Generating Tests](#generating-tests) - - [Database Migrations](#migrations) + - [Resetting the Database After Each Test](#resetting-the-database-after-each-test) - [Running Tests](#running-tests) - [Environment Handling](#environment-handling) - [Browser Basics](#browser-basics) @@ -17,27 +17,28 @@ - [Authentication](#authentication) - [Cookies](#cookies) - [Executing JavaScript](#executing-javascript) - - [Taking A Screenshot](#taking-a-screenshot) - - [Storing Console Output To Disk](#storing-console-output-to-disk) - - [Storing Page Source To Disk](#storing-page-source-to-disk) + - [Taking a Screenshot](#taking-a-screenshot) + - [Storing Console Output to Disk](#storing-console-output-to-disk) + - [Storing Page Source to Disk](#storing-page-source-to-disk) - [Interacting With Elements](#interacting-with-elements) - [Dusk Selectors](#dusk-selectors) - - [Text, Values, & Attributes](#text-values-and-attributes) + - [Text, Values, and Attributes](#text-values-and-attributes) - [Interacting With Forms](#interacting-with-forms) - [Attaching Files](#attaching-files) - [Pressing Buttons](#pressing-buttons) - [Clicking Links](#clicking-links) - - [Using The Keyboard](#using-the-keyboard) - - [Using The Mouse](#using-the-mouse) + - [Using the Keyboard](#using-the-keyboard) + - [Using the Mouse](#using-the-mouse) - [JavaScript Dialogs](#javascript-dialogs) + - [Interacting With Inline Frames](#interacting-with-iframes) - [Scoping Selectors](#scoping-selectors) - - [Waiting For Elements](#waiting-for-elements) - - [Scrolling An Element Into View](#scrolling-an-element-into-view) + - [Waiting for Elements](#waiting-for-elements) + - [Scrolling an Element Into View](#scrolling-an-element-into-view) - [Available Assertions](#available-assertions) - [Pages](#pages) - [Generating Pages](#generating-pages) - [Configuring Pages](#configuring-pages) - - [Navigating To Pages](#navigating-to-pages) + - [Navigating to Pages](#navigating-to-pages) - [Shorthand Selectors](#shorthand-selectors) - [Page Methods](#page-methods) - [Components](#components) @@ -47,10 +48,14 @@ - [Heroku CI](#running-tests-on-heroku-ci) - [Travis CI](#running-tests-on-travis-ci) - [GitHub Actions](#running-tests-on-github-actions) + - [Chipper CI](#running-tests-on-chipper-ci) ## Introduction +> [!WARNING] +> [Pest 4](https://pestphp.com/) now includes automated browser testing which offers significant performance and usability improvements compared to Laravel Dusk. For new projects, we recommend using Pest for browser testing. + [Laravel Dusk](https://github.com/laravel/dusk) provides an expressive, easy-to-use browser automation and testing API. By default, Dusk does not require you to install JDK or Selenium on your local computer. Instead, Dusk uses a standalone [ChromeDriver](https://sites.google.com/chromium.org/driver) installation. However, you are free to utilize any other Selenium compatible driver you wish. @@ -59,12 +64,13 @@ To get started, you should install [Google Chrome](https://www.google.com/chrome) and add the `laravel/dusk` Composer dependency to your project: ```shell -composer require --dev laravel/dusk +composer require laravel/dusk --dev ``` -> {note} If you are manually registering Dusk's service provider, you should **never** register it in your production environment, as doing so could lead to arbitrary users being able to authenticate with your application. +> [!WARNING] +> If you are manually registering Dusk's service provider, you should **never** register it in your production environment, as doing so could lead to arbitrary users being able to authenticate with your application. -After installing the Dusk package, execute the `dusk:install` Artisan command. The `dusk:install` command will create a `tests/Browser` directory and an example Dusk test: +After installing the Dusk package, execute the `dusk:install` Artisan command. The `dusk:install` command will create a `tests/Browser` directory, an example Dusk test, and install the Chrome Driver binary for your operating system: ```shell php artisan dusk:install @@ -72,12 +78,13 @@ php artisan dusk:install Next, set the `APP_URL` environment variable in your application's `.env` file. This value should match the URL you use to access your application in a browser. -> {tip} If you are using [Laravel Sail](/docs/{{version}}/sail) to manage your local development environment, please also consult the Sail documentation on [configuring and running Dusk tests](/docs/{{version}}/sail#laravel-dusk). +> [!NOTE] +> If you are using [Laravel Sail](/docs/{{version}}/sail) to manage your local development environment, please also consult the Sail documentation on [configuring and running Dusk tests](/docs/{{version}}/sail#laravel-dusk). ### Managing ChromeDriver Installations -If you would like to install a different version of ChromeDriver than what is included with Laravel Dusk, you may use the `dusk:chrome-driver` command: +If you would like to install a different version of ChromeDriver than what is installed by Laravel Dusk via the `dusk:install` command, you may use the `dusk:chrome-driver` command: ```shell # Install the latest version of ChromeDriver for your OS... @@ -93,7 +100,8 @@ php artisan dusk:chrome-driver --all php artisan dusk:chrome-driver --detect ``` -> {note} Dusk requires the `chromedriver` binaries to be executable. If you're having problems running Dusk, you should ensure the binaries are executable using the following command: `chmod -R 0755 vendor/laravel/dusk/bin/`. +> [!WARNING] +> Dusk requires the `chromedriver` binaries to be executable. If you're having problems running Dusk, you should ensure the binaries are executable using the following command: `chmod -R 0755 vendor/laravel/dusk/bin/`. ### Using Other Browsers @@ -102,30 +110,33 @@ By default, Dusk uses Google Chrome and a standalone [ChromeDriver](https://site To get started, open your `tests/DuskTestCase.php` file, which is the base Dusk test case for your application. Within this file, you can remove the call to the `startChromeDriver` method. This will stop Dusk from automatically starting the ChromeDriver: - /** - * Prepare for Dusk test execution. - * - * @beforeClass - * @return void - */ - public static function prepare() - { - // static::startChromeDriver(); - } +```php +/** + * Prepare for Dusk test execution. + * + * @beforeClass + */ +public static function prepare(): void +{ + // static::startChromeDriver(); +} +``` Next, you may modify the `driver` method to connect to the URL and port of your choice. In addition, you may modify the "desired capabilities" that should be passed to the WebDriver: - /** - * Create the RemoteWebDriver instance. - * - * @return \Facebook\WebDriver\Remote\RemoteWebDriver - */ - protected function driver() - { - return RemoteWebDriver::create( - 'http://localhost:4444/wd/hub', DesiredCapabilities::phantomjs() - ); - } +```php +use Facebook\WebDriver\Remote\RemoteWebDriver; + +/** + * Create the RemoteWebDriver instance. + */ +protected function driver(): RemoteWebDriver +{ + return RemoteWebDriver::create( + 'http://localhost:4444/wd/hub', DesiredCapabilities::phantomjs() + ); +} +``` ## Getting Started @@ -139,26 +150,136 @@ To generate a Dusk test, use the `dusk:make` Artisan command. The generated test php artisan dusk:make LoginTest ``` - -### Database Migrations + +### Resetting the Database After Each Test -Most of the tests you write will interact with pages that retrieve data from your application's database; however, your Dusk tests should never use the `RefreshDatabase `trait. The `RefreshDatabase` trait leverages database transactions which will not be applicable or available across HTTP requests. Instead, use the `DatabaseMigrations` trait, which re-migrates the database for each test: +Most of the tests you write will interact with pages that retrieve data from your application's database; however, your Dusk tests should never use the `RefreshDatabase` trait. The `RefreshDatabase` trait leverages database transactions which will not be applicable or available across HTTP requests. Instead, you have two options: the `DatabaseMigrations` trait and the `DatabaseTruncation` trait. - +#### Using Database Migrations - namespace Tests\Browser; +The `DatabaseMigrations` trait will run your database migrations before each test. However, dropping and re-creating your database tables for each test is typically slower than truncating the tables: - use App\Models\User; - use Illuminate\Foundation\Testing\DatabaseMigrations; - use Laravel\Dusk\Chrome; - use Tests\DuskTestCase; +```php tab=Pest +use(DatabaseMigrations::class); + +// +``` + +```php tab=PHPUnit + [!WARNING] +> SQLite in-memory databases may not be used when executing Dusk tests. Since the browser executes within its own process, it will not be able to access the in-memory databases of other processes. + + +#### Using Database Truncation + +The `DatabaseTruncation` trait will migrate your database on the first test in order to ensure your database tables have been properly created. However, on subsequent tests, the database's tables will simply be truncated - providing a speed boost over re-running all of your database migrations: + +```php tab=Pest + {note} SQLite in-memory databases may not be used when executing Dusk tests. Since the browser executes within its own process, it will not be able to access the in-memory databases of other processes. +pest()->use(DatabaseTruncation::class); + +// +``` + +```php tab=PHPUnit + [!NOTE] +> If you are using Pest, you should define properties or methods on the base `DuskTestCase` class or on any class your test file extends. + +```php +/** + * Indicates which tables should be truncated. + * + * @var array + */ +protected $tablesToTruncate = ['users']; +``` + +Alternatively, you may define an `$exceptTables` property on your test class to specify which tables should be excluded from truncation: + +```php +/** + * Indicates which tables should be excluded from truncation. + * + * @var array + */ +protected $exceptTables = ['users']; +``` + +To specify the database connections that should have their tables truncated, you may define a `$connectionsToTruncate` property on your test class: + +```php +/** + * Indicates which connections should have their tables truncated. + * + * @var array + */ +protected $connectionsToTruncate = ['mysql']; +``` + +If you would like to execute code before or after database truncation is performed, you may define `beforeTruncatingDatabase` or `afterTruncatingDatabase` methods on your test class: + +```php +/** + * Perform any work that should take place before the database has started truncating. + */ +protected function beforeTruncatingDatabase(): void +{ + // +} + +/** + * Perform any work that should take place after the database has finished truncating. + */ +protected function afterTruncatingDatabase(): void +{ + // +} +``` ### Running Tests @@ -175,43 +296,47 @@ If you had test failures the last time you ran the `dusk` command, you may save php artisan dusk:fails ``` -The `dusk` command accepts any argument that is normally accepted by the PHPUnit test runner, such as allowing you to only run the tests for a given [group](https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.group): +The `dusk` command accepts any argument that is normally accepted by the Pest / PHPUnit test runner, such as allowing you to only run the tests for a given [group](https://docs.phpunit.de/en/10.5/annotations.html#group): ```shell php artisan dusk --group=foo ``` -> {tip} If you are using [Laravel Sail](/docs/{{version}}/sail) to manage your local development environment, please consult the Sail documentation on [configuring and running Dusk tests](/docs/{{version}}/sail#laravel-dusk). +> [!NOTE] +> If you are using [Laravel Sail](/docs/{{version}}/sail) to manage your local development environment, please consult the Sail documentation on [configuring and running Dusk tests](/docs/{{version}}/sail#laravel-dusk). #### Manually Starting ChromeDriver By default, Dusk will automatically attempt to start ChromeDriver. If this does not work for your particular system, you may manually start ChromeDriver before running the `dusk` command. If you choose to start ChromeDriver manually, you should comment out the following line of your `tests/DuskTestCase.php` file: - /** - * Prepare for Dusk test execution. - * - * @beforeClass - * @return void - */ - public static function prepare() - { - // static::startChromeDriver(); - } +```php +/** + * Prepare for Dusk test execution. + * + * @beforeClass + */ +public static function prepare(): void +{ + // static::startChromeDriver(); +} +``` In addition, if you start ChromeDriver on a port other than 9515, you should modify the `driver` method of the same class to reflect the correct port: - /** - * Create the RemoteWebDriver instance. - * - * @return \Facebook\WebDriver\Remote\RemoteWebDriver - */ - protected function driver() - { - return RemoteWebDriver::create( - 'http://localhost:9515/', DesiredCapabilities::chrome() - ); - } +```php +use Facebook\WebDriver\Remote\RemoteWebDriver; + +/** + * Create the RemoteWebDriver instance. + */ +protected function driver(): RemoteWebDriver +{ + return RemoteWebDriver::create( + 'http://localhost:9515/', DesiredCapabilities::chrome() + ); +} +``` ### Environment Handling @@ -228,39 +353,63 @@ When running tests, Dusk will back-up your `.env` file and rename your Dusk envi To get started, let's write a test that verifies we can log into our application. After generating a test, we can modify it to navigate to the login page, enter some credentials, and click the "Login" button. To create a browser instance, you may call the `browse` method from within your Dusk test: - use(DatabaseMigrations::class); - class ExampleTest extends DuskTestCase - { - use DatabaseMigrations; - - /** - * A basic browser test example. - * - * @return void - */ - public function test_basic_example() - { - $user = User::factory()->create([ - 'email' => 'taylor@laravel.com', - ]); +test('basic example', function () { + $user = User::factory()->create([ + 'email' => 'taylor@laravel.com', + ]); - $this->browse(function ($browser) use ($user) { - $browser->visit('/login') - ->type('email', $user->email) - ->type('password', 'password') - ->press('Login') - ->assertPathIs('/home'); - }); - } + $this->browse(function (Browser $browser) use ($user) { + $browser->visit('/login') + ->type('email', $user->email) + ->type('password', 'password') + ->press('Login') + ->assertPathIs('/home'); + }); +}); +``` + +```php tab=PHPUnit +create([ + 'email' => 'taylor@laravel.com', + ]); + + $this->browse(function (Browser $browser) use ($user) { + $browser->visit('/login') + ->type('email', $user->email) + ->type('password', 'password') + ->press('Login') + ->assertPathIs('/home'); + }); } +} +``` As you can see in the example above, the `browse` method accepts a closure. A browser instance will automatically be passed to this closure by Dusk and is the main object used to interact with and make assertions against your application. @@ -269,169 +418,221 @@ As you can see in the example above, the `browse` method accepts a closure. A br Sometimes you may need multiple browsers in order to properly carry out a test. For example, multiple browsers may be needed to test a chat screen that interacts with websockets. To create multiple browsers, simply add more browser arguments to the signature of the closure given to the `browse` method: - $this->browse(function ($first, $second) { - $first->loginAs(User::find(1)) - ->visit('/home') - ->waitForText('Message'); - - $second->loginAs(User::find(2)) - ->visit('/home') - ->waitForText('Message') - ->type('message', 'Hey Taylor') - ->press('Send'); - - $first->waitForText('Hey Taylor') - ->assertSee('Jeffrey Way'); - }); +```php +$this->browse(function (Browser $first, Browser $second) { + $first->loginAs(User::find(1)) + ->visit('/home') + ->waitForText('Message'); + + $second->loginAs(User::find(2)) + ->visit('/home') + ->waitForText('Message') + ->type('message', 'Hey Taylor') + ->press('Send'); + + $first->waitForText('Hey Taylor') + ->assertSee('Jeffrey Way'); +}); +``` ### Navigation The `visit` method may be used to navigate to a given URI within your application: - $browser->visit('/login'); +```php +$browser->visit('/login'); +``` You may use the `visitRoute` method to navigate to a [named route](/docs/{{version}}/routing#named-routes): - $browser->visitRoute('login'); +```php +$browser->visitRoute($routeName, $parameters); +``` You may navigate "back" and "forward" using the `back` and `forward` methods: - $browser->back(); +```php +$browser->back(); - $browser->forward(); +$browser->forward(); +``` You may use the `refresh` method to refresh the page: - $browser->refresh(); +```php +$browser->refresh(); +``` ### Resizing Browser Windows You may use the `resize` method to adjust the size of the browser window: - $browser->resize(1920, 1080); +```php +$browser->resize(1920, 1080); +``` The `maximize` method may be used to maximize the browser window: - $browser->maximize(); +```php +$browser->maximize(); +``` The `fitContent` method will resize the browser window to match the size of its content: - $browser->fitContent(); +```php +$browser->fitContent(); +``` When a test fails, Dusk will automatically resize the browser to fit the content prior to taking a screenshot. You may disable this feature by calling the `disableFitOnFailure` method within your test: - $browser->disableFitOnFailure(); +```php +$browser->disableFitOnFailure(); +``` You may use the `move` method to move the browser window to a different position on your screen: - $browser->move($x = 100, $y = 100); +```php +$browser->move($x = 100, $y = 100); +``` ### Browser Macros If you would like to define a custom browser method that you can re-use in a variety of your tests, you may use the `macro` method on the `Browser` class. Typically, you should call this method from a [service provider's](/docs/{{version}}/providers) `boot` method: - script("$('html, body').animate({ scrollTop: $('$element').offset().top }, 0);"); - - return $this; - }); - } + Browser::macro('scrollToElement', function (string $element = null) { + $this->script("$('html, body').animate({ scrollTop: $('$element').offset().top }, 0);"); + + return $this; + }); } +} +``` The `macro` function accepts a name as its first argument, and a closure as its second. The macro's closure will be executed when calling the macro as a method on a `Browser` instance: - $this->browse(function ($browser) use ($user) { - $browser->visit('/pay') - ->scrollToElement('#credit-card-details') - ->assertSee('Enter Credit Card Details'); - }); +```php +$this->browse(function (Browser $browser) use ($user) { + $browser->visit('/pay') + ->scrollToElement('#credit-card-details') + ->assertSee('Enter Credit Card Details'); +}); +``` ### Authentication Often, you will be testing pages that require authentication. You can use Dusk's `loginAs` method in order to avoid interacting with your application's login screen during every test. The `loginAs` method accepts a primary key associated with your authenticatable model or an authenticatable model instance: - use App\Models\User; +```php +use App\Models\User; +use Laravel\Dusk\Browser; - $this->browse(function ($browser) { - $browser->loginAs(User::find(1)) - ->visit('/home'); - }); +$this->browse(function (Browser $browser) { + $browser->loginAs(User::find(1)) + ->visit('/home'); +}); +``` -> {note} After using the `loginAs` method, the user session will be maintained for all tests within the file. +> [!WARNING] +> After using the `loginAs` method, the user session will be maintained for all tests within the file. ### Cookies You may use the `cookie` method to get or set an encrypted cookie's value. By default, all of the cookies created by Laravel are encrypted: - $browser->cookie('name'); +```php +$browser->cookie('name'); - $browser->cookie('name', 'Taylor'); +$browser->cookie('name', 'Taylor'); +``` You may use the `plainCookie` method to get or set an unencrypted cookie's value: - $browser->plainCookie('name'); +```php +$browser->plainCookie('name'); - $browser->plainCookie('name', 'Taylor'); +$browser->plainCookie('name', 'Taylor'); +``` You may use the `deleteCookie` method to delete the given cookie: - $browser->deleteCookie('name'); +```php +$browser->deleteCookie('name'); +``` ### Executing JavaScript You may use the `script` method to execute arbitrary JavaScript statements within the browser: - $browser->script('document.documentElement.scrollTop = 0'); +```php +$browser->script('document.documentElement.scrollTop = 0'); - $browser->script([ - 'document.body.scrollTop = 0', - 'document.documentElement.scrollTop = 0', - ]); +$browser->script([ + 'document.body.scrollTop = 0', + 'document.documentElement.scrollTop = 0', +]); - $output = $browser->script('return window.location.pathname'); +$output = $browser->script('return window.location.pathname'); +``` -### Taking A Screenshot +### Taking a Screenshot You may use the `screenshot` method to take a screenshot and store it with the given filename. All screenshots will be stored within the `tests/Browser/screenshots` directory: - $browser->screenshot('filename'); +```php +$browser->screenshot('filename'); +``` + +The `responsiveScreenshots` method may be used to take a series of screenshots at various breakpoints: + +```php +$browser->responsiveScreenshots('filename'); +``` + +The `screenshotElement` method may be used to take a screenshot of a specific element on the page: + +```php +$browser->screenshotElement('#selector', 'filename'); +``` -### Storing Console Output To Disk +### Storing Console Output to Disk You may use the `storeConsoleLog` method to write the current browser's console output to disk with the given filename. Console output will be stored within the `tests/Browser/console` directory: - $browser->storeConsoleLog('filename'); +```php +$browser->storeConsoleLog('filename'); +``` -### Storing Page Source To Disk +### Storing Page Source to Disk You may use the `storeSource` method to write the current page's source to disk with the given filename. The page source will be stored within the `tests/Browser/source` directory: - $browser->storeSource('filename'); +```php +$browser->storeSource('filename'); +``` ## Interacting With Elements @@ -441,55 +642,79 @@ You may use the `storeSource` method to write the current page's source to disk Choosing good CSS selectors for interacting with elements is one of the hardest parts of writing Dusk tests. Over time, frontend changes can cause CSS selectors like the following to break your tests: - // HTML... +```html +// HTML... - + +``` - // Test... +```php +// Test... - $browser->click('.login-page .container div > button'); +$browser->click('.login-page .container div > button'); +``` Dusk selectors allow you to focus on writing effective tests rather than remembering CSS selectors. To define a selector, add a `dusk` attribute to your HTML element. Then, when interacting with a Dusk browser, prefix the selector with `@` to manipulate the attached element within your test: - // HTML... +```html +// HTML... - + +``` - // Test... +```php +// Test... - $browser->click('@login-button'); +$browser->click('@login-button'); +``` + +If desired, you may customize the HTML attribute that the Dusk selector utilizes via the `selectorHtmlAttribute` method. Typically, this method should be called from the `boot` method of your application's `AppServiceProvider`: + +```php +use Laravel\Dusk\Dusk; + +Dusk::selectorHtmlAttribute('data-dusk'); +``` -### Text, Values, & Attributes +### Text, Values, and Attributes -#### Retrieving & Setting Values +#### Retrieving and Setting Values Dusk provides several methods for interacting with the current value, display text, and attributes of elements on the page. For example, to get the "value" of an element that matches a given CSS or Dusk selector, use the `value` method: - // Retrieve the value... - $value = $browser->value('selector'); +```php +// Retrieve the value... +$value = $browser->value('selector'); - // Set the value... - $browser->value('selector', 'value'); +// Set the value... +$browser->value('selector', 'value'); +``` You may use the `inputValue` method to get the "value" of an input element that has a given field name: - $value = $browser->inputValue('field'); +```php +$value = $browser->inputValue('field'); +``` #### Retrieving Text The `text` method may be used to retrieve the display text of an element that matches the given selector: - $text = $browser->text('selector'); +```php +$text = $browser->text('selector'); +``` #### Retrieving Attributes Finally, the `attribute` method may be used to retrieve the value of an attribute of an element matching the given selector: - $attribute = $browser->attribute('selector', 'value'); +```php +$attribute = $browser->attribute('selector', 'value'); +``` ### Interacting With Forms @@ -499,225 +724,390 @@ Finally, the `attribute` method may be used to retrieve the value of an attribut Dusk provides a variety of methods for interacting with forms and input elements. First, let's take a look at an example of typing text into an input field: - $browser->type('email', 'taylor@laravel.com'); +```php +$browser->type('email', 'taylor@laravel.com'); +``` Note that, although the method accepts one if necessary, we are not required to pass a CSS selector into the `type` method. If a CSS selector is not provided, Dusk will search for an `input` or `textarea` field with the given `name` attribute. To append text to a field without clearing its content, you may use the `append` method: - $browser->type('tags', 'foo') - ->append('tags', ', bar, baz'); +```php +$browser->type('tags', 'foo') + ->append('tags', ', bar, baz'); +``` You may clear the value of an input using the `clear` method: - $browser->clear('email'); +```php +$browser->clear('email'); +``` You can instruct Dusk to type slowly using the `typeSlowly` method. By default, Dusk will pause for 100 milliseconds between key presses. To customize the amount of time between key presses, you may pass the appropriate number of milliseconds as the third argument to the method: - $browser->typeSlowly('mobile', '+1 (202) 555-5555'); +```php +$browser->typeSlowly('mobile', '+1 (202) 555-5555'); - $browser->typeSlowly('mobile', '+1 (202) 555-5555', 300); +$browser->typeSlowly('mobile', '+1 (202) 555-5555', 300); +``` You may use the `appendSlowly` method to append text slowly: - $browser->type('tags', 'foo') - ->appendSlowly('tags', ', bar, baz'); +```php +$browser->type('tags', 'foo') + ->appendSlowly('tags', ', bar, baz'); +``` #### Dropdowns To select a value available on a `select` element, you may use the `select` method. Like the `type` method, the `select` method does not require a full CSS selector. When passing a value to the `select` method, you should pass the underlying option value instead of the display text: - $browser->select('size', 'Large'); +```php +$browser->select('size', 'Large'); +``` You may select a random option by omitting the second argument: - $browser->select('size'); +```php +$browser->select('size'); +``` By providing an array as the second argument to the `select` method, you can instruct the method to select multiple options: - $browser->select('categories', ['Art', 'Music']); +```php +$browser->select('categories', ['Art', 'Music']); +``` #### Checkboxes To "check" a checkbox input, you may use the `check` method. Like many other input related methods, a full CSS selector is not required. If a CSS selector match can't be found, Dusk will search for a checkbox with a matching `name` attribute: - $browser->check('terms'); +```php +$browser->check('terms'); +``` The `uncheck` method may be used to "uncheck" a checkbox input: - $browser->uncheck('terms'); +```php +$browser->uncheck('terms'); +``` #### Radio Buttons To "select" a `radio` input option, you may use the `radio` method. Like many other input related methods, a full CSS selector is not required. If a CSS selector match can't be found, Dusk will search for a `radio` input with matching `name` and `value` attributes: - $browser->radio('size', 'large'); +```php +$browser->radio('size', 'large'); +``` ### Attaching Files The `attach` method may be used to attach a file to a `file` input element. Like many other input related methods, a full CSS selector is not required. If a CSS selector match can't be found, Dusk will search for a `file` input with a matching `name` attribute: - $browser->attach('photo', __DIR__.'/photos/mountains.png'); +```php +$browser->attach('photo', __DIR__.'/photos/mountains.png'); +``` -> {note} The attach function requires the `Zip` PHP extension to be installed and enabled on your server. +> [!WARNING] +> The attach function requires the `Zip` PHP extension to be installed and enabled on your server. ### Pressing Buttons -The `press` method may be used to click a button element on the page. The first argument given to the `press` method may be either the display text of the button or a CSS / Dusk selector: +The `press` method may be used to click a button element on the page. The argument given to the `press` method may be either the display text of the button or a CSS / Dusk selector: - $browser->press('Login'); +```php +$browser->press('Login'); +``` -When submitting forms, many application's disable the form's submission button after it is pressed and then re-enable the button when the form submission's HTTP request is complete. To press a button and wait for the button to be re-enabled, you may use the `pressAndWaitFor` method: +When submitting forms, many applications disable the form's submission button after it is pressed and then re-enable the button when the form submission's HTTP request is complete. To press a button and wait for the button to be re-enabled, you may use the `pressAndWaitFor` method: - // Press the button and wait a maximum of 5 seconds for it to be enabled... - $browser->pressAndWaitFor('Save'); +```php +// Press the button and wait a maximum of 5 seconds for it to be enabled... +$browser->pressAndWaitFor('Save'); - // Press the button and wait a maximum of 1 second for it to be enabled... - $browser->pressAndWaitFor('Save', 1); +// Press the button and wait a maximum of 1 second for it to be enabled... +$browser->pressAndWaitFor('Save', 1); +``` ### Clicking Links To click a link, you may use the `clickLink` method on the browser instance. The `clickLink` method will click the link that has the given display text: - $browser->clickLink($linkText); +```php +$browser->clickLink($linkText); +``` You may use the `seeLink` method to determine if a link with the given display text is visible on the page: - if ($browser->seeLink($linkText)) { - // ... - } +```php +if ($browser->seeLink($linkText)) { + // ... +} +``` -> {note} These methods interact with jQuery. If jQuery is not available on the page, Dusk will automatically inject it into the page so it is available for the test's duration. +> [!WARNING] +> These methods interact with jQuery. If jQuery is not available on the page, Dusk will automatically inject it into the page so it is available for the test's duration. -### Using The Keyboard +### Using the Keyboard The `keys` method allows you to provide more complex input sequences to a given element than normally allowed by the `type` method. For example, you may instruct Dusk to hold modifier keys while entering values. In this example, the `shift` key will be held while `taylor` is entered into the element matching the given selector. After `taylor` is typed, `swift` will be typed without any modifier keys: - $browser->keys('selector', ['{shift}', 'taylor'], 'swift'); +```php +$browser->keys('selector', ['{shift}', 'taylor'], 'swift'); +``` Another valuable use case for the `keys` method is sending a "keyboard shortcut" combination to the primary CSS selector for your application: - $browser->keys('.app', ['{command}', 'j']); +```php +$browser->keys('.app', ['{command}', 'j']); +``` + +> [!NOTE] +> All modifier keys such as `{command}` are wrapped in `{}` characters, and match the constants defined in the `Facebook\WebDriver\WebDriverKeys` class, which can be [found on GitHub](https://github.com/php-webdriver/php-webdriver/blob/master/lib/WebDriverKeys.php). + + +#### Fluent Keyboard Interactions + +Dusk also provides a `withKeyboard` method, allowing you to fluently perform complex keyboard interactions via the `Laravel\Dusk\Keyboard` class. The `Keyboard` class provides `press`, `release`, `type`, and `pause` methods: + +```php +use Laravel\Dusk\Keyboard; + +$browser->withKeyboard(function (Keyboard $keyboard) { + $keyboard->press('c') + ->pause(1000) + ->release('c') + ->type(['c', 'e', 'o']); +}); +``` + + +#### Keyboard Macros + +If you would like to define custom keyboard interactions that you can easily re-use throughout your test suite, you may use the `macro` method provided by the `Keyboard` class. Typically, you should call this method from a [service provider's](/docs/{{version}}/providers) `boot` method: + +```php +type([ + OperatingSystem::onMac() ? WebDriverKeys::META : WebDriverKeys::CONTROL, 'c', + ]); + + return $this; + }); + + Keyboard::macro('paste', function (string $element = null) { + $this->type([ + OperatingSystem::onMac() ? WebDriverKeys::META : WebDriverKeys::CONTROL, 'v', + ]); + + return $this; + }); + } +} +``` + +The `macro` function accepts a name as its first argument and a closure as its second. The macro's closure will be executed when calling the macro as a method on a `Keyboard` instance: -> {tip} All modifier keys such as `{command}` are wrapped in `{}` characters, and match the constants defined in the `Facebook\WebDriver\WebDriverKeys` class, which can be [found on GitHub](https://github.com/php-webdriver/php-webdriver/blob/master/lib/WebDriverKeys.php). +```php +$browser->click('@textarea') + ->withKeyboard(fn (Keyboard $keyboard) => $keyboard->copy()) + ->click('@another-textarea') + ->withKeyboard(fn (Keyboard $keyboard) => $keyboard->paste()); +``` -### Using The Mouse +### Using the Mouse -#### Clicking On Elements +#### Clicking on Elements The `click` method may be used to click on an element matching the given CSS or Dusk selector: - $browser->click('.selector'); +```php +$browser->click('.selector'); +``` The `clickAtXPath` method may be used to click on an element matching the given XPath expression: - $browser->clickAtXPath('//div[@class = "selector"]'); +```php +$browser->clickAtXPath('//div[@class = "selector"]'); +``` The `clickAtPoint` method may be used to click on the topmost element at a given pair of coordinates relative to the viewable area of the browser: - $browser->clickAtPoint($x = 0, $y = 0); +```php +$browser->clickAtPoint($x = 0, $y = 0); +``` The `doubleClick` method may be used to simulate the double click of a mouse: - $browser->doubleClick(); +```php +$browser->doubleClick(); + +$browser->doubleClick('.selector'); +``` The `rightClick` method may be used to simulate the right click of a mouse: - $browser->rightClick(); +```php +$browser->rightClick(); - $browser->rightClick('.selector'); +$browser->rightClick('.selector'); +``` The `clickAndHold` method may be used to simulate a mouse button being clicked and held down. A subsequent call to the `releaseMouse` method will undo this behavior and release the mouse button: - $browser->clickAndHold() - ->pause(1000) - ->releaseMouse(); +```php +$browser->clickAndHold('.selector'); + +$browser->clickAndHold() + ->pause(1000) + ->releaseMouse(); +``` + +The `controlClick` method may be used to simulate the `ctrl+click` event within the browser: + +```php +$browser->controlClick(); + +$browser->controlClick('.selector'); +``` #### Mouseover The `mouseover` method may be used when you need to move the mouse over an element matching the given CSS or Dusk selector: - $browser->mouseover('.selector'); +```php +$browser->mouseover('.selector'); +``` -#### Drag & Drop +#### Drag and Drop The `drag` method may be used to drag an element matching the given selector to another element: - $browser->drag('.from-selector', '.to-selector'); +```php +$browser->drag('.from-selector', '.to-selector'); +``` Or, you may drag an element in a single direction: - $browser->dragLeft('.selector', $pixels = 10); - $browser->dragRight('.selector', $pixels = 10); - $browser->dragUp('.selector', $pixels = 10); - $browser->dragDown('.selector', $pixels = 10); +```php +$browser->dragLeft('.selector', $pixels = 10); +$browser->dragRight('.selector', $pixels = 10); +$browser->dragUp('.selector', $pixels = 10); +$browser->dragDown('.selector', $pixels = 10); +``` Finally, you may drag an element by a given offset: - $browser->dragOffset('.selector', $x = 10, $y = 10); +```php +$browser->dragOffset('.selector', $x = 10, $y = 10); +``` ### JavaScript Dialogs Dusk provides various methods to interact with JavaScript Dialogs. For example, you may use the `waitForDialog` method to wait for a JavaScript dialog to appear. This method accepts an optional argument indicating how many seconds to wait for the dialog to appear: - $browser->waitForDialog($seconds = null); +```php +$browser->waitForDialog($seconds = null); +``` The `assertDialogOpened` method may be used to assert that a dialog has been displayed and contains the given message: - $browser->assertDialogOpened('Dialog message'); +```php +$browser->assertDialogOpened('Dialog message'); +``` If the JavaScript dialog contains a prompt, you may use the `typeInDialog` method to type a value into the prompt: - $browser->typeInDialog('Hello World'); +```php +$browser->typeInDialog('Hello World'); +``` To close an open JavaScript dialog by clicking the "OK" button, you may invoke the `acceptDialog` method: - $browser->acceptDialog(); +```php +$browser->acceptDialog(); +``` To close an open JavaScript dialog by clicking the "Cancel" button, you may invoke the `dismissDialog` method: - $browser->dismissDialog(); +```php +$browser->dismissDialog(); +``` + + +### Interacting With Inline Frames + +If you need to interact with elements within an iframe, you may use the `withinFrame` method. All element interactions that take place within the closure provided to the `withinFrame` method will be scoped to the context of the specified iframe: + +```php +$browser->withinFrame('#credit-card-details', function ($browser) { + $browser->type('input[name="cardnumber"]', '4242424242424242') + ->type('input[name="exp-date"]', '1224') + ->type('input[name="cvc"]', '123') + ->press('Pay'); +}); +``` ### Scoping Selectors Sometimes you may wish to perform several operations while scoping all of the operations within a given selector. For example, you may wish to assert that some text exists only within a table and then click a button within that table. You may use the `with` method to accomplish this. All operations performed within the closure given to the `with` method will be scoped to the original selector: - $browser->with('.table', function ($table) { - $table->assertSee('Hello World') - ->clickLink('Delete'); - }); +```php +$browser->with('.table', function (Browser $table) { + $table->assertSee('Hello World') + ->clickLink('Delete'); +}); +``` You may occasionally need to execute assertions outside of the current scope. You may use the `elsewhere` and `elsewhereWhenAvailable` methods to accomplish this: - $browser->with('.table', function ($table) { - // Current scope is `body .table`... +```php +$browser->with('.table', function (Browser $table) { + // Current scope is `body .table`... - $browser->elsewhere('.page-title', function ($title) { - // Current scope is `body .page-title`... - $title->assertSee('Hello World'); - }); + $browser->elsewhere('.page-title', function (Browser $title) { + // Current scope is `body .page-title`... + $title->assertSee('Hello World'); + }); - $browser->elsewhereWhenAvailable('.page-title', function ($title) { - // Current scope is `body .page-title`... - $title->assertSee('Hello World'); - }); - }); + $browser->elsewhereWhenAvailable('.page-title', function (Browser $title) { + // Current scope is `body .page-title`... + $title->assertSee('Hello World'); + }); +}); +``` -### Waiting For Elements +### Waiting for Elements When testing applications that use JavaScript extensively, it often becomes necessary to "wait" for certain elements or data to be available before proceeding with a test. Dusk makes this a cinch. Using a variety of methods, you may wait for elements to become visible on the page or even wait until a given JavaScript expression evaluates to `true`. @@ -726,159 +1116,254 @@ When testing applications that use JavaScript extensively, it often becomes nece If you just need to pause the test for a given number of milliseconds, use the `pause` method: - $browser->pause(1000); +```php +$browser->pause(1000); +``` + +If you need to pause the test only if a given condition is `true`, use the `pauseIf` method: + +```php +$browser->pauseIf(App::environment('production'), 1000); +``` + +Likewise, if you need to pause the test unless a given condition is `true`, you may use the `pauseUnless` method: + +```php +$browser->pauseUnless(App::environment('testing'), 1000); +``` -#### Waiting For Selectors +#### Waiting for Selectors The `waitFor` method may be used to pause the execution of the test until the element matching the given CSS or Dusk selector is displayed on the page. By default, this will pause the test for a maximum of five seconds before throwing an exception. If necessary, you may pass a custom timeout threshold as the second argument to the method: - // Wait a maximum of five seconds for the selector... - $browser->waitFor('.selector'); +```php +// Wait a maximum of five seconds for the selector... +$browser->waitFor('.selector'); - // Wait a maximum of one second for the selector... - $browser->waitFor('.selector', 1); +// Wait a maximum of one second for the selector... +$browser->waitFor('.selector', 1); +``` You may also wait until the element matching the given selector contains the given text: - // Wait a maximum of five seconds for the selector to contain the given text... - $browser->waitForTextIn('.selector', 'Hello World'); +```php +// Wait a maximum of five seconds for the selector to contain the given text... +$browser->waitForTextIn('.selector', 'Hello World'); - // Wait a maximum of one second for the selector to contain the given text... - $browser->waitForTextIn('.selector', 'Hello World', 1); +// Wait a maximum of one second for the selector to contain the given text... +$browser->waitForTextIn('.selector', 'Hello World', 1); +``` You may also wait until the element matching the given selector is missing from the page: - // Wait a maximum of five seconds until the selector is missing... - $browser->waitUntilMissing('.selector'); +```php +// Wait a maximum of five seconds until the selector is missing... +$browser->waitUntilMissing('.selector'); - // Wait a maximum of one second until the selector is missing... - $browser->waitUntilMissing('.selector', 1); +// Wait a maximum of one second until the selector is missing... +$browser->waitUntilMissing('.selector', 1); +``` Or, you may wait until the element matching the given selector is enabled or disabled: - // Wait a maximum of five seconds until the selector is enabled... - $browser->waitUntilEnabled('.selector'); +```php +// Wait a maximum of five seconds until the selector is enabled... +$browser->waitUntilEnabled('.selector'); - // Wait a maximum of one second until the selector is enabled... - $browser->waitUntilEnabled('.selector', 1); +// Wait a maximum of one second until the selector is enabled... +$browser->waitUntilEnabled('.selector', 1); - // Wait a maximum of five seconds until the selector is disabled... - $browser->waitUntilDisabled('.selector'); +// Wait a maximum of five seconds until the selector is disabled... +$browser->waitUntilDisabled('.selector'); - // Wait a maximum of one second until the selector is disabled... - $browser->waitUntilDisabled('.selector', 1); +// Wait a maximum of one second until the selector is disabled... +$browser->waitUntilDisabled('.selector', 1); +``` #### Scoping Selectors When Available Occasionally, you may wish to wait for an element to appear that matches a given selector and then interact with the element. For example, you may wish to wait until a modal window is available and then press the "OK" button within the modal. The `whenAvailable` method may be used to accomplish this. All element operations performed within the given closure will be scoped to the original selector: - $browser->whenAvailable('.modal', function ($modal) { - $modal->assertSee('Hello World') - ->press('OK'); - }); +```php +$browser->whenAvailable('.modal', function (Browser $modal) { + $modal->assertSee('Hello World') + ->press('OK'); +}); +``` -#### Waiting For Text +#### Waiting for Text The `waitForText` method may be used to wait until the given text is displayed on the page: - // Wait a maximum of five seconds for the text... - $browser->waitForText('Hello World'); +```php +// Wait a maximum of five seconds for the text... +$browser->waitForText('Hello World'); - // Wait a maximum of one second for the text... - $browser->waitForText('Hello World', 1); +// Wait a maximum of one second for the text... +$browser->waitForText('Hello World', 1); +``` You may use the `waitUntilMissingText` method to wait until the displayed text has been removed from the page: - // Wait a maximum of five seconds for the text to be removed... - $browser->waitUntilMissingText('Hello World'); +```php +// Wait a maximum of five seconds for the text to be removed... +$browser->waitUntilMissingText('Hello World'); - // Wait a maximum of one second for the text to be removed... - $browser->waitUntilMissingText('Hello World', 1); +// Wait a maximum of one second for the text to be removed... +$browser->waitUntilMissingText('Hello World', 1); +``` -#### Waiting For Links +#### Waiting for Links The `waitForLink` method may be used to wait until the given link text is displayed on the page: - // Wait a maximum of five seconds for the link... - $browser->waitForLink('Create'); +```php +// Wait a maximum of five seconds for the link... +$browser->waitForLink('Create'); + +// Wait a maximum of one second for the link... +$browser->waitForLink('Create', 1); +``` + + +#### Waiting for Inputs - // Wait a maximum of one second for the link... - $browser->waitForLink('Create', 1); +The `waitForInput` method may be used to wait until the given input field is visible on the page: + +```php +// Wait a maximum of five seconds for the input... +$browser->waitForInput($field); + +// Wait a maximum of one second for the input... +$browser->waitForInput($field, 1); +``` -#### Waiting On The Page Location +#### Waiting on the Page Location When making a path assertion such as `$browser->assertPathIs('/home')`, the assertion can fail if `window.location.pathname` is being updated asynchronously. You may use the `waitForLocation` method to wait for the location to be a given value: - $browser->waitForLocation('/secret'); +```php +$browser->waitForLocation('/secret'); +``` The `waitForLocation` method can also be used to wait for the current window location to be a fully qualified URL: - $browser->waitForLocation('https://example.com/path'); +```php +$browser->waitForLocation('https://example.com/path'); +``` You may also wait for a [named route's](/docs/{{version}}/routing#named-routes) location: - $browser->waitForRoute($routeName, $parameters); +```php +$browser->waitForRoute($routeName, $parameters); +``` #### Waiting for Page Reloads If you need to wait for a page to reload after performing an action, use the `waitForReload` method: - use Laravel\Dusk\Browser; +```php +use Laravel\Dusk\Browser; - $browser->waitForReload(function (Browser $browser) { - $browser->press('Submit'); - }) - ->assertSee('Success!'); +$browser->waitForReload(function (Browser $browser) { + $browser->press('Submit'); +}) +->assertSee('Success!'); +``` Since the need to wait for the page to reload typically occurs after clicking a button, you may use the `clickAndWaitForReload` method for convenience: - $browser->clickAndWaitForReload('.selector') - ->assertSee('something'); +```php +$browser->clickAndWaitForReload('.selector') + ->assertSee('something'); +``` -#### Waiting On JavaScript Expressions +#### Waiting on JavaScript Expressions Sometimes you may wish to pause the execution of a test until a given JavaScript expression evaluates to `true`. You may easily accomplish this using the `waitUntil` method. When passing an expression to this method, you do not need to include the `return` keyword or an ending semi-colon: - // Wait a maximum of five seconds for the expression to be true... - $browser->waitUntil('App.data.servers.length > 0'); +```php +// Wait a maximum of five seconds for the expression to be true... +$browser->waitUntil('App.data.servers.length > 0'); - // Wait a maximum of one second for the expression to be true... - $browser->waitUntil('App.data.servers.length > 0', 1); +// Wait a maximum of one second for the expression to be true... +$browser->waitUntil('App.data.servers.length > 0', 1); +``` -#### Waiting On Vue Expressions +#### Waiting on Vue Expressions The `waitUntilVue` and `waitUntilVueIsNot` methods may be used to wait until a [Vue component](https://vuejs.org) attribute has a given value: - // Wait until the component attribute contains the given value... - $browser->waitUntilVue('user.name', 'Taylor', '@user'); +```php +// Wait until the component attribute contains the given value... +$browser->waitUntilVue('user.name', 'Taylor', '@user'); + +// Wait until the component attribute doesn't contain the given value... +$browser->waitUntilVueIsNot('user.name', null, '@user'); +``` + + +#### Waiting for JavaScript Events + +The `waitForEvent` method can be used to pause the execution of a test until a JavaScript event occurs: + +```php +$browser->waitForEvent('load'); +``` + +The event listener is attached to the current scope, which is the `body` element by default. When using a scoped selector, the event listener will be attached to the matching element: + +```php +$browser->with('iframe', function (Browser $iframe) { + // Wait for the iframe's load event... + $iframe->waitForEvent('load'); +}); +``` - // Wait until the component attribute doesn't contain the given value... - $browser->waitUntilVueIsNot('user.name', null, '@user'); +You may also provide a selector as the second argument to the `waitForEvent` method to attach the event listener to a specific element: + +```php +$browser->waitForEvent('load', '.selector'); +``` + +You may also wait for events on the `document` and `window` objects: + +```php +// Wait until the document is scrolled... +$browser->waitForEvent('scroll', 'document'); + +// Wait a maximum of five seconds until the window is resized... +$browser->waitForEvent('resize', 'window', 5); +``` -#### Waiting With A Callback +#### Waiting With a Callback Many of the "wait" methods in Dusk rely on the underlying `waitUsing` method. You may use this method directly to wait for a given closure to return `true`. The `waitUsing` method accepts the maximum number of seconds to wait, the interval at which the closure should be evaluated, the closure, and an optional failure message: - $browser->waitUsing(10, 1, function () use ($something) { - return $something->isReady(); - }, "Something wasn't ready in time."); +```php +$browser->waitUsing(10, 1, function () use ($something) { + return $something->isReady(); +}, "Something wasn't ready in time."); +``` -### Scrolling An Element Into View +### Scrolling an Element Into View Sometimes you may not be able to click on an element because it is outside of the viewable area of the browser. The `scrollIntoView` method will scroll the browser window until the element at the given selector is within the view: - $browser->scrollIntoView('.selector') - ->click('.selector'); +```php +$browser->scrollIntoView('.selector') + ->click('.selector'); +``` ## Available Assertions @@ -887,12 +1372,14 @@ Dusk provides a variety of assertions that you may make against your application @@ -908,6 +1395,8 @@ Dusk provides a variety of assertions that you may make against your application [assertPortIs](#assert-port-is) [assertPortIsNot](#assert-port-is-not) [assertPathBeginsWith](#assert-path-begins-with) +[assertPathEndsWith](#assert-path-ends-with) +[assertPathContains](#assert-path-contains) [assertPathIs](#assert-path-is) [assertPathIsNot](#assert-path-is-not) [assertRouteIs](#assert-route-is) @@ -928,6 +1417,7 @@ Dusk provides a variety of assertions that you may make against your application [assertDontSeeIn](#assert-dont-see-in) [assertSeeAnythingIn](#assert-see-anything-in) [assertSeeNothingIn](#assert-see-nothing-in) +[assertCount](#assert-count) [assertScript](#assert-script) [assertSourceHas](#assert-source-has) [assertSourceMissing](#assert-source-missing) @@ -937,6 +1427,7 @@ Dusk provides a variety of assertions that you may make against your application [assertInputValueIsNot](#assert-input-value-is-not) [assertChecked](#assert-checked) [assertNotChecked](#assert-not-checked) +[assertIndeterminate](#assert-indeterminate) [assertRadioSelected](#assert-radio-selected) [assertRadioNotSelected](#assert-radio-not-selected) [assertSelected](#assert-selected) @@ -948,7 +1439,9 @@ Dusk provides a variety of assertions that you may make against your application [assertValue](#assert-value) [assertValueIsNot](#assert-value-is-not) [assertAttribute](#assert-attribute) +[assertAttributeMissing](#assert-attribute-missing) [assertAttributeContains](#assert-attribute-contains) +[assertAttributeDoesntContain](#assert-attribute-doesnt-contain) [assertAriaAttribute](#assert-aria-attribute) [assertDataAttribute](#assert-data-attribute) [assertVisible](#assert-visible) @@ -970,7 +1463,7 @@ Dusk provides a variety of assertions that you may make against your application [assertVue](#assert-vue) [assertVueIsNot](#assert-vue-is-not) [assertVueContains](#assert-vue-contains) -[assertVueDoesNotContain](#assert-vue-does-not-contain) +[assertVueDoesntContain](#assert-vue-doesnt-contain)
@@ -979,496 +1472,694 @@ Dusk provides a variety of assertions that you may make against your application Assert that the page title matches the given text: - $browser->assertTitle($title); +```php +$browser->assertTitle($title); +``` #### assertTitleContains Assert that the page title contains the given text: - $browser->assertTitleContains($title); +```php +$browser->assertTitleContains($title); +``` #### assertUrlIs Assert that the current URL (without the query string) matches the given string: - $browser->assertUrlIs($url); +```php +$browser->assertUrlIs($url); +``` #### assertSchemeIs Assert that the current URL scheme matches the given scheme: - $browser->assertSchemeIs($scheme); +```php +$browser->assertSchemeIs($scheme); +``` #### assertSchemeIsNot Assert that the current URL scheme does not match the given scheme: - $browser->assertSchemeIsNot($scheme); +```php +$browser->assertSchemeIsNot($scheme); +``` #### assertHostIs Assert that the current URL host matches the given host: - $browser->assertHostIs($host); +```php +$browser->assertHostIs($host); +``` #### assertHostIsNot Assert that the current URL host does not match the given host: - $browser->assertHostIsNot($host); +```php +$browser->assertHostIsNot($host); +``` #### assertPortIs Assert that the current URL port matches the given port: - $browser->assertPortIs($port); +```php +$browser->assertPortIs($port); +``` #### assertPortIsNot Assert that the current URL port does not match the given port: - $browser->assertPortIsNot($port); +```php +$browser->assertPortIsNot($port); +``` #### assertPathBeginsWith Assert that the current URL path begins with the given path: - $browser->assertPathBeginsWith('/home'); +```php +$browser->assertPathBeginsWith('/home'); +``` + + +#### assertPathEndsWith + +Assert that the current URL path ends with the given path: + +```php +$browser->assertPathEndsWith('/home'); +``` + + +#### assertPathContains + +Assert that the current URL path contains the given path: + +```php +$browser->assertPathContains('/home'); +``` #### assertPathIs Assert that the current path matches the given path: - $browser->assertPathIs('/home'); +```php +$browser->assertPathIs('/home'); +``` #### assertPathIsNot Assert that the current path does not match the given path: - $browser->assertPathIsNot('/home'); +```php +$browser->assertPathIsNot('/home'); +``` #### assertRouteIs Assert that the current URL matches the given [named route's](/docs/{{version}}/routing#named-routes) URL: - $browser->assertRouteIs($name, $parameters); +```php +$browser->assertRouteIs($name, $parameters); +``` #### assertQueryStringHas Assert that the given query string parameter is present: - $browser->assertQueryStringHas($name); +```php +$browser->assertQueryStringHas($name); +``` Assert that the given query string parameter is present and has a given value: - $browser->assertQueryStringHas($name, $value); +```php +$browser->assertQueryStringHas($name, $value); +``` #### assertQueryStringMissing Assert that the given query string parameter is missing: - $browser->assertQueryStringMissing($name); +```php +$browser->assertQueryStringMissing($name); +``` #### assertFragmentIs Assert that the URL's current hash fragment matches the given fragment: - $browser->assertFragmentIs('anchor'); +```php +$browser->assertFragmentIs('anchor'); +``` #### assertFragmentBeginsWith Assert that the URL's current hash fragment begins with the given fragment: - $browser->assertFragmentBeginsWith('anchor'); +```php +$browser->assertFragmentBeginsWith('anchor'); +``` #### assertFragmentIsNot Assert that the URL's current hash fragment does not match the given fragment: - $browser->assertFragmentIsNot('anchor'); +```php +$browser->assertFragmentIsNot('anchor'); +``` #### assertHasCookie Assert that the given encrypted cookie is present: - $browser->assertHasCookie($name); +```php +$browser->assertHasCookie($name); +``` #### assertHasPlainCookie Assert that the given unencrypted cookie is present: - $browser->assertHasPlainCookie($name); +```php +$browser->assertHasPlainCookie($name); +``` #### assertCookieMissing Assert that the given encrypted cookie is not present: - $browser->assertCookieMissing($name); +```php +$browser->assertCookieMissing($name); +``` #### assertPlainCookieMissing Assert that the given unencrypted cookie is not present: - $browser->assertPlainCookieMissing($name); +```php +$browser->assertPlainCookieMissing($name); +``` #### assertCookieValue Assert that an encrypted cookie has a given value: - $browser->assertCookieValue($name, $value); +```php +$browser->assertCookieValue($name, $value); +``` #### assertPlainCookieValue Assert that an unencrypted cookie has a given value: - $browser->assertPlainCookieValue($name, $value); +```php +$browser->assertPlainCookieValue($name, $value); +``` #### assertSee Assert that the given text is present on the page: - $browser->assertSee($text); +```php +$browser->assertSee($text); +``` #### assertDontSee Assert that the given text is not present on the page: - $browser->assertDontSee($text); +```php +$browser->assertDontSee($text); +``` #### assertSeeIn Assert that the given text is present within the selector: - $browser->assertSeeIn($selector, $text); +```php +$browser->assertSeeIn($selector, $text); +``` #### assertDontSeeIn Assert that the given text is not present within the selector: - $browser->assertDontSeeIn($selector, $text); +```php +$browser->assertDontSeeIn($selector, $text); +``` #### assertSeeAnythingIn Assert that any text is present within the selector: - $browser->assertSeeAnythingIn($selector); +```php +$browser->assertSeeAnythingIn($selector); +``` #### assertSeeNothingIn Assert that no text is present within the selector: - $browser->assertSeeNothingIn($selector); +```php +$browser->assertSeeNothingIn($selector); +``` + + +#### assertCount + +Assert that elements matching the given selector appear the specified number of times: + +```php +$browser->assertCount($selector, $count); +``` #### assertScript Assert that the given JavaScript expression evaluates to the given value: - $browser->assertScript('window.isLoaded') - ->assertScript('document.readyState', 'complete'); +```php +$browser->assertScript('window.isLoaded') + ->assertScript('document.readyState', 'complete'); +``` #### assertSourceHas Assert that the given source code is present on the page: - $browser->assertSourceHas($code); +```php +$browser->assertSourceHas($code); +``` #### assertSourceMissing Assert that the given source code is not present on the page: - $browser->assertSourceMissing($code); +```php +$browser->assertSourceMissing($code); +``` #### assertSeeLink Assert that the given link is present on the page: - $browser->assertSeeLink($linkText); +```php +$browser->assertSeeLink($linkText); +``` #### assertDontSeeLink Assert that the given link is not present on the page: - $browser->assertDontSeeLink($linkText); +```php +$browser->assertDontSeeLink($linkText); +``` #### assertInputValue Assert that the given input field has the given value: - $browser->assertInputValue($field, $value); +```php +$browser->assertInputValue($field, $value); +``` #### assertInputValueIsNot Assert that the given input field does not have the given value: - $browser->assertInputValueIsNot($field, $value); +```php +$browser->assertInputValueIsNot($field, $value); +``` #### assertChecked Assert that the given checkbox is checked: - $browser->assertChecked($field); +```php +$browser->assertChecked($field); +``` #### assertNotChecked Assert that the given checkbox is not checked: - $browser->assertNotChecked($field); +```php +$browser->assertNotChecked($field); +``` + + +#### assertIndeterminate + +Assert that the given checkbox is in an indeterminate state: + +```php +$browser->assertIndeterminate($field); +``` #### assertRadioSelected Assert that the given radio field is selected: - $browser->assertRadioSelected($field, $value); +```php +$browser->assertRadioSelected($field, $value); +``` #### assertRadioNotSelected Assert that the given radio field is not selected: - $browser->assertRadioNotSelected($field, $value); +```php +$browser->assertRadioNotSelected($field, $value); +``` #### assertSelected Assert that the given dropdown has the given value selected: - $browser->assertSelected($field, $value); +```php +$browser->assertSelected($field, $value); +``` #### assertNotSelected Assert that the given dropdown does not have the given value selected: - $browser->assertNotSelected($field, $value); +```php +$browser->assertNotSelected($field, $value); +``` #### assertSelectHasOptions Assert that the given array of values are available to be selected: - $browser->assertSelectHasOptions($field, $values); +```php +$browser->assertSelectHasOptions($field, $values); +``` #### assertSelectMissingOptions Assert that the given array of values are not available to be selected: - $browser->assertSelectMissingOptions($field, $values); +```php +$browser->assertSelectMissingOptions($field, $values); +``` #### assertSelectHasOption Assert that the given value is available to be selected on the given field: - $browser->assertSelectHasOption($field, $value); +```php +$browser->assertSelectHasOption($field, $value); +``` #### assertSelectMissingOption Assert that the given value is not available to be selected: - $browser->assertSelectMissingOption($field, $value); +```php +$browser->assertSelectMissingOption($field, $value); +``` #### assertValue Assert that the element matching the given selector has the given value: - $browser->assertValue($selector, $value); +```php +$browser->assertValue($selector, $value); +``` #### assertValueIsNot Assert that the element matching the given selector does not have the given value: - $browser->assertValueIsNot($selector, $value); +```php +$browser->assertValueIsNot($selector, $value); +``` #### assertAttribute Assert that the element matching the given selector has the given value in the provided attribute: - $browser->assertAttribute($selector, $attribute, $value); +```php +$browser->assertAttribute($selector, $attribute, $value); +``` + + +#### assertAttributeMissing + +Assert that the element matching the given selector is missing the provided attribute: + +```php +$browser->assertAttributeMissing($selector, $attribute); +``` #### assertAttributeContains Assert that the element matching the given selector contains the given value in the provided attribute: - $browser->assertAttributeContains($selector, $attribute, $value); +```php +$browser->assertAttributeContains($selector, $attribute, $value); +``` + + +#### assertAttributeDoesntContain + +Assert that the element matching the given selector does not contain the given value in the provided attribute: + +```php +$browser->assertAttributeDoesntContain($selector, $attribute, $value); +``` #### assertAriaAttribute Assert that the element matching the given selector has the given value in the provided aria attribute: - $browser->assertAriaAttribute($selector, $attribute, $value); +```php +$browser->assertAriaAttribute($selector, $attribute, $value); +``` For example, given the markup ``, you may assert against the `aria-label` attribute like so: - $browser->assertAriaAttribute('button', 'label', 'Add') +```php +$browser->assertAriaAttribute('button', 'label', 'Add') +``` #### assertDataAttribute Assert that the element matching the given selector has the given value in the provided data attribute: - $browser->assertDataAttribute($selector, $attribute, $value); +```php +$browser->assertDataAttribute($selector, $attribute, $value); +``` For example, given the markup ``, you may assert against the `data-label` attribute like so: - $browser->assertDataAttribute('#row-1', 'content', 'attendees') +```php +$browser->assertDataAttribute('#row-1', 'content', 'attendees') +``` #### assertVisible Assert that the element matching the given selector is visible: - $browser->assertVisible($selector); +```php +$browser->assertVisible($selector); +``` #### assertPresent Assert that the element matching the given selector is present in the source: - $browser->assertPresent($selector); +```php +$browser->assertPresent($selector); +``` #### assertNotPresent Assert that the element matching the given selector is not present in the source: - $browser->assertNotPresent($selector); +```php +$browser->assertNotPresent($selector); +``` #### assertMissing Assert that the element matching the given selector is not visible: - $browser->assertMissing($selector); +```php +$browser->assertMissing($selector); +``` #### assertInputPresent Assert that an input with the given name is present: - $browser->assertInputPresent($name); +```php +$browser->assertInputPresent($name); +``` #### assertInputMissing Assert that an input with the given name is not present in the source: - $browser->assertInputMissing($name); +```php +$browser->assertInputMissing($name); +``` #### assertDialogOpened Assert that a JavaScript dialog with the given message has been opened: - $browser->assertDialogOpened($message); +```php +$browser->assertDialogOpened($message); +``` #### assertEnabled Assert that the given field is enabled: - $browser->assertEnabled($field); +```php +$browser->assertEnabled($field); +``` #### assertDisabled Assert that the given field is disabled: - $browser->assertDisabled($field); +```php +$browser->assertDisabled($field); +``` #### assertButtonEnabled Assert that the given button is enabled: - $browser->assertButtonEnabled($button); +```php +$browser->assertButtonEnabled($button); +``` #### assertButtonDisabled Assert that the given button is disabled: - $browser->assertButtonDisabled($button); +```php +$browser->assertButtonDisabled($button); +``` #### assertFocused Assert that the given field is focused: - $browser->assertFocused($field); +```php +$browser->assertFocused($field); +``` #### assertNotFocused Assert that the given field is not focused: - $browser->assertNotFocused($field); +```php +$browser->assertNotFocused($field); +``` #### assertAuthenticated Assert that the user is authenticated: - $browser->assertAuthenticated(); +```php +$browser->assertAuthenticated(); +``` #### assertGuest Assert that the user is not authenticated: - $browser->assertGuest(); +```php +$browser->assertGuest(); +``` #### assertAuthenticatedAs Assert that the user is authenticated as the given user: - $browser->assertAuthenticatedAs($user); +```php +$browser->assertAuthenticatedAs($user); +``` #### assertVue @@ -1495,39 +2186,54 @@ Dusk even allows you to make assertions on the state of [Vue component](https:// You may assert on the state of the Vue component like so: - /** - * A basic Vue test example. - * - * @return void - */ - public function testVue() - { - $this->browse(function (Browser $browser) { - $browser->visit('/') - ->assertVue('user.name', 'Taylor', '@profile-component'); - }); - } +```php tab=Pest +test('vue', function () { + $this->browse(function (Browser $browser) { + $browser->visit('/') + ->assertVue('user.name', 'Taylor', '@profile-component'); + }); +}); +``` + +```php tab=PHPUnit +/** + * A basic Vue test example. + */ +public function test_vue(): void +{ + $this->browse(function (Browser $browser) { + $browser->visit('/') + ->assertVue('user.name', 'Taylor', '@profile-component'); + }); +} +``` #### assertVueIsNot Assert that a given Vue component data property does not match the given value: - $browser->assertVueIsNot($property, $value, $componentSelector = null); +```php +$browser->assertVueIsNot($property, $value, $componentSelector = null); +``` #### assertVueContains Assert that a given Vue component data property is an array and contains the given value: - $browser->assertVueContains($property, $value, $componentSelector = null); +```php +$browser->assertVueContains($property, $value, $componentSelector = null); +``` - -#### assertVueDoesNotContain + +#### assertVueDoesntContain Assert that a given Vue component data property is an array and does not contain the given value: - $browser->assertVueDoesNotContain($property, $value, $componentSelector = null); +```php +$browser->assertVueDoesntContain($property, $value, $componentSelector = null); +``` ## Pages @@ -1539,7 +2245,9 @@ Sometimes, tests require several complicated actions to be performed in sequence To generate a page object, execute the `dusk:page` Artisan command. All page objects will be placed in your application's `tests/Browser/Pages` directory: - php artisan dusk:page Login +```shell +php artisan dusk:page Login +``` ### Configuring Pages @@ -1551,265 +2259,302 @@ By default, pages have three methods: `url`, `assert`, and `elements`. We will d The `url` method should return the path of the URL that represents the page. Dusk will use this URL when navigating to the page in the browser: - /** - * Get the URL for the page. - * - * @return string - */ - public function url() - { - return '/login'; - } +```php +/** + * Get the URL for the page. + */ +public function url(): string +{ + return '/login'; +} +``` #### The `assert` Method The `assert` method may make any assertions necessary to verify that the browser is actually on the given page. It is not actually necessary to place anything within this method; however, you are free to make these assertions if you wish. These assertions will be run automatically when navigating to the page: - /** - * Assert that the browser is on the page. - * - * @return void - */ - public function assert(Browser $browser) - { - $browser->assertPathIs($this->url()); - } +```php +/** + * Assert that the browser is on the page. + */ +public function assert(Browser $browser): void +{ + $browser->assertPathIs($this->url()); +} +``` -### Navigating To Pages +### Navigating to Pages Once a page has been defined, you may navigate to it using the `visit` method: - use Tests\Browser\Pages\Login; +```php +use Tests\Browser\Pages\Login; - $browser->visit(new Login); +$browser->visit(new Login); +``` Sometimes you may already be on a given page and need to "load" the page's selectors and methods into the current test context. This is common when pressing a button and being redirected to a given page without explicitly navigating to it. In this situation, you may use the `on` method to load the page: - use Tests\Browser\Pages\CreatePlaylist; +```php +use Tests\Browser\Pages\CreatePlaylist; - $browser->visit('/dashboard') - ->clickLink('Create Playlist') - ->on(new CreatePlaylist) - ->assertSee('@create'); +$browser->visit('/dashboard') + ->clickLink('Create Playlist') + ->on(new CreatePlaylist) + ->assertSee('@create'); +``` ### Shorthand Selectors The `elements` method within page classes allows you to define quick, easy-to-remember shortcuts for any CSS selector on your page. For example, let's define a shortcut for the "email" input field of the application's login page: - /** - * Get the element shortcuts for the page. - * - * @return array - */ - public function elements() - { - return [ - '@email' => 'input[name=email]', - ]; - } +```php +/** + * Get the element shortcuts for the page. + * + * @return array + */ +public function elements(): array +{ + return [ + '@email' => 'input[name=email]', + ]; +} +``` Once the shortcut has been defined, you may use the shorthand selector anywhere you would typically use a full CSS selector: - $browser->type('@email', 'taylor@laravel.com'); +```php +$browser->type('@email', 'taylor@laravel.com'); +``` #### Global Shorthand Selectors After installing Dusk, a base `Page` class will be placed in your `tests/Browser/Pages` directory. This class contains a `siteElements` method which may be used to define global shorthand selectors that should be available on every page throughout your application: - /** - * Get the global element shortcuts for the site. - * - * @return array - */ - public static function siteElements() - { - return [ - '@element' => '#selector', - ]; - } +```php +/** + * Get the global element shortcuts for the site. + * + * @return array + */ +public static function siteElements(): array +{ + return [ + '@element' => '#selector', + ]; +} +``` ### Page Methods In addition to the default methods defined on pages, you may define additional methods which may be used throughout your tests. For example, let's imagine we are building a music management application. A common action for one page of the application might be to create a playlist. Instead of re-writing the logic to create a playlist in each test, you may define a `createPlaylist` method on a page class: - type('name', $name) - ->check('share') - ->press('Create Playlist'); - } + $browser->type('name', $name) + ->check('share') + ->press('Create Playlist'); } +} +``` Once the method has been defined, you may use it within any test that utilizes the page. The browser instance will automatically be passed as the first argument to custom page methods: - use Tests\Browser\Pages\Dashboard; +```php +use Tests\Browser\Pages\Dashboard; - $browser->visit(new Dashboard) - ->createPlaylist('My Playlist') - ->assertSee('My Playlist'); +$browser->visit(new Dashboard) + ->createPlaylist('My Playlist') + ->assertSee('My Playlist'); +``` ## Components -Components are similar to Dusk’s “page objects”, but are intended for pieces of UI and functionality that are re-used throughout your application, such as a navigation bar or notification window. As such, components are not bound to specific URLs. +Components are similar to Dusk's "page objects", but are intended for pieces of UI and functionality that are re-used throughout your application, such as a navigation bar or notification window. As such, components are not bound to specific URLs. ### Generating Components To generate a component, execute the `dusk:component` Artisan command. New components are placed in the `tests/Browser/Components` directory: - php artisan dusk:component DatePicker +```shell +php artisan dusk:component DatePicker +``` As shown above, a "date picker" is an example of a component that might exist throughout your application on a variety of pages. It can become cumbersome to manually write the browser automation logic to select a date in dozens of tests throughout your test suite. Instead, we can define a Dusk component to represent the date picker, allowing us to encapsulate that logic within the component: - assertVisible($this->selector()); - } + /** + * Assert that the browser page contains the component. + */ + public function assert(Browser $browser): void + { + $browser->assertVisible($this->selector()); + } - /** - * Get the element shortcuts for the component. - * - * @return array - */ - public function elements() - { - return [ - '@date-field' => 'input.datepicker-input', - '@year-list' => 'div > div.datepicker-years', - '@month-list' => 'div > div.datepicker-months', - '@day-list' => 'div > div.datepicker-days', - ]; - } + /** + * Get the element shortcuts for the component. + * + * @return array + */ + public function elements(): array + { + return [ + '@date-field' => 'input.datepicker-input', + '@year-list' => 'div > div.datepicker-years', + '@month-list' => 'div > div.datepicker-months', + '@day-list' => 'div > div.datepicker-days', + ]; + } - /** - * Select the given date. - * - * @param \Laravel\Dusk\Browser $browser - * @param int $year - * @param int $month - * @param int $day - * @return void - */ - public function selectDate(Browser $browser, $year, $month, $day) - { - $browser->click('@date-field') - ->within('@year-list', function ($browser) use ($year) { - $browser->click($year); - }) - ->within('@month-list', function ($browser) use ($month) { - $browser->click($month); - }) - ->within('@day-list', function ($browser) use ($day) { - $browser->click($day); - }); - } + /** + * Select the given date. + */ + public function selectDate(Browser $browser, int $year, int $month, int $day): void + { + $browser->click('@date-field') + ->within('@year-list', function (Browser $browser) use ($year) { + $browser->click($year); + }) + ->within('@month-list', function (Browser $browser) use ($month) { + $browser->click($month); + }) + ->within('@day-list', function (Browser $browser) use ($day) { + $browser->click($day); + }); } +} +``` ### Using Components Once the component has been defined, we can easily select a date within the date picker from any test. And, if the logic necessary to select a date changes, we only need to update the component: - use(DatabaseMigrations::class); - class ExampleTest extends DuskTestCase +test('basic example', function () { + $this->browse(function (Browser $browser) { + $browser->visit('/') + ->within(new DatePicker, function (Browser $browser) { + $browser->selectDate(2019, 1, 30); + }) + ->assertSee('January'); + }); +}); +``` + +```php tab=PHPUnit +browse(function (Browser $browser) { - $browser->visit('/') - ->within(new DatePicker, function ($browser) { - $browser->selectDate(2019, 1, 30); - }) - ->assertSee('January'); - }); - } + $this->browse(function (Browser $browser) { + $browser->visit('/') + ->within(new DatePicker, function (Browser $browser) { + $browser->selectDate(2019, 1, 30); + }) + ->assertSee('January'); + }); } +} +``` + +The `component` method may be used to retrieve a browser instance scoped to the given component: + +```php +$datePicker = $browser->component(new DatePickerComponent); + +$datePicker->selectDate(2019, 1, 30); + +$datePicker->assertSee('January'); +``` ## Continuous Integration -> {note} Most Dusk continuous integration configurations expect your Laravel application to be served using the built-in PHP development server on port 8000. Therefore, before continuing, you should ensure that your continuous integration environment has an `APP_URL` environment variable value of `http://127.0.0.1:8000`. +> [!WARNING] +> Most Dusk continuous integration configurations expect your Laravel application to be served using the built-in PHP development server on port 8000. Therefore, before continuing, you should ensure that your continuous integration environment has an `APP_URL` environment variable value of `http://127.0.0.1:8000`. ### Heroku CI To run Dusk tests on [Heroku CI](https://www.heroku.com/continuous-integration), add the following Google Chrome buildpack and scripts to your Heroku `app.json` file: - { - "environments": { - "test": { - "buildpacks": [ - { "url": "heroku/php" }, - { "url": "https://github.com/heroku/heroku-buildpack-google-chrome" } - ], - "scripts": { - "test-setup": "cp .env.testing .env", - "test": "nohup bash -c './vendor/laravel/dusk/bin/chromedriver-linux > /dev/null 2>&1 &' && nohup bash -c 'php artisan serve --no-reload > /dev/null 2>&1 &' && php artisan dusk" - } - } +```json +{ + "environments": { + "test": { + "buildpacks": [ + { "url": "heroku/php" }, + { "url": "https://github.com/heroku/heroku-buildpack-chrome-for-testing" } + ], + "scripts": { + "test-setup": "cp .env.testing .env", + "test": "nohup bash -c './vendor/laravel/dusk/bin/chromedriver-linux --port=9515 > /dev/null 2>&1 &' && nohup bash -c 'php artisan serve --no-reload > /dev/null 2>&1 &' && php artisan dusk" } } + } +} +``` ### Travis CI @@ -1820,7 +2565,7 @@ To run your Dusk tests on [Travis CI](https://travis-ci.org), use the following language: php php: - - 7.3 + - 8.2 addons: chrome: stable @@ -1842,7 +2587,7 @@ script: ### GitHub Actions -If you are using [Github Actions](https://github.com/features/actions) to run your Dusk tests, you may use the following configuration file as a starting point. Like TravisCI, we will use the `php artisan serve` command to launch PHP's built-in web server: +If you are using [GitHub Actions](https://github.com/features/actions) to run your Dusk tests, you may use the following configuration file as a starting point. Like TravisCI, we will use the `php artisan serve` command to launch PHP's built-in web server: ```yaml name: CI @@ -1851,38 +2596,89 @@ jobs: dusk-php: runs-on: ubuntu-latest + env: + APP_URL: "http://127.0.0.1:8000/" + DB_USERNAME: root + DB_PASSWORD: root + MAIL_MAILER: log steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v5 - name: Prepare The Environment run: cp .env.example .env - name: Create Database run: | sudo systemctl start mysql - mysql --user="root" --password="root" -e "CREATE DATABASE 'my-database' character set UTF8mb4 collate utf8mb4_bin;" + mysql --user="root" --password="root" -e "CREATE DATABASE \`my-database\` character set UTF8mb4 collate utf8mb4_bin;" - name: Install Composer Dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Generate Application Key run: php artisan key:generate - name: Upgrade Chrome Driver - run: php artisan dusk:chrome-driver `/opt/google/chrome/chrome --version | cut -d " " -f3 | cut -d "." -f1` + run: php artisan dusk:chrome-driver --detect - name: Start Chrome Driver - run: ./vendor/laravel/dusk/bin/chromedriver-linux & + run: ./vendor/laravel/dusk/bin/chromedriver-linux --port=9515 & - name: Run Laravel Server run: php artisan serve --no-reload & - name: Run Dusk Tests - env: - APP_URL: "http://127.0.0.1:8000/" run: php artisan dusk - name: Upload Screenshots if: failure() - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: screenshots path: tests/Browser/screenshots - name: Upload Console Logs if: failure() - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: console path: tests/Browser/console ``` + + +### Chipper CI + +If you are using [Chipper CI](https://chipperci.com) to run your Dusk tests, you may use the following configuration file as a starting point. We will use PHP's built-in server to run Laravel so we can listen for requests: + +```yaml +# file .chipperci.yml +version: 1 + +environment: + php: 8.2 + node: 16 + +# Include Chrome in the build environment +services: + - dusk + +# Build all commits +on: + push: + branches: .* + +pipeline: + - name: Setup + cmd: | + cp -v .env.example .env + composer install --no-interaction --prefer-dist --optimize-autoloader + php artisan key:generate + + # Create a dusk env file, ensuring APP_URL uses BUILD_HOST + cp -v .env .env.dusk.ci + sed -i "s@APP_URL=.*@APP_URL=http://$BUILD_HOST:8000@g" .env.dusk.ci + + - name: Compile Assets + cmd: | + npm ci --no-audit + npm run build + + - name: Browser Tests + cmd: | + php -S [::0]:8000 -t public 2>server.log & + sleep 2 + php artisan dusk:chrome-driver $CHROME_DRIVER + php artisan dusk --env=ci +``` + +To learn more about running Dusk tests on Chipper CI, including how to use databases, consult the [official Chipper CI documentation](https://chipperci.com/docs/testing/laravel-dusk-new/). diff --git a/eloquent-collections.md b/eloquent-collections.md index dd90ef55d36..9eec2ebd366 100644 --- a/eloquent-collections.md +++ b/eloquent-collections.md @@ -11,21 +11,25 @@ All Eloquent methods that return more than one model result will return instance All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays: - use App\Models\User; +```php +use App\Models\User; - $users = User::where('active', 1)->get(); +$users = User::where('active', 1)->get(); - foreach ($users as $user) { - echo $user->name; - } +foreach ($users as $user) { + echo $user->name; +} +``` However, as previously mentioned, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, we may remove all inactive models and then gather the first name for each remaining user: - $names = User::all()->reject(function ($user) { - return $user->active === false; - })->map(function ($user) { - return $user->name; - }); +```php +$names = User::all()->reject(function (User $user) { + return $user->active === false; +})->map(function (User $user) { + return $user->name; +}); +``` #### Eloquent Collection Conversion @@ -40,13 +44,15 @@ All Eloquent collections extend the base [Laravel collection](/docs/{{version}}/ In addition, the `Illuminate\Database\Eloquent\Collection` class provides a superset of methods to aid with managing your model collections. Most methods return `Illuminate\Database\Eloquent\Collection` instances; however, some methods, like `modelKeys`, return an `Illuminate\Support\Collection` instance. -
+
+[append](#method-append) [contains](#method-contains) [diff](#method-diff) [except](#method-except) [find](#method-find) +[findOrFail](#method-find-or-fail) [fresh](#method-fresh) [intersect](#method-intersect) [load](#method-load) @@ -72,155 +80,272 @@ In addition, the `Illuminate\Database\Eloquent\Collection` class provides a supe [makeVisible](#method-makeVisible) [makeHidden](#method-makeHidden) [only](#method-only) +[partition](#method-partition) +[setVisible](#method-setVisible) +[setHidden](#method-setHidden) [toQuery](#method-toquery) [unique](#method-unique)
+ +#### `append($attributes)` {.collection-method .first-collection-method} + +The `append` method may be used to indicate that an attribute should be [appended](/docs/{{version}}/eloquent-serialization#appending-values-to-json) for every model in the collection. This method accepts an array of attributes or a single attribute: + +```php +$users->append('team'); + +$users->append(['team', 'is_admin']); +``` + -#### `contains($key, $operator = null, $value = null)` {.collection-method .first-collection-method} +#### `contains($key, $operator = null, $value = null)` {.collection-method} The `contains` method may be used to determine if a given model instance is contained by the collection. This method accepts a primary key or a model instance: - $users->contains(1); +```php +$users->contains(1); - $users->contains(User::find(1)); +$users->contains(User::find(1)); +``` #### `diff($items)` {.collection-method} The `diff` method returns all of the models that are not present in the given collection: - use App\Models\User; +```php +use App\Models\User; - $users = $users->diff(User::whereIn('id', [1, 2, 3])->get()); +$users = $users->diff(User::whereIn('id', [1, 2, 3])->get()); +``` #### `except($keys)` {.collection-method} The `except` method returns all of the models that do not have the given primary keys: - $users = $users->except([1, 2, 3]); +```php +$users = $users->except([1, 2, 3]); +``` #### `find($key)` {.collection-method} The `find` method returns the model that has a primary key matching the given key. If `$key` is a model instance, `find` will attempt to return a model matching the primary key. If `$key` is an array of keys, `find` will return all models which have a primary key in the given array: - $users = User::all(); +```php +$users = User::all(); + +$user = $users->find(1); +``` + + +#### `findOrFail($key)` {.collection-method} + +The `findOrFail` method returns the model that has a primary key matching the given key or throws an `Illuminate\Database\Eloquent\ModelNotFoundException` exception if no matching model can be found in the collection: - $user = $users->find(1); +```php +$users = User::all(); + +$user = $users->findOrFail(1); +``` #### `fresh($with = [])` {.collection-method} The `fresh` method retrieves a fresh instance of each model in the collection from the database. In addition, any specified relationships will be eager loaded: - $users = $users->fresh(); +```php +$users = $users->fresh(); - $users = $users->fresh('comments'); +$users = $users->fresh('comments'); +``` #### `intersect($items)` {.collection-method} The `intersect` method returns all of the models that are also present in the given collection: - use App\Models\User; +```php +use App\Models\User; - $users = $users->intersect(User::whereIn('id', [1, 2, 3])->get()); +$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get()); +``` #### `load($relations)` {.collection-method} The `load` method eager loads the given relationships for all models in the collection: - $users->load(['comments', 'posts']); +```php +$users->load(['comments', 'posts']); + +$users->load('comments.author'); - $users->load('comments.author'); +$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]); +``` #### `loadMissing($relations)` {.collection-method} The `loadMissing` method eager loads the given relationships for all models in the collection if the relationships are not already loaded: - $users->loadMissing(['comments', 'posts']); +```php +$users->loadMissing(['comments', 'posts']); - $users->loadMissing('comments.author'); +$users->loadMissing('comments.author'); + +$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]); +``` #### `modelKeys()` {.collection-method} The `modelKeys` method returns the primary keys for all models in the collection: - $users->modelKeys(); +```php +$users->modelKeys(); - // [1, 2, 3, 4, 5] +// [1, 2, 3, 4, 5] +``` #### `makeVisible($attributes)` {.collection-method} The `makeVisible` method [makes attributes visible](/docs/{{version}}/eloquent-serialization#hiding-attributes-from-json) that are typically "hidden" on each model in the collection: - $users = $users->makeVisible(['address', 'phone_number']); +```php +$users = $users->makeVisible(['address', 'phone_number']); +``` #### `makeHidden($attributes)` {.collection-method} The `makeHidden` method [hides attributes](/docs/{{version}}/eloquent-serialization#hiding-attributes-from-json) that are typically "visible" on each model in the collection: - $users = $users->makeHidden(['address', 'phone_number']); +```php +$users = $users->makeHidden(['address', 'phone_number']); +``` #### `only($keys)` {.collection-method} The `only` method returns all of the models that have the given primary keys: - $users = $users->only([1, 2, 3]); +```php +$users = $users->only([1, 2, 3]); +``` + + +#### `partition` {.collection-method} + +The `partition` method returns an instance of `Illuminate\Support\Collection` containing `Illuminate\Database\Eloquent\Collection` collection instances: + +```php +$partition = $users->partition(fn ($user) => $user->age > 18); + +dump($partition::class); // Illuminate\Support\Collection +dump($partition[0]::class); // Illuminate\Database\Eloquent\Collection +dump($partition[1]::class); // Illuminate\Database\Eloquent\Collection +``` + + +#### `setVisible($attributes)` {.collection-method} + +The `setVisible` method [temporarily overrides](/docs/{{version}}/eloquent-serialization#temporarily-modifying-attribute-visibility) all of the visible attributes on each model in the collection: + +```php +$users = $users->setVisible(['id', 'name']); +``` + + +#### `setHidden($attributes)` {.collection-method} + +The `setHidden` method [temporarily overrides](/docs/{{version}}/eloquent-serialization#temporarily-modifying-attribute-visibility) all of the hidden attributes on each model in the collection: + +```php +$users = $users->setHidden(['email', 'password', 'remember_token']); +``` #### `toQuery()` {.collection-method} The `toQuery` method returns an Eloquent query builder instance containing a `whereIn` constraint on the collection model's primary keys: - use App\Models\User; +```php +use App\Models\User; - $users = User::where('status', 'VIP')->get(); +$users = User::where('status', 'VIP')->get(); - $users->toQuery()->update([ - 'status' => 'Administrator', - ]); +$users->toQuery()->update([ + 'status' => 'Administrator', +]); +``` #### `unique($key = null, $strict = false)` {.collection-method} -The `unique` method returns all of the unique models in the collection. Any models of the same type with the same primary key as another model in the collection are removed: +The `unique` method returns all of the unique models in the collection. Any models with the same primary key as another model in the collection are removed: - $users = $users->unique(); +```php +$users = $users->unique(); +``` ## Custom Collections -If you would like to use a custom `Collection` object when interacting with a given model, you may define a `newCollection` method on your model: +If you would like to use a custom `Collection` object when interacting with a given model, you may add the `CollectedBy` attribute to your model: + +```php + $models + * @return \Illuminate\Database\Eloquent\Collection + */ + public function newCollection(array $models = []): Collection { - /** - * Create a new Eloquent Collection instance. - * - * @param array $models - * @return \Illuminate\Database\Eloquent\Collection - */ - public function newCollection(array $models = []) - { - return new UserCollection($models); + $collection = new UserCollection($models); + + if (Model::isAutomaticallyEagerLoadingRelationships()) { + $collection->withRelationshipAutoloading(); } + + return $collection; } +} +``` + +Once you have defined a `newCollection` method or added the `CollectedBy` attribute to your model, you will receive an instance of your custom collection anytime Eloquent would normally return an `Illuminate\Database\Eloquent\Collection` instance. -Once you have defined a `newCollection` method, you will receive an instance of your custom collection anytime Eloquent would normally return an `Illuminate\Database\Eloquent\Collection` instance. If you would like to use a custom collection for every model in your application, you should define the `newCollection` method on a base model class that is extended by all of your application's models. +If you would like to use a custom collection for every model in your application, you should define the `newCollection` method on a base model class that is extended by all of your application's models. diff --git a/eloquent-factories.md b/eloquent-factories.md new file mode 100644 index 00000000000..67ca396a541 --- /dev/null +++ b/eloquent-factories.md @@ -0,0 +1,639 @@ +# Eloquent: Factories + +- [Introduction](#introduction) +- [Defining Model Factories](#defining-model-factories) + - [Generating Factories](#generating-factories) + - [Factory States](#factory-states) + - [Factory Callbacks](#factory-callbacks) +- [Creating Models Using Factories](#creating-models-using-factories) + - [Instantiating Models](#instantiating-models) + - [Persisting Models](#persisting-models) + - [Sequences](#sequences) +- [Factory Relationships](#factory-relationships) + - [Has Many Relationships](#has-many-relationships) + - [Belongs To Relationships](#belongs-to-relationships) + - [Many to Many Relationships](#many-to-many-relationships) + - [Polymorphic Relationships](#polymorphic-relationships) + - [Defining Relationships Within Factories](#defining-relationships-within-factories) + - [Recycling an Existing Model for Relationships](#recycling-an-existing-model-for-relationships) + + +## Introduction + +When testing your application or seeding your database, you may need to insert a few records into your database. Instead of manually specifying the value of each column, Laravel allows you to define a set of default attributes for each of your [Eloquent models](/docs/{{version}}/eloquent) using model factories. + +To see an example of how to write a factory, take a look at the `database/factories/UserFactory.php` file in your application. This factory is included with all new Laravel applications and contains the following factory definition: + +```php +namespace Database\Factories; + +use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Str; + +/** + * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User> + */ +class UserFactory extends Factory +{ + /** + * The current password being used by the factory. + */ + protected static ?string $password; + + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'name' => fake()->name(), + 'email' => fake()->unique()->safeEmail(), + 'email_verified_at' => now(), + 'password' => static::$password ??= Hash::make('password'), + 'remember_token' => Str::random(10), + ]; + } + + /** + * Indicate that the model's email address should be unverified. + */ + public function unverified(): static + { + return $this->state(fn (array $attributes) => [ + 'email_verified_at' => null, + ]); + } +} +``` + +As you can see, in their most basic form, factories are classes that extend Laravel's base factory class and define a `definition` method. The `definition` method returns the default set of attribute values that should be applied when creating a model using the factory. + +Via the `fake` helper, factories have access to the [Faker](https://github.com/FakerPHP/Faker) PHP library, which allows you to conveniently generate various kinds of random data for testing and seeding. + +> [!NOTE] +> You can change your application's Faker locale by updating the `faker_locale` option in your `config/app.php` configuration file. + + +## Defining Model Factories + + +### Generating Factories + +To create a factory, execute the `make:factory` [Artisan command](/docs/{{version}}/artisan): + +```shell +php artisan make:factory PostFactory +``` + +The new factory class will be placed in your `database/factories` directory. + + +#### Model and Factory Discovery Conventions + +Once you have defined your factories, you may use the static `factory` method provided to your models by the `Illuminate\Database\Eloquent\Factories\HasFactory` trait in order to instantiate a factory instance for that model. + +The `HasFactory` trait's `factory` method will use conventions to determine the proper factory for the model the trait is assigned to. Specifically, the method will look for a factory in the `Database\Factories` namespace that has a class name matching the model name and is suffixed with `Factory`. If these conventions do not apply to your particular application or factory, you may overwrite the `newFactory` method on your model to return an instance of the model's corresponding factory directly: + +```php +use Database\Factories\Administration\FlightFactory; + +/** + * Create a new factory instance for the model. + */ +protected static function newFactory() +{ + return FlightFactory::new(); +} +``` + +Then, define a `model` property on the corresponding factory: + +```php +use App\Administration\Flight; +use Illuminate\Database\Eloquent\Factories\Factory; + +class FlightFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var class-string<\Illuminate\Database\Eloquent\Model> + */ + protected $model = Flight::class; +} +``` + + +### Factory States + +State manipulation methods allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your `Database\Factories\UserFactory` factory might contain a `suspended` state method that modifies one of its default attribute values. + +State transformation methods typically call the `state` method provided by Laravel's base factory class. The `state` method accepts a closure which will receive the array of raw attributes defined for the factory and should return an array of attributes to modify: + +```php +use Illuminate\Database\Eloquent\Factories\Factory; + +/** + * Indicate that the user is suspended. + */ +public function suspended(): Factory +{ + return $this->state(function (array $attributes) { + return [ + 'account_status' => 'suspended', + ]; + }); +} +``` + + +#### "Trashed" State + +If your Eloquent model can be [soft deleted](/docs/{{version}}/eloquent#soft-deleting), you may invoke the built-in `trashed` state method to indicate that the created model should already be "soft deleted". You do not need to manually define the `trashed` state as it is automatically available to all factories: + +```php +use App\Models\User; + +$user = User::factory()->trashed()->create(); +``` + + +### Factory Callbacks + +Factory callbacks are registered using the `afterMaking` and `afterCreating` methods and allow you to perform additional tasks after making or creating a model. You should register these callbacks by defining a `configure` method on your factory class. This method will be automatically called by Laravel when the factory is instantiated: + +```php +namespace Database\Factories; + +use App\Models\User; +use Illuminate\Database\Eloquent\Factories\Factory; + +class UserFactory extends Factory +{ + /** + * Configure the model factory. + */ + public function configure(): static + { + return $this->afterMaking(function (User $user) { + // ... + })->afterCreating(function (User $user) { + // ... + }); + } + + // ... +} +``` + +You may also register factory callbacks within state methods to perform additional tasks that are specific to a given state: + +```php +use App\Models\User; +use Illuminate\Database\Eloquent\Factories\Factory; + +/** + * Indicate that the user is suspended. + */ +public function suspended(): Factory +{ + return $this->state(function (array $attributes) { + return [ + 'account_status' => 'suspended', + ]; + })->afterMaking(function (User $user) { + // ... + })->afterCreating(function (User $user) { + // ... + }); +} +``` + + +## Creating Models Using Factories + + +### Instantiating Models + +Once you have defined your factories, you may use the static `factory` method provided to your models by the `Illuminate\Database\Eloquent\Factories\HasFactory` trait in order to instantiate a factory instance for that model. Let's take a look at a few examples of creating models. First, we'll use the `make` method to create models without persisting them to the database: + +```php +use App\Models\User; + +$user = User::factory()->make(); +``` + +You may create a collection of many models using the `count` method: + +```php +$users = User::factory()->count(3)->make(); +``` + + +#### Applying States + +You may also apply any of your [states](#factory-states) to the models. If you would like to apply multiple state transformations to the models, you may simply call the state transformation methods directly: + +```php +$users = User::factory()->count(5)->suspended()->make(); +``` + + +#### Overriding Attributes + +If you would like to override some of the default values of your models, you may pass an array of values to the `make` method. Only the specified attributes will be replaced while the rest of the attributes remain set to their default values as specified by the factory: + +```php +$user = User::factory()->make([ + 'name' => 'Abigail Otwell', +]); +``` + +Alternatively, the `state` method may be called directly on the factory instance to perform an inline state transformation: + +```php +$user = User::factory()->state([ + 'name' => 'Abigail Otwell', +])->make(); +``` + +> [!NOTE] +> [Mass assignment protection](/docs/{{version}}/eloquent#mass-assignment) is automatically disabled when creating models using factories. + + +### Persisting Models + +The `create` method instantiates model instances and persists them to the database using Eloquent's `save` method: + +```php +use App\Models\User; + +// Create a single App\Models\User instance... +$user = User::factory()->create(); + +// Create three App\Models\User instances... +$users = User::factory()->count(3)->create(); +``` + +You may override the factory's default model attributes by passing an array of attributes to the `create` method: + +```php +$user = User::factory()->create([ + 'name' => 'Abigail', +]); +``` + + +### Sequences + +Sometimes you may wish to alternate the value of a given model attribute for each created model. You may accomplish this by defining a state transformation as a sequence. For example, you may wish to alternate the value of an `admin` column between `Y` and `N` for each created user: + +```php +use App\Models\User; +use Illuminate\Database\Eloquent\Factories\Sequence; + +$users = User::factory() + ->count(10) + ->state(new Sequence( + ['admin' => 'Y'], + ['admin' => 'N'], + )) + ->create(); +``` + +In this example, five users will be created with an `admin` value of `Y` and five users will be created with an `admin` value of `N`. + +If necessary, you may include a closure as a sequence value. The closure will be invoked each time the sequence needs a new value: + +```php +use Illuminate\Database\Eloquent\Factories\Sequence; + +$users = User::factory() + ->count(10) + ->state(new Sequence( + fn (Sequence $sequence) => ['role' => UserRoles::all()->random()], + )) + ->create(); +``` + +Within a sequence closure, you may access the `$index` property on the sequence instance that is injected into the closure. The `$index` property contains the number of iterations through the sequence that have occurred thus far: + +```php +$users = User::factory() + ->count(10) + ->state(new Sequence( + fn (Sequence $sequence) => ['name' => 'Name '.$sequence->index], + )) + ->create(); +``` + +For convenience, sequences may also be applied using the `sequence` method, which simply invokes the `state` method internally. The `sequence` method accepts a closure or arrays of sequenced attributes: + +```php +$users = User::factory() + ->count(2) + ->sequence( + ['name' => 'First User'], + ['name' => 'Second User'], + ) + ->create(); +``` + + +## Factory Relationships + + +### Has Many Relationships + +Next, let's explore building Eloquent model relationships using Laravel's fluent factory methods. First, let's assume our application has an `App\Models\User` model and an `App\Models\Post` model. Also, let's assume that the `User` model defines a `hasMany` relationship with `Post`. We can create a user that has three posts using the `has` method provided by the Laravel's factories. The `has` method accepts a factory instance: + +```php +use App\Models\Post; +use App\Models\User; + +$user = User::factory() + ->has(Post::factory()->count(3)) + ->create(); +``` + +By convention, when passing a `Post` model to the `has` method, Laravel will assume that the `User` model must have a `posts` method that defines the relationship. If necessary, you may explicitly specify the name of the relationship that you would like to manipulate: + +```php +$user = User::factory() + ->has(Post::factory()->count(3), 'posts') + ->create(); +``` + +Of course, you may perform state manipulations on the related models. In addition, you may pass a closure-based state transformation if your state change requires access to the parent model: + +```php +$user = User::factory() + ->has( + Post::factory() + ->count(3) + ->state(function (array $attributes, User $user) { + return ['user_type' => $user->type]; + }) + ) + ->create(); +``` + + +#### Using Magic Methods + +For convenience, you may use Laravel's magic factory relationship methods to build relationships. For example, the following example will use convention to determine that the related models should be created via a `posts` relationship method on the `User` model: + +```php +$user = User::factory() + ->hasPosts(3) + ->create(); +``` + +When using magic methods to create factory relationships, you may pass an array of attributes to override on the related models: + +```php +$user = User::factory() + ->hasPosts(3, [ + 'published' => false, + ]) + ->create(); +``` + +You may provide a closure-based state transformation if your state change requires access to the parent model: + +```php +$user = User::factory() + ->hasPosts(3, function (array $attributes, User $user) { + return ['user_type' => $user->type]; + }) + ->create(); +``` + + +### Belongs To Relationships + +Now that we have explored how to build "has many" relationships using factories, let's explore the inverse of the relationship. The `for` method may be used to define the parent model that factory created models belong to. For example, we can create three `App\Models\Post` model instances that belong to a single user: + +```php +use App\Models\Post; +use App\Models\User; + +$posts = Post::factory() + ->count(3) + ->for(User::factory()->state([ + 'name' => 'Jessica Archer', + ])) + ->create(); +``` + +If you already have a parent model instance that should be associated with the models you are creating, you may pass the model instance to the `for` method: + +```php +$user = User::factory()->create(); + +$posts = Post::factory() + ->count(3) + ->for($user) + ->create(); +``` + + +#### Using Magic Methods + +For convenience, you may use Laravel's magic factory relationship methods to define "belongs to" relationships. For example, the following example will use convention to determine that the three posts should belong to the `user` relationship on the `Post` model: + +```php +$posts = Post::factory() + ->count(3) + ->forUser([ + 'name' => 'Jessica Archer', + ]) + ->create(); +``` + + +### Many to Many Relationships + +Like [has many relationships](#has-many-relationships), "many to many" relationships may be created using the `has` method: + +```php +use App\Models\Role; +use App\Models\User; + +$user = User::factory() + ->has(Role::factory()->count(3)) + ->create(); +``` + + +#### Pivot Table Attributes + +If you need to define attributes that should be set on the pivot / intermediate table linking the models, you may use the `hasAttached` method. This method accepts an array of pivot table attribute names and values as its second argument: + +```php +use App\Models\Role; +use App\Models\User; + +$user = User::factory() + ->hasAttached( + Role::factory()->count(3), + ['active' => true] + ) + ->create(); +``` + +You may provide a closure-based state transformation if your state change requires access to the related model: + +```php +$user = User::factory() + ->hasAttached( + Role::factory() + ->count(3) + ->state(function (array $attributes, User $user) { + return ['name' => $user->name.' Role']; + }), + ['active' => true] + ) + ->create(); +``` + +If you already have model instances that you would like to be attached to the models you are creating, you may pass the model instances to the `hasAttached` method. In this example, the same three roles will be attached to all three users: + +```php +$roles = Role::factory()->count(3)->create(); + +$users = User::factory() + ->count(3) + ->hasAttached($roles, ['active' => true]) + ->create(); +``` + + +#### Using Magic Methods + +For convenience, you may use Laravel's magic factory relationship methods to define many to many relationships. For example, the following example will use convention to determine that the related models should be created via a `roles` relationship method on the `User` model: + +```php +$user = User::factory() + ->hasRoles(1, [ + 'name' => 'Editor' + ]) + ->create(); +``` + + +### Polymorphic Relationships + +[Polymorphic relationships](/docs/{{version}}/eloquent-relationships#polymorphic-relationships) may also be created using factories. Polymorphic "morph many" relationships are created in the same way as typical "has many" relationships. For example, if an `App\Models\Post` model has a `morphMany` relationship with an `App\Models\Comment` model: + +```php +use App\Models\Post; + +$post = Post::factory()->hasComments(3)->create(); +``` + + +#### Morph To Relationships + +Magic methods may not be used to create `morphTo` relationships. Instead, the `for` method must be used directly and the name of the relationship must be explicitly provided. For example, imagine that the `Comment` model has a `commentable` method that defines a `morphTo` relationship. In this situation, we may create three comments that belong to a single post by using the `for` method directly: + +```php +$comments = Comment::factory()->count(3)->for( + Post::factory(), 'commentable' +)->create(); +``` + + +#### Polymorphic Many to Many Relationships + +Polymorphic "many to many" (`morphToMany` / `morphedByMany`) relationships may be created just like non-polymorphic "many to many" relationships: + +```php +use App\Models\Tag; +use App\Models\Video; + +$video = Video::factory() + ->hasAttached( + Tag::factory()->count(3), + ['public' => true] + ) + ->create(); +``` + +Of course, the magic `has` method may also be used to create polymorphic "many to many" relationships: + +```php +$video = Video::factory() + ->hasTags(3, ['public' => true]) + ->create(); +``` + + +### Defining Relationships Within Factories + +To define a relationship within your model factory, you will typically assign a new factory instance to the foreign key of the relationship. This is normally done for the "inverse" relationships such as `belongsTo` and `morphTo` relationships. For example, if you would like to create a new user when creating a post, you may do the following: + +```php +use App\Models\User; + +/** + * Define the model's default state. + * + * @return array + */ +public function definition(): array +{ + return [ + 'user_id' => User::factory(), + 'title' => fake()->title(), + 'content' => fake()->paragraph(), + ]; +} +``` + +If the relationship's columns depend on the factory that defines it you may assign a closure to an attribute. The closure will receive the factory's evaluated attribute array: + +```php +/** + * Define the model's default state. + * + * @return array + */ +public function definition(): array +{ + return [ + 'user_id' => User::factory(), + 'user_type' => function (array $attributes) { + return User::find($attributes['user_id'])->type; + }, + 'title' => fake()->title(), + 'content' => fake()->paragraph(), + ]; +} +``` + + +### Recycling an Existing Model for Relationships + +If you have models that share a common relationship with another model, you may use the `recycle` method to ensure a single instance of the related model is recycled for all of the relationships created by the factory. + +For example, imagine you have `Airline`, `Flight`, and `Ticket` models, where the ticket belongs to an airline and a flight, and the flight also belongs to an airline. When creating tickets, you will probably want the same airline for both the ticket and the flight, so you may pass an airline instance to the `recycle` method: + +```php +Ticket::factory() + ->recycle(Airline::factory()->create()) + ->create(); +``` + +You may find the `recycle` method particularly useful if you have models belonging to a common user or team. + +The `recycle` method also accepts a collection of existing models. When a collection is provided to the `recycle` method, a random model from the collection will be chosen when the factory needs a model of that type: + +```php +Ticket::factory() + ->recycle($airlines) + ->create(); +``` diff --git a/eloquent-mutators.md b/eloquent-mutators.md index c112ebd8c1f..f8ef3c27789 100644 --- a/eloquent-mutators.md +++ b/eloquent-mutators.md @@ -1,11 +1,11 @@ # Eloquent: Mutators & Casting - [Introduction](#introduction) -- [Accessors & Mutators](#accessors-and-mutators) - - [Defining An Accessor](#defining-an-accessor) - - [Defining A Mutator](#defining-a-mutator) +- [Accessors and Mutators](#accessors-and-mutators) + - [Defining an Accessor](#defining-an-accessor) + - [Defining a Mutator](#defining-a-mutator) - [Attribute Casting](#attribute-casting) - - [Array & JSON Casting](#array-and-json-casting) + - [Array and JSON Casting](#array-and-json-casting) - [Date Casting](#date-casting) - [Enum Casting](#enum-casting) - [Encrypted Casting](#encrypted-casting) @@ -15,6 +15,7 @@ - [Array / JSON Serialization](#array-json-serialization) - [Inbound Casting](#inbound-casting) - [Cast Parameters](#cast-parameters) + - [Comparing Cast Values](#comparing-cast-values) - [Castables](#castables) @@ -23,48 +24,51 @@ Accessors, mutators, and attribute casting allow you to transform Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the [Laravel encrypter](/docs/{{version}}/encryption) to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. Or, you may want to convert a JSON string that is stored in your database to an array when it is accessed via your Eloquent model. -## Accessors & Mutators +## Accessors and Mutators -### Defining An Accessor +### Defining an Accessor An accessor transforms an Eloquent attribute value when it is accessed. To define an accessor, create a protected method on your model to represent the accessible attribute. This method name should correspond to the "camel case" representation of the true underlying model attribute / database column when applicable. In this example, we'll define an accessor for the `first_name` attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the `first_name` attribute. All attribute accessor / mutator methods must declare a return type-hint of `Illuminate\Database\Eloquent\Casts\Attribute`: - ucfirst($value), - ); - } + return Attribute::make( + get: fn (string $value) => ucfirst($value), + ); } +} +``` All accessor methods return an `Attribute` instance which defines how the attribute will be accessed and, optionally, mutated. In this example, we are only defining how the attribute will be accessed. To do so, we supply the `get` argument to the `Attribute` class constructor. As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may simply access the `first_name` attribute on a model instance: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $firstName = $user->first_name; +$firstName = $user->first_name; +``` -> {tip} If you would like these computed values to be added to the array / JSON representations of your model, [you will need to append them](/docs/{{version}}/eloquent-serialization#appending-values-to-json). +> [!NOTE] +> If you would like these computed values to be added to the array / JSON representations of your model, [you will need to append them](/docs/{{version}}/eloquent-serialization#appending-values-to-json). #### Building Value Objects From Multiple Attributes @@ -77,13 +81,11 @@ use Illuminate\Database\Eloquent\Casts\Attribute; /** * Interact with the user's address. - * - * @return \Illuminate\Database\Eloquent\Casts\Attribute */ -public function address(): Attribute +protected function address(): Attribute { - return new Attribute( - get: fn ($value, $attributes) => new Address( + return Attribute::make( + get: fn (mixed $value, array $attributes) => new Address( $attributes['address_line_one'], $attributes['address_line_two'], ), @@ -91,74 +93,89 @@ public function address(): Attribute } ``` -When returning value objects from accessors, any changes made to the value object will automatically be synced back to the model before the model is saved. This is possible because Eloquent retains instances returned by accessors so it can be return the same instance each time the accessor is invoked: + +#### Accessor Caching + +When returning value objects from accessors, any changes made to the value object will automatically be synced back to the model before the model is saved. This is possible because Eloquent retains instances returned by accessors so it can return the same instance each time the accessor is invoked: + +```php +use App\Models\User; - use App\Models\User; +$user = User::find(1); - $user = User::find(1); +$user->address->lineOne = 'Updated Address Line 1 Value'; +$user->address->lineTwo = 'Updated Address Line 2 Value'; - $user->address->lineOne = 'Updated Address Line 1 Value'; - $user->address->lineTwo = 'Updated Address Line 2 Value'; +$user->save(); +``` - $user->save(); +However, you may sometimes wish to enable caching for primitive values like strings and booleans, particularly if they are computationally intensive. To accomplish this, you may invoke the `shouldCache` method when defining your accessor: + +```php +protected function hash(): Attribute +{ + return Attribute::make( + get: fn (string $value) => bcrypt(gzuncompress($value)), + )->shouldCache(); +} +``` If you would like to disable the object caching behavior of attributes, you may invoke the `withoutObjectCaching` method when defining the attribute: ```php /** * Interact with the user's address. - * - * @return \Illuminate\Database\Eloquent\Casts\Attribute */ -public function address(): Attribute +protected function address(): Attribute { - return (new Attribute( - get: fn ($value, $attributes) => new Address( + return Attribute::make( + get: fn (mixed $value, array $attributes) => new Address( $attributes['address_line_one'], $attributes['address_line_two'], ), - ))->withoutObjectCaching(); + )->withoutObjectCaching(); } ``` -### Defining A Mutator +### Defining a Mutator A mutator transforms an Eloquent attribute value when it is set. To define a mutator, you may provide the `set` argument when defining your attribute. Let's define a mutator for the `first_name` attribute. This mutator will be automatically called when we attempt to set the value of the `first_name` attribute on the model: - ucfirst($value), - set: fn ($value) => strtolower($value), - ); - } + return Attribute::make( + get: fn (string $value) => ucfirst($value), + set: fn (string $value) => strtolower($value), + ); } +} +``` The mutator closure will receive the value that is being set on the attribute, allowing you to manipulate the value and return the manipulated value. To use our mutator, we only need to set the `first_name` attribute on an Eloquent model: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $user->first_name = 'Sally'; +$user->first_name = 'Sally'; +``` -In this example, the `set` callback will be called with the value `Sally`. The mutator will then apply the `strtolower` function to the name and set its resulting value in model's the internal `$attributes` array. +In this example, the `set` callback will be called with the value `Sally`. The mutator will then apply the `strtolower` function to the name and set its resulting value in the model's internal `$attributes` array. #### Mutating Multiple Attributes @@ -171,13 +188,11 @@ use Illuminate\Database\Eloquent\Casts\Attribute; /** * Interact with the user's address. - * - * @return \Illuminate\Database\Eloquent\Casts\Attribute */ -public function address(): Attribute +protected function address(): Attribute { - return new Attribute( - get: fn ($value, $attributes) => new Address( + return Attribute::make( + get: fn (mixed $value, array $attributes) => new Address( $attributes['address_line_one'], $attributes['address_line_two'], ), @@ -192,27 +207,30 @@ public function address(): Attribute ## Attribute Casting -Attribute casting provides functionality similar to accessors and mutators without requiring you to define any additional methods on your model. Instead, your model's `$casts` property provides a convenient method of converting attributes to common data types. +Attribute casting provides functionality similar to accessors and mutators without requiring you to define any additional methods on your model. Instead, your model's `casts` method provides a convenient way of converting attributes to common data types. -The `$casts` property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are: +The `casts` method should return an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are:
- `array` +- `AsFluent::class` - `AsStringable::class` +- `AsUri::class` - `boolean` - `collection` - `date` - `datetime` - `immutable_date` - `immutable_datetime` -- `decimal:`<digits> +- decimal:<precision> - `double` - `encrypted` - `encrypted:array` - `encrypted:collection` - `encrypted:object` - `float` +- `hashed` - `integer` - `object` - `real` @@ -223,215 +241,393 @@ The `$casts` property should be an array where the key is the name of the attrib To demonstrate attribute casting, let's cast the `is_admin` attribute, which is stored in our database as an integer (`0` or `1`) to a boolean value: - + */ + protected function casts(): array { - /** - * The attributes that should be cast. - * - * @var array - */ - protected $casts = [ + return [ 'is_admin' => 'boolean', ]; } +} +``` After defining the cast, the `is_admin` attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer: - $user = App\Models\User::find(1); +```php +$user = App\Models\User::find(1); - if ($user->is_admin) { - // - } +if ($user->is_admin) { + // ... +} +``` If you need to add a new, temporary cast at runtime, you may use the `mergeCasts` method. These cast definitions will be added to any of the casts already defined on the model: - $user->mergeCasts([ - 'is_admin' => 'integer', - 'options' => 'object', - ]); +```php +$user->mergeCasts([ + 'is_admin' => 'integer', + 'options' => 'object', +]); +``` -> {note} Attributes that are `null` will not be cast. In addition, you should never define a cast (or an attribute) that has the same name as a relationship. +> [!WARNING] +> Attributes that are `null` will not be cast. In addition, you should never define a cast (or an attribute) that has the same name as a relationship or assign a cast to the model's primary key. #### Stringable Casting -You may use the `Illuminate\Database\Eloquent\Casts\AsStringable` cast class to cast a model attribute to a [fluent `Illuminate\Support\Stringable` object](/docs/{{version}}/helpers#fluent-strings-method-list): +You may use the `Illuminate\Database\Eloquent\Casts\AsStringable` cast class to cast a model attribute to a [fluent Illuminate\Support\Stringable object](/docs/{{version}}/strings#fluent-strings-method-list): - + */ + protected function casts(): array { - /** - * The attributes that should be cast. - * - * @var array - */ - protected $casts = [ + return [ 'directory' => AsStringable::class, ]; } +} +``` -### Array & JSON Casting +### Array and JSON Casting The `array` cast is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a `JSON` or `TEXT` field type that contains serialized JSON, adding the `array` cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model: - + */ + protected function casts(): array { - /** - * The attributes that should be cast. - * - * @var array - */ - protected $casts = [ + return [ 'options' => 'array', ]; } +} +``` Once the cast is defined, you may access the `options` attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the `options` attribute, the given array will automatically be serialized back into JSON for storage: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $options = $user->options; +$options = $user->options; - $options['key'] = 'value'; +$options['key'] = 'value'; - $user->options = $options; +$user->options = $options; - $user->save(); +$user->save(); +``` -To update a single field of a JSON attribute with a more terse syntax, you may use the `->` operator when calling the `update` method: +To update a single field of a JSON attribute with a more terse syntax, you may [make the attribute mass assignable](/docs/{{version}}/eloquent#mass-assignment-json-columns) and use the `->` operator when calling the `update` method: - $user = User::find(1); +```php +$user = User::find(1); - $user->update(['options->key' => 'value']); +$user->update(['options->key' => 'value']); +``` + + +#### JSON and Unicode + +If you would like to store an array attribute as JSON with unescaped Unicode characters, you may use the `json:unicode` cast: + +```php +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ + 'options' => 'json:unicode', + ]; +} +``` -#### Array Object & Collection Casting +#### Array Object and Collection Casting Although the standard `array` cast is sufficient for many applications, it does have some disadvantages. Since the `array` cast returns a primitive type, it is not possible to mutate an offset of the array directly. For example, the following code will trigger a PHP error: - $user = User::find(1); +```php +$user = User::find(1); - $user->options['key'] = $value; +$user->options['key'] = $value; +``` To solve this, Laravel offers an `AsArrayObject` cast that casts your JSON attribute to an [ArrayObject](https://www.php.net/manual/en/class.arrayobject.php) class. This feature is implemented using Laravel's [custom cast](#custom-casts) implementation, which allows Laravel to intelligently cache and transform the mutated object such that individual offsets may be modified without triggering a PHP error. To use the `AsArrayObject` cast, simply assign it to an attribute: - use Illuminate\Database\Eloquent\Casts\AsArrayObject; +```php +use Illuminate\Database\Eloquent\Casts\AsArrayObject; - /** - * The attributes that should be cast. - * - * @var array - */ - protected $casts = [ +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ 'options' => AsArrayObject::class, ]; +} +``` Similarly, Laravel offers an `AsCollection` cast that casts your JSON attribute to a Laravel [Collection](/docs/{{version}}/collections) instance: - use Illuminate\Database\Eloquent\Casts\AsCollection; +```php +use Illuminate\Database\Eloquent\Casts\AsCollection; + +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ + 'options' => AsCollection::class, + ]; +} +``` + +If you would like the `AsCollection` cast to instantiate a custom collection class instead of Laravel's base collection class, you may provide the collection class name as a cast argument: + +```php +use App\Collections\OptionCollection; +use Illuminate\Database\Eloquent\Casts\AsCollection; + +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ + 'options' => AsCollection::using(OptionCollection::class), + ]; +} +``` + +The `of` method may be used to indicate collection items should be mapped into a given class via the collection's [mapInto method](/docs/{{version}}/collections#method-mapinto): + +```php +use App\ValueObjects\Option; +use Illuminate\Database\Eloquent\Casts\AsCollection; + +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ + 'options' => AsCollection::of(Option::class) + ]; +} +``` + +When mapping collections to objects, the object should implement the `Illuminate\Contracts\Support\Arrayable` and `JsonSerializable` interfaces to define how their instances should be serialized into the database as JSON: + +```php +name = $data['name']; + $this->value = $data['value']; + $this->isLocked = $data['is_locked']; + } + + /** + * Get the instance as an array. + * + * @return array{name: string, data: string, is_locked: bool} + */ + public function toArray(): array + { + return [ + 'name' => $this->name, + 'value' => $this->value, + 'is_locked' => $this->isLocked, + ]; + } /** - * The attributes that should be cast. + * Specify the data which should be serialized to JSON. * - * @var array + * @return array{name: string, data: string, is_locked: bool} */ - protected $casts = [ - 'options' => AsCollection::class, - ]; + public function jsonSerialize(): array + { + return $this->toArray(); + } +} +``` ### Date Casting -By default, Eloquent will cast the `created_at` and `updated_at` columns to instances of [Carbon](https://github.com/briannesbitt/Carbon), which extends the PHP `DateTime` class and provides an assortment of helpful methods. You may cast additional date attributes by defining additional date casts within your model's `$casts` property array. Typically, dates should be cast using the `datetime` or `immutable_datetime` cast types. +By default, Eloquent will cast the `created_at` and `updated_at` columns to instances of [Carbon](https://github.com/briannesbitt/Carbon), which extends the PHP `DateTime` class and provides an assortment of helpful methods. You may cast additional date attributes by defining additional date casts within your model's `casts` method. Typically, dates should be cast using the `datetime` or `immutable_datetime` cast types. When defining a `date` or `datetime` cast, you may also specify the date's format. This format will be used when the [model is serialized to an array or JSON](/docs/{{version}}/eloquent-serialization): - /** - * The attributes that should be cast. - * - * @var array - */ - protected $casts = [ +```php +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ 'created_at' => 'datetime:Y-m-d', ]; +} +``` When a column is cast as a date, you may set the corresponding model attribute value to a UNIX timestamp, date string (`Y-m-d`), date-time string, or a `DateTime` / `Carbon` instance. The date's value will be correctly converted and stored in your database. You may customize the default serialization format for all of your model's dates by defining a `serializeDate` method on your model. This method does not affect how your dates are formatted for storage in the database: - /** - * Prepare a date for array / JSON serialization. - * - * @param \DateTimeInterface $date - * @return string - */ - protected function serializeDate(DateTimeInterface $date) - { - return $date->format('Y-m-d'); - } +```php +/** + * Prepare a date for array / JSON serialization. + */ +protected function serializeDate(DateTimeInterface $date): string +{ + return $date->format('Y-m-d'); +} +``` To specify the format that should be used when actually storing a model's dates within your database, you should define a `$dateFormat` property on your model: - /** - * The storage format of the model's date columns. - * - * @var string - */ - protected $dateFormat = 'U'; +```php +/** + * The storage format of the model's date columns. + * + * @var string + */ +protected $dateFormat = 'U'; +``` -#### Date Casting, Serialization, & Timezones +#### Date Casting, Serialization, and Timezones -By default, the `date` and `datetime` casts will serialize dates to a UTC ISO-8601 date string (`1986-05-28T21:05:54.000000Z`), regardless of the timezone specified in your application's `timezone` configuration option. You are strongly encouraged to always use this serialization format, as well as to store your application's dates in the UTC timezone by not changing your application's `timezone` configuration option from its default `UTC` value. Consistently using the UTC timezone throughout your application will provide the maximum level of interoperability with other date manipulation libraries written in PHP and JavaScript. +By default, the `date` and `datetime` casts will serialize dates to a UTC ISO-8601 date string (`YYYY-MM-DDTHH:MM:SS.uuuuuuZ`), regardless of the timezone specified in your application's `timezone` configuration option. You are strongly encouraged to always use this serialization format, as well as to store your application's dates in the UTC timezone by not changing your application's `timezone` configuration option from its default `UTC` value. Consistently using the UTC timezone throughout your application will provide the maximum level of interoperability with other date manipulation libraries written in PHP and JavaScript. -If a custom format is applied to the `date` or `datetime` cast, such as `datetime:Y-m-d H:i:s`, the inner timezone of the Carbon instance will be used during date serialization. Typically, this will be the timezone specified in your application's `timezone` configuration option. +If a custom format is applied to the `date` or `datetime` cast, such as `datetime:Y-m-d H:i:s`, the inner timezone of the Carbon instance will be used during date serialization. Typically, this will be the timezone specified in your application's `timezone` configuration option. However, it's important to note that `timestamp` columns such as `created_at` and `updated_at` are exempt from this behavior and are always formatted in UTC, regardless of the application's timezone setting. ### Enum Casting -> {note} Enum casting is only available for PHP 8.1+. - -Eloquent also allows you to cast your attribute values to PHP ["backed" enums](https://www.php.net/manual/en/language.enumerations.backed.php). To accomplish this, you may specify the attribute and enum you wish to cast in your model's `$casts` property array: +Eloquent also allows you to cast your attribute values to PHP [Enums](https://www.php.net/manual/en/language.enumerations.backed.php). To accomplish this, you may specify the attribute and enum you wish to cast in your model's `casts` method: - use App\Enums\ServerStatus; +```php +use App\Enums\ServerStatus; - /** - * The attributes that should be cast. - * - * @var array - */ - protected $casts = [ +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ 'status' => ServerStatus::class, ]; +} +``` Once you have defined the cast on your model, the specified attribute will be automatically cast to and from an enum when you interact with the attribute: - if ($server->status == ServerStatus::provisioned) { - $server->status = ServerStatus::ready; +```php +if ($server->status == ServerStatus::Provisioned) { + $server->status = ServerStatus::Ready; - $server->save(); - } + $server->save(); +} +``` + + +#### Casting Arrays of Enums + +Sometimes you may need your model to store an array of enum values within a single column. To accomplish this, you may utilize the `AsEnumArrayObject` or `AsEnumCollection` casts provided by Laravel: + +```php +use App\Enums\ServerStatus; +use Illuminate\Database\Eloquent\Casts\AsEnumCollection; + +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ + 'statuses' => AsEnumCollection::of(ServerStatus::class), + ]; +} +``` ### Encrypted Casting @@ -440,162 +636,207 @@ The `encrypted` cast will encrypt a model's attribute value using Laravel's buil As the final length of the encrypted text is not predictable and is longer than its plain text counterpart, make sure the associated database column is of `TEXT` type or larger. In addition, since the values are encrypted in the database, you will not be able to query or search encrypted attribute values. + +#### Key Rotation + +As you may know, Laravel encrypts strings using the `key` configuration value specified in your application's `app` configuration file. Typically, this value corresponds to the value of the `APP_KEY` environment variable. If you need to rotate your application's encryption key, you will need to manually re-encrypt your encrypted attributes using the new key. + ### Query Time Casting Sometimes you may need to apply casts while executing a query, such as when selecting a raw value from a table. For example, consider the following query: - use App\Models\Post; - use App\Models\User; - - $users = User::select([ - 'users.*', - 'last_posted_at' => Post::selectRaw('MAX(created_at)') - ->whereColumn('user_id', 'users.id') - ])->get(); +```php +use App\Models\Post; +use App\Models\User; + +$users = User::select([ + 'users.*', + 'last_posted_at' => Post::selectRaw('MAX(created_at)') + ->whereColumn('user_id', 'users.id') +])->get(); +``` The `last_posted_at` attribute on the results of this query will be a simple string. It would be wonderful if we could apply a `datetime` cast to this attribute when executing the query. Thankfully, we may accomplish this using the `withCasts` method: - $users = User::select([ - 'users.*', - 'last_posted_at' => Post::selectRaw('MAX(created_at)') - ->whereColumn('user_id', 'users.id') - ])->withCasts([ - 'last_posted_at' => 'datetime' - ])->get(); +```php +$users = User::select([ + 'users.*', + 'last_posted_at' => Post::selectRaw('MAX(created_at)') + ->whereColumn('user_id', 'users.id') +])->withCasts([ + 'last_posted_at' => 'datetime' +])->get(); +``` ## Custom Casts -Laravel has a variety of built-in, helpful cast types; however, you may occasionally need to define your own cast types. You may accomplish this by defining a class that implements the `CastsAttributes` interface. +Laravel has a variety of built-in, helpful cast types; however, you may occasionally need to define your own cast types. To create a cast, execute the `make:cast` Artisan command. The new cast class will be placed in your `app/Casts` directory: -Classes that implement this interface must define a `get` and `set` method. The `get` method is responsible for transforming a raw value from the database into a cast value, while the `set` method should transform a cast value into a raw value that can be stored in the database. As an example, we will re-implement the built-in `json` cast type as a custom cast type: +```shell +php artisan make:cast AsJson +``` - $attributes + * @return array + */ + public function get( + Model $model, + string $key, + mixed $value, + array $attributes, + ): array { + return json_decode($value, true); } + /** + * Prepare the given value for storage. + * + * @param array $attributes + */ + public function set( + Model $model, + string $key, + mixed $value, + array $attributes, + ): string { + return json_encode($value); + } +} +``` + Once you have defined a custom cast type, you may attach it to a model attribute using its class name: - + */ + protected function casts(): array { - /** - * The attributes that should be cast. - * - * @var array - */ - protected $casts = [ - 'options' => Json::class, + return [ + 'options' => AsJson::class, ]; } +} +``` ### Value Object Casting -You are not limited to casting values to primitive types. You may also cast values to objects. Defining custom casts that cast values to objects is very similar to casting to primitive types; however, the `set` method should return an array of key / value pairs that will be used to set raw, storable values on the model. +You are not limited to casting values to primitive types. You may also cast values to objects. Defining custom casts that cast values to objects is very similar to casting to primitive types; however, if your value object encompasses more than one database column, the `set` method must return an array of key / value pairs that will be used to set raw, storable values on the model. If your value object only affects a single column, you should simply return the storable value. -As an example, we will define a custom cast class that casts multiple model values into a single `Address` value object. We will assume the `Address` value has two public properties: `lineOne` and `lineTwo`: +As an example, we will define a custom cast class that casts multiple model values into a single `Address` value object. We will assume the `Address` value object has two public properties: `lineOne` and `lineTwo`: - $attributes + */ + public function get( + Model $model, + string $key, + mixed $value, + array $attributes, + ): Address { + return new Address( + $attributes['address_line_one'], + $attributes['address_line_two'] + ); + } - return [ - 'address_line_one' => $value->lineOne, - 'address_line_two' => $value->lineTwo, - ]; + /** + * Prepare the given value for storage. + * + * @param array $attributes + * @return array + */ + public function set( + Model $model, + string $key, + mixed $value, + array $attributes, + ): array { + if (! $value instanceof Address) { + throw new InvalidArgumentException('The given value is not an Address instance.'); } + + return [ + 'address_line_one' => $value->lineOne, + 'address_line_two' => $value->lineTwo, + ]; } +} +``` When casting to value objects, any changes made to the value object will automatically be synced back to the model before the model is saved: - use App\Models\User; +```php +use App\Models\User; + +$user = User::find(1); + +$user->address->lineOne = 'Updated Address Value'; - $user = User::find(1); +$user->save(); +``` + +> [!NOTE] +> If you plan to serialize your Eloquent models containing value objects to JSON or arrays, you should implement the `Illuminate\Contracts\Support\Arrayable` and `JsonSerializable` interfaces on the value object. + + +#### Value Object Caching - $user->address->lineOne = 'Updated Address Value'; +When attributes that are cast to value objects are resolved, they are cached by Eloquent. Therefore, the same object instance will be returned if the attribute is accessed again. - $user->save(); +If you would like to disable the object caching behavior of custom cast classes, you may declare a public `withoutObjectCaching` property on your custom cast class: -> {tip} If you plan to serialize your Eloquent models containing value objects to JSON or arrays, you should implement the `Illuminate\Contracts\Support\Arrayable` and `JsonSerializable` interfaces on the value object. +```php +class AsAddress implements CastsAttributes +{ + public bool $withoutObjectCaching = true; + + // ... +} +``` ### Array / JSON Serialization @@ -604,165 +845,219 @@ When an Eloquent model is converted to an array or JSON using the `toArray` and Therefore, you may specify that your custom cast class will be responsible for serializing the value object. To do so, your custom cast class should implement the `Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes` interface. This interface states that your class should contain a `serialize` method which should return the serialized form of your value object: - /** - * Get the serialized representation of the value. - * - * @param \Illuminate\Database\Eloquent\Model $model - * @param string $key - * @param mixed $value - * @param array $attributes - * @return mixed - */ - public function serialize($model, string $key, $value, array $attributes) - { - return (string) $value; - } +```php +/** + * Get the serialized representation of the value. + * + * @param array $attributes + */ +public function serialize( + Model $model, + string $key, + mixed $value, + array $attributes, +): string { + return (string) $value; +} +``` ### Inbound Casting -Occasionally, you may need to write a custom cast that only transforms values that are being set on the model and does not perform any operations when attributes are being retrieved from the model. A classic example of an inbound only cast is a "hashing" cast. Inbound only custom casts should implement the `CastsInboundAttributes` interface, which only requires a `set` method to be defined. +Occasionally, you may need to write a custom cast class that only transforms values that are being set on the model and does not perform any operations when attributes are being retrieved from the model. - algorithm = $algorithm; - } +```php +algorithm) - ? bcrypt($value) - : hash($this->algorithm, $value); - } +namespace App\Casts; + +use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes; +use Illuminate\Database\Eloquent\Model; + +class AsHash implements CastsInboundAttributes +{ + /** + * Create a new cast class instance. + */ + public function __construct( + protected string|null $algorithm = null, + ) {} + + /** + * Prepare the given value for storage. + * + * @param array $attributes + */ + public function set( + Model $model, + string $key, + mixed $value, + array $attributes, + ): string { + return is_null($this->algorithm) + ? bcrypt($value) + : hash($this->algorithm, $value); } +} +``` ### Cast Parameters When attaching a custom cast to a model, cast parameters may be specified by separating them from the class name using a `:` character and comma-delimiting multiple parameters. The parameters will be passed to the constructor of the cast class: - /** - * The attributes that should be cast. - * - * @var array - */ - protected $casts = [ - 'secret' => Hash::class.':sha256', +```php +/** + * Get the attributes that should be cast. + * + * @return array + */ +protected function casts(): array +{ + return [ + 'secret' => AsHash::class.':sha256', ]; +} +``` + + +### Comparing Cast Values + +If you would like to define how two given cast values should be compared to determine if they have been changed, your custom cast class may implement the `Illuminate\Contracts\Database\Eloquent\ComparesCastableAttributes` interface. This allows you to have fine-grained control over which values Eloquent considers changed and thus saves to the database when a model is updated. + +This interface states that your class should contain a `compare` method which should return `true` if the given values are considered equal: + +```php +/** + * Determine if the given values are equal. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $firstValue + * @param mixed $secondValue + * @return bool + */ +public function compare( + Model $model, + string $key, + mixed $firstValue, + mixed $secondValue +): bool { + return $firstValue === $secondValue; +} +``` ### Castables You may want to allow your application's value objects to define their own custom cast classes. Instead of attaching the custom cast class to your model, you may alternatively attach a value object class that implements the `Illuminate\Contracts\Database\Eloquent\Castable` interface: - use App\Models\Address; +```php +use App\ValueObjects\Address; - protected $casts = [ +protected function casts(): array +{ + return [ 'address' => Address::class, ]; +} +``` Objects that implement the `Castable` interface must define a `castUsing` method that returns the class name of the custom caster class that is responsible for casting to and from the `Castable` class: - $arguments + */ + public static function castUsing(array $arguments): string { - /** - * Get the name of the caster class to use when casting from / to this cast target. - * - * @param array $arguments - * @return string - */ - public static function castUsing(array $arguments) - { - return AddressCast::class; - } + return AsAddress::class; } +} +``` -When using `Castable` classes, you may still provide arguments in the `$casts` definition. The arguments will be passed to the `castUsing` method: +When using `Castable` classes, you may still provide arguments in the `casts` method definition. The arguments will be passed to the `castUsing` method: - use App\Models\Address; +```php +use App\ValueObjects\Address; - protected $casts = [ +protected function casts(): array +{ + return [ 'address' => Address::class.':argument', ]; +} +``` #### Castables & Anonymous Cast Classes By combining "castables" with PHP's [anonymous classes](https://www.php.net/manual/en/language.oop5.anonymous.php), you may define a value object and its casting logic as a single castable object. To accomplish this, return an anonymous class from your value object's `castUsing` method. The anonymous class should implement the `CastsAttributes` interface: - $arguments + */ + public static function castUsing(array $arguments): CastsAttributes { - // ... - - /** - * Get the caster class to use when casting from / to this cast target. - * - * @param array $arguments - * @return object|string - */ - public static function castUsing(array $arguments) + return new class implements CastsAttributes { - return new class implements CastsAttributes - { - public function get($model, $key, $value, $attributes) - { - return new Address( - $attributes['address_line_one'], - $attributes['address_line_two'] - ); - } - - public function set($model, $key, $value, $attributes) - { - return [ - 'address_line_one' => $value->lineOne, - 'address_line_two' => $value->lineTwo, - ]; - } - }; - } + public function get( + Model $model, + string $key, + mixed $value, + array $attributes, + ): Address { + return new Address( + $attributes['address_line_one'], + $attributes['address_line_two'] + ); + } + + public function set( + Model $model, + string $key, + mixed $value, + array $attributes, + ): array { + return [ + 'address_line_one' => $value->lineOne, + 'address_line_two' => $value->lineTwo, + ]; + } + }; } +} +``` diff --git a/eloquent-relationships.md b/eloquent-relationships.md index 4cf9c689ada..8bcbe480622 100644 --- a/eloquent-relationships.md +++ b/eloquent-relationships.md @@ -2,41 +2,44 @@ - [Introduction](#introduction) - [Defining Relationships](#defining-relationships) - - [One To One](#one-to-one) - - [One To Many](#one-to-many) - - [One To Many (Inverse) / Belongs To](#one-to-many-inverse) - - [Has One Of Many](#has-one-of-many) + - [One to One / Has One](#one-to-one) + - [One to Many / Has Many](#one-to-many) + - [One to Many (Inverse) / Belongs To](#one-to-many-inverse) + - [Has One of Many](#has-one-of-many) - [Has One Through](#has-one-through) - [Has Many Through](#has-many-through) -- [Many To Many Relationships](#many-to-many) +- [Scoped Relationships](#scoped-relationships) +- [Many to Many Relationships](#many-to-many) - [Retrieving Intermediate Table Columns](#retrieving-intermediate-table-columns) - - [Filtering Queries Via Intermediate Table Columns](#filtering-queries-via-intermediate-table-columns) + - [Filtering Queries via Intermediate Table Columns](#filtering-queries-via-intermediate-table-columns) + - [Ordering Queries via Intermediate Table Columns](#ordering-queries-via-intermediate-table-columns) - [Defining Custom Intermediate Table Models](#defining-custom-intermediate-table-models) - [Polymorphic Relationships](#polymorphic-relationships) - - [One To One](#one-to-one-polymorphic-relations) - - [One To Many](#one-to-many-polymorphic-relations) - - [One Of Many](#one-of-many-polymorphic-relations) - - [Many To Many](#many-to-many-polymorphic-relations) + - [One to One](#one-to-one-polymorphic-relations) + - [One to Many](#one-to-many-polymorphic-relations) + - [One of Many](#one-of-many-polymorphic-relations) + - [Many to Many](#many-to-many-polymorphic-relations) - [Custom Polymorphic Types](#custom-polymorphic-types) - [Dynamic Relationships](#dynamic-relationships) - [Querying Relations](#querying-relations) - - [Relationship Methods Vs. Dynamic Properties](#relationship-methods-vs-dynamic-properties) + - [Relationship Methods vs. Dynamic Properties](#relationship-methods-vs-dynamic-properties) - [Querying Relationship Existence](#querying-relationship-existence) - [Querying Relationship Absence](#querying-relationship-absence) - [Querying Morph To Relationships](#querying-morph-to-relationships) - [Aggregating Related Models](#aggregating-related-models) - [Counting Related Models](#counting-related-models) - [Other Aggregate Functions](#other-aggregate-functions) - - [Counting Related Models On Morph To Relationships](#counting-related-models-on-morph-to-relationships) + - [Counting Related Models on Morph To Relationships](#counting-related-models-on-morph-to-relationships) - [Eager Loading](#eager-loading) - [Constraining Eager Loads](#constraining-eager-loads) - [Lazy Eager Loading](#lazy-eager-loading) + - [Automatic Eager Loading](#automatic-eager-loading) - [Preventing Lazy Loading](#preventing-lazy-loading) -- [Inserting & Updating Related Models](#inserting-and-updating-related-models) +- [Inserting and Updating Related Models](#inserting-and-updating-related-models) - [The `save` Method](#the-save-method) - [The `create` Method](#the-create-method) - [Belongs To Relationships](#updating-belongs-to-relationships) - - [Many To Many Relationships](#updating-many-to-many-relationships) + - [Many to Many Relationships](#updating-many-to-many-relationships) - [Touching Parent Timestamps](#touching-parent-timestamps) @@ -62,163 +65,244 @@ Database tables are often related to one another. For example, a blog post may h Eloquent relationships are defined as methods on your Eloquent model classes. Since relationships also serve as powerful [query builders](/docs/{{version}}/queries), defining relationships as methods provides powerful method chaining and querying capabilities. For example, we may chain additional query constraints on this `posts` relationship: - $user->posts()->where('active', 1)->get(); +```php +$user->posts()->where('active', 1)->get(); +``` But, before diving too deep into using relationships, let's learn how to define each type of relationship supported by Eloquent. -### One To One +### One to One / Has One A one-to-one relationship is a very basic type of database relationship. For example, a `User` model might be associated with one `Phone` model. To define this relationship, we will place a `phone` method on the `User` model. The `phone` method should call the `hasOne` method and return its result. The `hasOne` method is available to your model via the model's `Illuminate\Database\Eloquent\Model` base class: - hasOne(Phone::class); - } + return $this->hasOne(Phone::class); } +} +``` The first argument passed to the `hasOne` method is the name of the related model class. Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model: - $phone = User::find(1)->phone; +```php +$phone = User::find(1)->phone; +``` Eloquent determines the foreign key of the relationship based on the parent model name. In this case, the `Phone` model is automatically assumed to have a `user_id` foreign key. If you wish to override this convention, you may pass a second argument to the `hasOne` method: - return $this->hasOne(Phone::class, 'foreign_key'); +```php +return $this->hasOne(Phone::class, 'foreign_key'); +``` Additionally, Eloquent assumes that the foreign key should have a value matching the primary key column of the parent. In other words, Eloquent will look for the value of the user's `id` column in the `user_id` column of the `Phone` record. If you would like the relationship to use a primary key value other than `id` or your model's `$primaryKey` property, you may pass a third argument to the `hasOne` method: - return $this->hasOne(Phone::class, 'foreign_key', 'local_key'); +```php +return $this->hasOne(Phone::class, 'foreign_key', 'local_key'); +``` -#### Defining The Inverse Of The Relationship +#### Defining the Inverse of the Relationship So, we can access the `Phone` model from our `User` model. Next, let's define a relationship on the `Phone` model that will let us access the user that owns the phone. We can define the inverse of a `hasOne` relationship using the `belongsTo` method: - belongsTo(User::class); - } + return $this->belongsTo(User::class); } +} +``` When invoking the `user` method, Eloquent will attempt to find a `User` model that has an `id` which matches the `user_id` column on the `Phone` model. Eloquent determines the foreign key name by examining the name of the relationship method and suffixing the method name with `_id`. So, in this case, Eloquent assumes that the `Phone` model has a `user_id` column. However, if the foreign key on the `Phone` model is not `user_id`, you may pass a custom key name as the second argument to the `belongsTo` method: - /** - * Get the user that owns the phone. - */ - public function user() - { - return $this->belongsTo(User::class, 'foreign_key'); - } +```php +/** + * Get the user that owns the phone. + */ +public function user(): BelongsTo +{ + return $this->belongsTo(User::class, 'foreign_key'); +} +``` If the parent model does not use `id` as its primary key, or you wish to find the associated model using a different column, you may pass a third argument to the `belongsTo` method specifying the parent table's custom key: - /** - * Get the user that owns the phone. - */ - public function user() - { - return $this->belongsTo(User::class, 'foreign_key', 'owner_key'); - } +```php +/** + * Get the user that owns the phone. + */ +public function user(): BelongsTo +{ + return $this->belongsTo(User::class, 'foreign_key', 'owner_key'); +} +``` -### One To Many +### One to Many / Has Many A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by defining a method on your Eloquent model: - hasMany(Comment::class); - } + return $this->hasMany(Comment::class); } +} +``` Remember, Eloquent will automatically determine the proper foreign key column for the `Comment` model. By convention, Eloquent will take the "snake case" name of the parent model and suffix it with `_id`. So, in this example, Eloquent will assume the foreign key column on the `Comment` model is `post_id`. Once the relationship method has been defined, we can access the [collection](/docs/{{version}}/eloquent-collections) of related comments by accessing the `comments` property. Remember, since Eloquent provides "dynamic relationship properties", we can access relationship methods as if they were defined as properties on the model: - use App\Models\Post; +```php +use App\Models\Post; - $comments = Post::find(1)->comments; +$comments = Post::find(1)->comments; - foreach ($comments as $comment) { - // - } +foreach ($comments as $comment) { + // ... +} +``` Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the `comments` method and continuing to chain conditions onto the query: - $comment = Post::find(1)->comments() - ->where('title', 'foo') - ->first(); +```php +$comment = Post::find(1)->comments() + ->where('title', 'foo') + ->first(); +``` Like the `hasOne` method, you may also override the foreign and local keys by passing additional arguments to the `hasMany` method: - return $this->hasMany(Comment::class, 'foreign_key'); +```php +return $this->hasMany(Comment::class, 'foreign_key'); - return $this->hasMany(Comment::class, 'foreign_key', 'local_key'); +return $this->hasMany(Comment::class, 'foreign_key', 'local_key'); +``` + + +#### Automatically Hydrating Parent Models on Children + +Even when utilizing Eloquent eager loading, "N + 1" query problems can arise if you try to access the parent model from a child model while looping through the child models: + +```php +$posts = Post::with('comments')->get(); + +foreach ($posts as $post) { + foreach ($post->comments as $comment) { + echo $comment->post->title; + } +} +``` + +In the example above, an "N + 1" query problem has been introduced because, even though comments were eager loaded for every `Post` model, Eloquent does not automatically hydrate the parent `Post` on each child `Comment` model. + +If you would like Eloquent to automatically hydrate parent models onto their children, you may invoke the `chaperone` method when defining a `hasMany` relationship: + +```php +hasMany(Comment::class)->chaperone(); + } +} +``` + +Or, if you would like to opt-in to automatic parent hydration at run time, you may invoke the `chaperone` model when eager loading the relationship: + +```php +use App\Models\Post; + +$posts = Post::with([ + 'comments' => fn ($comments) => $comments->chaperone(), +])->get(); +``` -### One To Many (Inverse) / Belongs To +### One to Many (Inverse) / Belongs To Now that we can access all of a post's comments, let's define a relationship to allow a comment to access its parent post. To define the inverse of a `hasMany` relationship, define a relationship method on the child model which calls the `belongsTo` method: - belongsTo(Post::class); - } + return $this->belongsTo(Post::class); } +} +``` Once the relationship has been defined, we can retrieve a comment's parent post by accessing the `post` "dynamic relationship property": - use App\Models\Comment; +```php +use App\Models\Comment; - $comment = Comment::find(1); +$comment = Comment::find(1); - return $comment->post->title; +return $comment->post->title; +``` In the example above, Eloquent will attempt to find a `Post` model that has an `id` which matches the `post_id` column on the `Comment` model. @@ -226,78 +310,100 @@ Eloquent determines the default foreign key name by examining the name of the re However, if the foreign key for your relationship does not follow these conventions, you may pass a custom foreign key name as the second argument to the `belongsTo` method: - /** - * Get the post that owns the comment. - */ - public function post() - { - return $this->belongsTo(Post::class, 'foreign_key'); - } +```php +/** + * Get the post that owns the comment. + */ +public function post(): BelongsTo +{ + return $this->belongsTo(Post::class, 'foreign_key'); +} +``` If your parent model does not use `id` as its primary key, or you wish to find the associated model using a different column, you may pass a third argument to the `belongsTo` method specifying your parent table's custom key: - /** - * Get the post that owns the comment. - */ - public function post() - { - return $this->belongsTo(Post::class, 'foreign_key', 'owner_key'); - } +```php +/** + * Get the post that owns the comment. + */ +public function post(): BelongsTo +{ + return $this->belongsTo(Post::class, 'foreign_key', 'owner_key'); +} +``` #### Default Models The `belongsTo`, `hasOne`, `hasOneThrough`, and `morphOne` relationships allow you to define a default model that will be returned if the given relationship is `null`. This pattern is often referred to as the [Null Object pattern](https://en.wikipedia.org/wiki/Null_Object_pattern) and can help remove conditional checks in your code. In the following example, the `user` relation will return an empty `App\Models\User` model if no user is attached to the `Post` model: - /** - * Get the author of the post. - */ - public function user() - { - return $this->belongsTo(User::class)->withDefault(); - } +```php +/** + * Get the author of the post. + */ +public function user(): BelongsTo +{ + return $this->belongsTo(User::class)->withDefault(); +} +``` To populate the default model with attributes, you may pass an array or closure to the `withDefault` method: - /** - * Get the author of the post. - */ - public function user() - { - return $this->belongsTo(User::class)->withDefault([ - 'name' => 'Guest Author', - ]); - } +```php +/** + * Get the author of the post. + */ +public function user(): BelongsTo +{ + return $this->belongsTo(User::class)->withDefault([ + 'name' => 'Guest Author', + ]); +} - /** - * Get the author of the post. - */ - public function user() - { - return $this->belongsTo(User::class)->withDefault(function ($user, $post) { - $user->name = 'Guest Author'; - }); - } +/** + * Get the author of the post. + */ +public function user(): BelongsTo +{ + return $this->belongsTo(User::class)->withDefault(function (User $user, Post $post) { + $user->name = 'Guest Author'; + }); +} +``` #### Querying Belongs To Relationships When querying for the children of a "belongs to" relationship, you may manually build the `where` clause to retrieve the corresponding Eloquent models: - use App\Models\Post; +```php +use App\Models\Post; - $posts = Post::where('user_id', $user->id)->get(); +$posts = Post::where('user_id', $user->id)->get(); +``` However, you may find it more convenient to use the `whereBelongsTo` method, which will automatically determine the proper relationship and foreign key for the given model: - $posts = Post::whereBelongsTo($user)->get(); +```php +$posts = Post::whereBelongsTo($user)->get(); +``` + +You may also provide a [collection](/docs/{{version}}/eloquent-collections) instance to the `whereBelongsTo` method. When doing so, Laravel will retrieve models that belong to any of the parent models within the collection: + +```php +$users = User::where('vip', true)->get(); + +$posts = Post::whereBelongsTo($users)->get(); +``` By default, Laravel will determine the relationship associated with the given model based on the class name of the model; however, you may specify the relationship name manually by providing it as the second argument to the `whereBelongsTo` method: - $posts = Post::whereBelongsTo($user, 'author')->get(); +```php +$posts = Post::whereBelongsTo($user, 'author')->get(); +``` -### Has One Of Many +### Has One of Many Sometimes a model may have many related models, yet you want to easily retrieve the "latest" or "oldest" related model of the relationship. For example, a `User` model may be related to many `Order` models, but you want to define a convenient way to interact with the most recent order the user has placed. You may accomplish this using the `hasOne` relationship type combined with the `ofMany` methods: @@ -305,7 +411,7 @@ Sometimes a model may have many related models, yet you want to easily retrieve /** * Get the user's most recent order. */ -public function latestOrder() +public function latestOrder(): HasOne { return $this->hasOne(Order::class)->latestOfMany(); } @@ -317,7 +423,7 @@ Likewise, you may define a method to retrieve the "oldest", or first, related mo /** * Get the user's oldest order. */ -public function oldestOrder() +public function oldestOrder(): HasOne { return $this->hasOne(Order::class)->oldestOfMany(); } @@ -331,18 +437,51 @@ For example, using the `ofMany` method, you may retrieve the user's most expensi /** * Get the user's largest order. */ -public function largestOrder() +public function largestOrder(): HasOne { return $this->hasOne(Order::class)->ofMany('price', 'max'); } ``` -> {note} Because PostgreSQL does not support executing the `MAX` function against UUID columns, it is not currently possible to use one-of-many relationships in combination with PostgreSQL UUID columns. +> [!WARNING] +> Because PostgreSQL does not support executing the `MAX` function against UUID columns, it is not currently possible to use one-of-many relationships in combination with PostgreSQL UUID columns. + + +#### Converting "Many" Relationships to Has One Relationships + +Often, when retrieving a single model using the `latestOfMany`, `oldestOfMany`, or `ofMany` methods, you already have a "has many" relationship defined for the same model. For convenience, Laravel allows you to easily convert this relationship into a "has one" relationship by invoking the `one` method on the relationship: + +```php +/** + * Get the user's orders. + */ +public function orders(): HasMany +{ + return $this->hasMany(Order::class); +} + +/** + * Get the user's largest order. + */ +public function largestOrder(): HasOne +{ + return $this->orders()->one()->ofMany('price', 'max'); +} +``` + +You may also use the `one` method to convert `HasManyThrough` relationships to `HasOneThrough` relationships: + +```php +public function latestDeployment(): HasOneThrough +{ + return $this->deployments()->one()->latestOfMany(); +} +``` -#### Advanced Has One Of Many Relationships +#### Advanced Has One of Many Relationships -It is possible to construct more advanced "has one of many" relationships. For example, A `Product` model may have many associated `Price` models that are retained in the system even after new pricing is published. In addition, new pricing data for the product may be able to be published in advance to take effect at a future date via a `published_at` column. +It is possible to construct more advanced "has one of many" relationships. For example, a `Product` model may have many associated `Price` models that are retained in the system even after new pricing is published. In addition, new pricing data for the product may be able to be published in advance to take effect at a future date via a `published_at` column. So, in summary, we need to retrieve the latest published pricing where the published date is not in the future. In addition, if two prices have the same published date, we will prefer the price with the greatest ID. To accomplish this, we must pass an array to the `ofMany` method that contains the sortable columns which determine the latest price. In addition, a closure will be provided as the second argument to the `ofMany` method. This closure will be responsible for adding additional publish date constraints to the relationship query: @@ -350,12 +489,12 @@ So, in summary, we need to retrieve the latest published pricing where the publi /** * Get the current pricing for the product. */ -public function currentPricing() +public function currentPricing(): HasOne { return $this->hasOne(Price::class)->ofMany([ 'published_at' => 'max', 'id' => 'max', - ], function ($query) { + ], function (Builder $query) { $query->where('published_at', '<', now()); }); } @@ -368,128 +507,241 @@ The "has-one-through" relationship defines a one-to-one relationship with anothe For example, in a vehicle repair shop application, each `Mechanic` model may be associated with one `Car` model, and each `Car` model may be associated with one `Owner` model. While the mechanic and the owner have no direct relationship within the database, the mechanic can access the owner _through_ the `Car` model. Let's look at the tables necessary to define this relationship: - mechanics - id - integer - name - string +```text +mechanics + id - integer + name - string - cars - id - integer - model - string - mechanic_id - integer +cars + id - integer + model - string + mechanic_id - integer - owners - id - integer - name - string - car_id - integer +owners + id - integer + name - string + car_id - integer +``` Now that we have examined the table structure for the relationship, let's define the relationship on the `Mechanic` model: - hasOneThrough(Owner::class, Car::class); - } + return $this->hasOneThrough(Owner::class, Car::class); } +} +``` The first argument passed to the `hasOneThrough` method is the name of the final model we wish to access, while the second argument is the name of the intermediate model. +Or, if the relevant relationships have already been defined on all of the models involved in the relationship, you may fluently define a "has-one-through" relationship by invoking the `through` method and supplying the names of those relationships. For example, if the `Mechanic` model has a `cars` relationship and the `Car` model has an `owner` relationship, you may define a "has-one-through" relationship connecting the mechanic and the owner like so: + +```php +// String based syntax... +return $this->through('cars')->has('owner'); + +// Dynamic syntax... +return $this->throughCars()->hasOwner(); +``` + #### Key Conventions Typical Eloquent foreign key conventions will be used when performing the relationship's queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the `hasOneThrough` method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model: - class Mechanic extends Model +```php +class Mechanic extends Model +{ + /** + * Get the car's owner. + */ + public function carOwner(): HasOneThrough { - /** - * Get the car's owner. - */ - public function carOwner() - { - return $this->hasOneThrough( - Owner::class, - Car::class, - 'mechanic_id', // Foreign key on the cars table... - 'car_id', // Foreign key on the owners table... - 'id', // Local key on the mechanics table... - 'id' // Local key on the cars table... - ); - } + return $this->hasOneThrough( + Owner::class, + Car::class, + 'mechanic_id', // Foreign key on the cars table... + 'car_id', // Foreign key on the owners table... + 'id', // Local key on the mechanics table... + 'id' // Local key on the cars table... + ); } +} +``` + +Or, as discussed earlier, if the relevant relationships have already been defined on all of the models involved in the relationship, you may fluently define a "has-one-through" relationship by invoking the `through` method and supplying the names of those relationships. This approach offers the advantage of reusing the key conventions already defined on the existing relationships: + +```php +// String based syntax... +return $this->through('cars')->has('owner'); + +// Dynamic syntax... +return $this->throughCars()->hasOwner(); +``` ### Has Many Through -The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform like [Laravel Vapor](https://vapor.laravel.com). A `Project` model might access many `Deployment` models through an intermediate `Environment` model. Using this example, you could easily gather all deployments for a given project. Let's look at the tables required to define this relationship: +The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform like [Laravel Cloud](https://cloud.laravel.com). An `Application` model might access many `Deployment` models through an intermediate `Environment` model. Using this example, you could easily gather all deployments for a given application. Let's look at the tables required to define this relationship: - projects - id - integer - name - string +```text +applications + id - integer + name - string - environments - id - integer - project_id - integer - name - string +environments + id - integer + application_id - integer + name - string - deployments - id - integer - environment_id - integer - commit_hash - string +deployments + id - integer + environment_id - integer + commit_hash - string +``` -Now that we have examined the table structure for the relationship, let's define the relationship on the `Project` model: +Now that we have examined the table structure for the relationship, let's define the relationship on the `Application` model: - hasManyThrough(Deployment::class, Environment::class); - } + return $this->hasManyThrough(Deployment::class, Environment::class); } +} +``` The first argument passed to the `hasManyThrough` method is the name of the final model we wish to access, while the second argument is the name of the intermediate model. -Though the `Deployment` model's table does not contain a `project_id` column, the `hasManyThrough` relation provides access to a project's deployments via `$project->deployments`. To retrieve these models, Eloquent inspects the `project_id` column on the intermediate `Environment` model's table. After finding the relevant environment IDs, they are used to query the `Deployment` model's table. +Or, if the relevant relationships have already been defined on all of the models involved in the relationship, you may fluently define a "has-many-through" relationship by invoking the `through` method and supplying the names of those relationships. For example, if the `Application` model has a `environments` relationship and the `Environment` model has a `deployments` relationship, you may define a "has-many-through" relationship connecting the application and the deployments like so: + +```php +// String based syntax... +return $this->through('environments')->has('deployments'); + +// Dynamic syntax... +return $this->throughEnvironments()->hasDeployments(); +``` + +Though the `Deployment` model's table does not contain a `application_id` column, the `hasManyThrough` relation provides access to a application's deployments via `$application->deployments`. To retrieve these models, Eloquent inspects the `application_id` column on the intermediate `Environment` model's table. After finding the relevant environment IDs, they are used to query the `Deployment` model's table. #### Key Conventions Typical Eloquent foreign key conventions will be used when performing the relationship's queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the `hasManyThrough` method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model: - class Project extends Model +```php +class Application extends Model +{ + public function deployments(): HasManyThrough { - public function deployments() - { - return $this->hasManyThrough( - Deployment::class, - Environment::class, - 'project_id', // Foreign key on the environments table... - 'environment_id', // Foreign key on the deployments table... - 'id', // Local key on the projects table... - 'id' // Local key on the environments table... - ); - } + return $this->hasManyThrough( + Deployment::class, + Environment::class, + 'application_id', // Foreign key on the environments table... + 'environment_id', // Foreign key on the deployments table... + 'id', // Local key on the applications table... + 'id' // Local key on the environments table... + ); + } +} +``` + +Or, as discussed earlier, if the relevant relationships have already been defined on all of the models involved in the relationship, you may fluently define a "has-many-through" relationship by invoking the `through` method and supplying the names of those relationships. This approach offers the advantage of reusing the key conventions already defined on the existing relationships: + +```php +// String based syntax... +return $this->through('environments')->has('deployments'); + +// Dynamic syntax... +return $this->throughEnvironments()->hasDeployments(); +``` + + +### Scoped Relationships + +It's common to add additional methods to models that constrain relationships. For example, you might add a `featuredPosts` method to a `User` model which constrains the broader `posts` relationship with an additional `where` constraint: + +```php +hasMany(Post::class)->latest(); + } + + /** + * Get the user's featured posts. + */ + public function featuredPosts(): HasMany + { + return $this->posts()->where('featured', true); } +} +``` + +However, if you attempt to create a model via the `featuredPosts` method, its `featured` attribute would not be set to `true`. If you would like to create models via relationship methods and also specify attributes that should be added to all models created via that relationship, you may use the `withAttributes` method when building the relationship query: + +```php +/** + * Get the user's featured posts. + */ +public function featuredPosts(): HasMany +{ + return $this->posts()->withAttributes(['featured' => true]); +} +``` + +The `withAttributes` method will add `where` conditions to the query using the given attributes, and it will also add the given attributes to any models created via the relationship method: + +```php +$post = $user->featuredPosts()->create(['title' => 'Featured Post']); + +$post->featured; // true +``` + +To instruct the `withAttributes` method to not add `where` conditions to the query, you may set the `asConditions` argument to `false`: + +```php +return $this->posts()->withAttributes(['featured' => true], asConditions: false); +``` -## Many To Many Relationships +## Many to Many Relationships Many-to-many relations are slightly more complicated than `hasOne` and `hasMany` relationships. An example of a many-to-many relationship is a user that has many roles and those roles are also shared by other users in the application. For example, a user may be assigned the role of "Author" and "Editor"; however, those roles may also be assigned to other users as well. So, a user has many roles and a role has many users. @@ -500,83 +752,99 @@ To define this relationship, three database tables are needed: `users`, `roles`, Remember, since a role can belong to many users, we cannot simply place a `user_id` column on the `roles` table. This would mean that a role could only belong to a single user. In order to provide support for roles being assigned to multiple users, the `role_user` table is needed. We can summarize the relationship's table structure like so: - users - id - integer - name - string +```text +users + id - integer + name - string - roles - id - integer - name - string +roles + id - integer + name - string - role_user - user_id - integer - role_id - integer +role_user + user_id - integer + role_id - integer +``` #### Model Structure Many-to-many relationships are defined by writing a method that returns the result of the `belongsToMany` method. The `belongsToMany` method is provided by the `Illuminate\Database\Eloquent\Model` base class that is used by all of your application's Eloquent models. For example, let's define a `roles` method on our `User` model. The first argument passed to this method is the name of the related model class: - belongsToMany(Role::class); - } + return $this->belongsToMany(Role::class); } +} +``` Once the relationship is defined, you may access the user's roles using the `roles` dynamic relationship property: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - foreach ($user->roles as $role) { - // - } +foreach ($user->roles as $role) { + // ... +} +``` Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the `roles` method and continuing to chain conditions onto the query: - $roles = User::find(1)->roles()->orderBy('name')->get(); +```php +$roles = User::find(1)->roles()->orderBy('name')->get(); +``` To determine the table name of the relationship's intermediate table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the `belongsToMany` method: - return $this->belongsToMany(Role::class, 'role_user'); +```php +return $this->belongsToMany(Role::class, 'role_user'); +``` In addition to customizing the name of the intermediate table, you may also customize the column names of the keys on the table by passing additional arguments to the `belongsToMany` method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to: - return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id'); +```php +return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id'); +``` -#### Defining The Inverse Of The Relationship +#### Defining the Inverse of the Relationship To define the "inverse" of a many-to-many relationship, you should define a method on the related model which also returns the result of the `belongsToMany` method. To complete our user / role example, let's define the `users` method on the `Role` model: - belongsToMany(User::class); - } + return $this->belongsToMany(User::class); } +} +``` As you can see, the relationship is defined exactly the same as its `User` model counterpart with the exception of referencing the `App\Models\User` model. Since we're reusing the `belongsToMany` method, all of the usual table and key customization options are available when defining the "inverse" of many-to-many relationships. @@ -585,125 +853,164 @@ As you can see, the relationship is defined exactly the same as its `User` model As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our `User` model has many `Role` models that it is related to. After accessing this relationship, we may access the intermediate table using the `pivot` attribute on the models: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - foreach ($user->roles as $role) { - echo $role->pivot->created_at; - } +foreach ($user->roles as $role) { + echo $role->pivot->created_at; +} +``` Notice that each `Role` model we retrieve is automatically assigned a `pivot` attribute. This attribute contains a model representing the intermediate table. By default, only the model keys will be present on the `pivot` model. If your intermediate table contains extra attributes, you must specify them when defining the relationship: - return $this->belongsToMany(Role::class)->withPivot('active', 'created_by'); +```php +return $this->belongsToMany(Role::class)->withPivot('active', 'created_by'); +``` If you would like your intermediate table to have `created_at` and `updated_at` timestamps that are automatically maintained by Eloquent, call the `withTimestamps` method when defining the relationship: - return $this->belongsToMany(Role::class)->withTimestamps(); +```php +return $this->belongsToMany(Role::class)->withTimestamps(); +``` -> {note} Intermediate tables that utilize Eloquent's automatically maintained timestamps are required to have both `created_at` and `updated_at` timestamp columns. +> [!WARNING] +> Intermediate tables that utilize Eloquent's automatically maintained timestamps are required to have both `created_at` and `updated_at` timestamp columns. -#### Customizing The `pivot` Attribute Name +#### Customizing the `pivot` Attribute Name As noted previously, attributes from the intermediate table may be accessed on models via the `pivot` attribute. However, you are free to customize the name of this attribute to better reflect its purpose within your application. For example, if your application contains users that may subscribe to podcasts, you likely have a many-to-many relationship between users and podcasts. If this is the case, you may wish to rename your intermediate table attribute to `subscription` instead of `pivot`. This can be done using the `as` method when defining the relationship: - return $this->belongsToMany(Podcast::class) - ->as('subscription') - ->withTimestamps(); +```php +return $this->belongsToMany(Podcast::class) + ->as('subscription') + ->withTimestamps(); +``` Once the custom intermediate table attribute has been specified, you may access the intermediate table data using the customized name: - $users = User::with('podcasts')->get(); +```php +$users = User::with('podcasts')->get(); - foreach ($users->flatMap->podcasts as $podcast) { - echo $podcast->subscription->created_at; - } +foreach ($users->flatMap->podcasts as $podcast) { + echo $podcast->subscription->created_at; +} +``` -### Filtering Queries Via Intermediate Table Columns +### Filtering Queries via Intermediate Table Columns You can also filter the results returned by `belongsToMany` relationship queries using the `wherePivot`, `wherePivotIn`, `wherePivotNotIn`, `wherePivotBetween`, `wherePivotNotBetween`, `wherePivotNull`, and `wherePivotNotNull` methods when defining the relationship: - return $this->belongsToMany(Role::class) - ->wherePivot('approved', 1); +```php +return $this->belongsToMany(Role::class) + ->wherePivot('approved', 1); + +return $this->belongsToMany(Role::class) + ->wherePivotIn('priority', [1, 2]); + +return $this->belongsToMany(Role::class) + ->wherePivotNotIn('priority', [1, 2]); + +return $this->belongsToMany(Podcast::class) + ->as('subscriptions') + ->wherePivotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); + +return $this->belongsToMany(Podcast::class) + ->as('subscriptions') + ->wherePivotNotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); + +return $this->belongsToMany(Podcast::class) + ->as('subscriptions') + ->wherePivotNull('expired_at'); - return $this->belongsToMany(Role::class) - ->wherePivotIn('priority', [1, 2]); +return $this->belongsToMany(Podcast::class) + ->as('subscriptions') + ->wherePivotNotNull('expired_at'); +``` - return $this->belongsToMany(Role::class) - ->wherePivotNotIn('priority', [1, 2]); +The `wherePivot` adds a where clause constraint to the query, but does not add the specified value when creating new models via the defined relationship. If you need to both query and create relationships with a particular pivot value, you may use the `withPivotValue` method: - return $this->belongsToMany(Podcast::class) - ->as('subscriptions') - ->wherePivotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); +```php +return $this->belongsToMany(Role::class) + ->withPivotValue('approved', 1); +``` - return $this->belongsToMany(Podcast::class) - ->as('subscriptions') - ->wherePivotNotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); + +### Ordering Queries via Intermediate Table Columns - return $this->belongsToMany(Podcast::class) - ->as('subscriptions') - ->wherePivotNull('expired_at'); +You can order the results returned by `belongsToMany` relationship queries using the `orderByPivot` method. In the following example, we will retrieve all of the latest badges for the user: - return $this->belongsToMany(Podcast::class) - ->as('subscriptions') - ->wherePivotNotNull('expired_at'); +```php +return $this->belongsToMany(Badge::class) + ->where('rank', 'gold') + ->orderByPivot('created_at', 'desc'); +``` ### Defining Custom Intermediate Table Models -If you would like to define a custom model to represent the intermediate table of your many-to-many relationship, you may call the `using` method when defining the relationship. Custom pivot models give you the opportunity to define additional methods on the pivot model. +If you would like to define a custom model to represent the intermediate table of your many-to-many relationship, you may call the `using` method when defining the relationship. Custom pivot models give you the opportunity to define additional behavior on the pivot model, such as methods and casts. Custom many-to-many pivot models should extend the `Illuminate\Database\Eloquent\Relations\Pivot` class while custom polymorphic many-to-many pivot models should extend the `Illuminate\Database\Eloquent\Relations\MorphPivot` class. For example, we may define a `Role` model which uses a custom `RoleUser` pivot model: - belongsToMany(User::class)->using(RoleUser::class); - } + return $this->belongsToMany(User::class)->using(RoleUser::class); } +} +``` When defining the `RoleUser` model, you should extend the `Illuminate\Database\Eloquent\Relations\Pivot` class: - {note} Pivot models may not use the `SoftDeletes` trait. If you need to soft delete pivot records consider converting your pivot model to an actual Eloquent model. +> [!WARNING] +> Pivot models may not use the `SoftDeletes` trait. If you need to soft delete pivot records consider converting your pivot model to an actual Eloquent model. -#### Custom Pivot Models And Incrementing IDs +#### Custom Pivot Models and Incrementing IDs If you have defined a many-to-many relationship that uses a custom pivot model, and that pivot model has an auto-incrementing primary key, you should ensure your custom pivot model class defines an `incrementing` property that is set to `true`. - /** - * Indicates if the IDs are auto-incrementing. - * - * @var bool - */ - public $incrementing = true; +```php +/** + * Indicates if the IDs are auto-incrementing. + * + * @var bool + */ +public $incrementing = true; +``` ## Polymorphic Relationships @@ -711,26 +1018,28 @@ If you have defined a many-to-many relationship that uses a custom pivot model, A polymorphic relationship allows the child model to belong to more than one type of model using a single association. For example, imagine you are building an application that allows users to share blog posts and videos. In such an application, a `Comment` model might belong to both the `Post` and `Video` models. -### One To One (Polymorphic) +### One to One (Polymorphic) #### Table Structure A one-to-one polymorphic relation is similar to a typical one-to-one relation; however, the child model can belong to more than one type of model using a single association. For example, a blog `Post` and a `User` may share a polymorphic relation to an `Image` model. Using a one-to-one polymorphic relation allows you to have a single table of unique images that may be associated with posts and users. First, let's examine the table structure: - posts - id - integer - name - string +```text +posts + id - integer + name - string - users - id - integer - name - string +users + id - integer + name - string - images - id - integer - url - string - imageable_id - integer - imageable_type - string +images + id - integer + url - string + imageable_id - integer + imageable_type - string +``` Note the `imageable_id` and `imageable_type` columns on the `images` table. The `imageable_id` column will contain the ID value of the post or user, while the `imageable_type` column will contain the class name of the parent model. The `imageable_type` column is used by Eloquent to determine which "type" of parent model to return when accessing the `imageable` relation. In this case, the column would contain either `App\Models\Post` or `App\Models\User`. @@ -739,63 +1048,76 @@ Note the `imageable_id` and `imageable_type` columns on the `images` table. The Next, let's examine the model definitions needed to build this relationship: - morphTo(); - } + return $this->morphTo(); } +} + +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\MorphOne; - class Post extends Model +class Post extends Model +{ + /** + * Get the post's image. + */ + public function image(): MorphOne { - /** - * Get the post's image. - */ - public function image() - { - return $this->morphOne(Image::class, 'imageable'); - } + return $this->morphOne(Image::class, 'imageable'); } +} + +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\MorphOne; - class User extends Model +class User extends Model +{ + /** + * Get the user's image. + */ + public function image(): MorphOne { - /** - * Get the user's image. - */ - public function image() - { - return $this->morphOne(Image::class, 'imageable'); - } + return $this->morphOne(Image::class, 'imageable'); } +} +``` -#### Retrieving The Relationship +#### Retrieving the Relationship Once your database table and models are defined, you may access the relationships via your models. For example, to retrieve the image for a post, we can access the `image` dynamic relationship property: - use App\Models\Post; +```php +use App\Models\Post; - $post = Post::find(1); +$post = Post::find(1); - $image = $post->image; +$image = $post->image; +``` You may retrieve the parent of the polymorphic model by accessing the name of the method that performs the call to `morphTo`. In this case, that is the `imageable` method on the `Image` model. So, we will access that method as a dynamic relationship property: - use App\Models\Image; +```php +use App\Models\Image; - $image = Image::find(1); +$image = Image::find(1); - $imageable = $image->imageable; +$imageable = $image->imageable; +``` The `imageable` relation on the `Image` model will return either a `Post` or `User` instance, depending on which type of model owns the image. @@ -804,107 +1126,166 @@ The `imageable` relation on the `Image` model will return either a `Post` or `Us If necessary, you may specify the name of the "id" and "type" columns utilized by your polymorphic child model. If you do so, ensure that you always pass the name of the relationship as the first argument to the `morphTo` method. Typically, this value should match the method name, so you may use PHP's `__FUNCTION__` constant: - /** - * Get the model that the image belongs to. - */ - public function imageable() - { - return $this->morphTo(__FUNCTION__, 'imageable_type', 'imageable_id'); - } +```php +/** + * Get the model that the image belongs to. + */ +public function imageable(): MorphTo +{ + return $this->morphTo(__FUNCTION__, 'imageable_type', 'imageable_id'); +} +``` -### One To Many (Polymorphic) +### One to Many (Polymorphic) #### Table Structure A one-to-many polymorphic relation is similar to a typical one-to-many relation; however, the child model can belong to more than one type of model using a single association. For example, imagine users of your application can "comment" on posts and videos. Using polymorphic relationships, you may use a single `comments` table to contain comments for both posts and videos. First, let's examine the table structure required to build this relationship: - posts - id - integer - title - string - body - text - - videos - id - integer - title - string - url - string - - comments - id - integer - body - text - commentable_id - integer - commentable_type - string +```text +posts + id - integer + title - string + body - text + +videos + id - integer + title - string + url - string + +comments + id - integer + body - text + commentable_id - integer + commentable_type - string +``` #### Model Structure Next, let's examine the model definitions needed to build this relationship: - morphTo(); - } + return $this->morphTo(); } +} + +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\MorphMany; - class Post extends Model +class Post extends Model +{ + /** + * Get all of the post's comments. + */ + public function comments(): MorphMany { - /** - * Get all of the post's comments. - */ - public function comments() - { - return $this->morphMany(Comment::class, 'commentable'); - } + return $this->morphMany(Comment::class, 'commentable'); } +} + +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\MorphMany; - class Video extends Model +class Video extends Model +{ + /** + * Get all of the video's comments. + */ + public function comments(): MorphMany { - /** - * Get all of the video's comments. - */ - public function comments() - { - return $this->morphMany(Comment::class, 'commentable'); - } + return $this->morphMany(Comment::class, 'commentable'); } +} +``` -#### Retrieving The Relationship +#### Retrieving the Relationship Once your database table and models are defined, you may access the relationships via your model's dynamic relationship properties. For example, to access all of the comments for a post, we can use the `comments` dynamic property: - use App\Models\Post; +```php +use App\Models\Post; - $post = Post::find(1); +$post = Post::find(1); - foreach ($post->comments as $comment) { - // - } +foreach ($post->comments as $comment) { + // ... +} +``` You may also retrieve the parent of a polymorphic child model by accessing the name of the method that performs the call to `morphTo`. In this case, that is the `commentable` method on the `Comment` model. So, we will access that method as a dynamic relationship property in order to access the comment's parent model: - use App\Models\Comment; +```php +use App\Models\Comment; - $comment = Comment::find(1); +$comment = Comment::find(1); - $commentable = $comment->commentable; +$commentable = $comment->commentable; +``` The `commentable` relation on the `Comment` model will return either a `Post` or `Video` instance, depending on which type of model is the comment's parent. + +#### Automatically Hydrating Parent Models on Children + +Even when utilizing Eloquent eager loading, "N + 1" query problems can arise if you try to access the parent model from a child model while looping through the child models: + +```php +$posts = Post::with('comments')->get(); + +foreach ($posts as $post) { + foreach ($post->comments as $comment) { + echo $comment->commentable->title; + } +} +``` + +In the example above, an "N + 1" query problem has been introduced because, even though comments were eager loaded for every `Post` model, Eloquent does not automatically hydrate the parent `Post` on each child `Comment` model. + +If you would like Eloquent to automatically hydrate parent models onto their children, you may invoke the `chaperone` method when defining a `morphMany` relationship: + +```php +class Post extends Model +{ + /** + * Get all of the post's comments. + */ + public function comments(): MorphMany + { + return $this->morphMany(Comment::class, 'commentable')->chaperone(); + } +} +``` + +Or, if you would like to opt-in to automatic parent hydration at run time, you may invoke the `chaperone` model when eager loading the relationship: + +```php +use App\Models\Post; + +$posts = Post::with([ + 'comments' => fn ($comments) => $comments->chaperone(), +])->get(); +``` + -### One Of Many (Polymorphic) +### One of Many (Polymorphic) Sometimes a model may have many related models, yet you want to easily retrieve the "latest" or "oldest" related model of the relationship. For example, a `User` model may be related to many `Image` models, but you want to define a convenient way to interact with the most recent image the user has uploaded. You may accomplish this using the `morphOne` relationship type combined with the `ofMany` methods: @@ -912,7 +1293,7 @@ Sometimes a model may have many related models, yet you want to easily retrieve /** * Get the user's most recent image. */ -public function latestImage() +public function latestImage(): MorphOne { return $this->morphOne(Image::class, 'imageable')->latestOfMany(); } @@ -924,7 +1305,7 @@ Likewise, you may define a method to retrieve the "oldest", or first, related mo /** * Get the user's oldest image. */ -public function oldestImage() +public function oldestImage(): MorphOne { return $this->morphOne(Image::class, 'imageable')->oldestOfMany(); } @@ -938,40 +1319,44 @@ For example, using the `ofMany` method, you may retrieve the user's most "liked" /** * Get the user's most popular image. */ -public function bestImage() +public function bestImage(): MorphOne { return $this->morphOne(Image::class, 'imageable')->ofMany('likes', 'max'); } ``` -> {tip} It is possible to construct more advanced "one of many" relationships. For more information, please consult the [has one of many documentation](#advanced-has-one-of-many-relationships). +> [!NOTE] +> It is possible to construct more advanced "one of many" relationships. For more information, please consult the [has one of many documentation](#advanced-has-one-of-many-relationships). -### Many To Many (Polymorphic) +### Many to Many (Polymorphic) #### Table Structure Many-to-many polymorphic relations are slightly more complicated than "morph one" and "morph many" relationships. For example, a `Post` model and `Video` model could share a polymorphic relation to a `Tag` model. Using a many-to-many polymorphic relation in this situation would allow your application to have a single table of unique tags that may be associated with posts or videos. First, let's examine the table structure required to build this relationship: - posts - id - integer - name - string +```text +posts + id - integer + name - string - videos - id - integer - name - string +videos + id - integer + name - string - tags - id - integer - name - string +tags + id - integer + name - string - taggables - tag_id - integer - taggable_id - integer - taggable_type - string +taggables + tag_id - integer + taggable_id - integer + taggable_type - string +``` -> {tip} Before diving into polymorphic many-to-many relationships, you may benefit from reading the documentation on typical [many-to-many relationships](#many-to-many). +> [!NOTE] +> Before diving into polymorphic many-to-many relationships, you may benefit from reading the documentation on typical [many-to-many relationships](#many-to-many). #### Model Structure @@ -980,81 +1365,91 @@ Next, we're ready to define the relationships on the models. The `Post` and `Vid The `morphToMany` method accepts the name of the related model as well as the "relationship name". Based on the name we assigned to our intermediate table name and the keys it contains, we will refer to the relationship as "taggable": - morphToMany(Tag::class, 'taggable'); - } + return $this->morphToMany(Tag::class, 'taggable'); } +} +``` -#### Defining The Inverse Of The Relationship +#### Defining the Inverse of the Relationship Next, on the `Tag` model, you should define a method for each of its possible parent models. So, in this example, we will define a `posts` method and a `videos` method. Both of these methods should return the result of the `morphedByMany` method. The `morphedByMany` method accepts the name of the related model as well as the "relationship name". Based on the name we assigned to our intermediate table name and the keys it contains, we will refer to the relationship as "taggable": - morphedByMany(Post::class, 'taggable'); - } + return $this->morphedByMany(Post::class, 'taggable'); + } - /** - * Get all of the videos that are assigned this tag. - */ - public function videos() - { - return $this->morphedByMany(Video::class, 'taggable'); - } + /** + * Get all of the videos that are assigned this tag. + */ + public function videos(): MorphToMany + { + return $this->morphedByMany(Video::class, 'taggable'); } +} +``` -#### Retrieving The Relationship +#### Retrieving the Relationship Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the tags for a post, you may use the `tags` dynamic relationship property: - use App\Models\Post; +```php +use App\Models\Post; - $post = Post::find(1); +$post = Post::find(1); - foreach ($post->tags as $tag) { - // - } +foreach ($post->tags as $tag) { + // ... +} +``` You may retrieve the parent of a polymorphic relation from the polymorphic child model by accessing the name of the method that performs the call to `morphedByMany`. In this case, that is the `posts` or `videos` methods on the `Tag` model: - use App\Models\Tag; +```php +use App\Models\Tag; - $tag = Tag::find(1); +$tag = Tag::find(1); - foreach ($tag->posts as $post) { - // - } +foreach ($tag->posts as $post) { + // ... +} - foreach ($tag->videos as $video) { - // - } +foreach ($tag->videos as $video) { + // ... +} +``` ### Custom Polymorphic Types @@ -1063,24 +1458,29 @@ By default, Laravel will use the fully qualified class name to store the "type" For example, instead of using the model names as the "type", we may use simple strings such as `post` and `video`. By doing so, the polymorphic "type" column values in our database will remain valid even if the models are renamed: - use Illuminate\Database\Eloquent\Relations\Relation; +```php +use Illuminate\Database\Eloquent\Relations\Relation; - Relation::enforceMorphMap([ - 'post' => 'App\Models\Post', - 'video' => 'App\Models\Video', - ]); +Relation::enforceMorphMap([ + 'post' => 'App\Models\Post', + 'video' => 'App\Models\Video', +]); +``` You may call the `enforceMorphMap` method in the `boot` method of your `App\Providers\AppServiceProvider` class or create a separate service provider if you wish. You may determine the morph alias of a given model at runtime using the model's `getMorphClass` method. Conversely, you may determine the fully-qualified class name associated with a morph alias using the `Relation::getMorphedModel` method: - use Illuminate\Database\Eloquent\Relations\Relation; +```php +use Illuminate\Database\Eloquent\Relations\Relation; - $alias = $post->getMorphClass(); +$alias = $post->getMorphClass(); - $class = Relation::getMorphedModel($alias); +$class = Relation::getMorphedModel($alias); +``` -> {note} When adding a "morph map" to your existing application, every morphable `*_type` column value in your database that still contains a fully-qualified class will need to be converted to its "map" name. +> [!WARNING] +> When adding a "morph map" to your existing application, every morphable `*_type` column value in your database that still contains a fully-qualified class will need to be converted to its "map" name. ### Dynamic Relationships @@ -1089,14 +1489,17 @@ You may use the `resolveRelationUsing` method to define relations between Eloque The `resolveRelationUsing` method accepts the desired relationship name as its first argument. The second argument passed to the method should be a closure that accepts the model instance and returns a valid Eloquent relationship definition. Typically, you should configure dynamic relationships within the boot method of a [service provider](/docs/{{version}}/providers): - use App\Models\Order; - use App\Models\Customer; +```php +use App\Models\Order; +use App\Models\Customer; - Order::resolveRelationUsing('customer', function ($orderModel) { - return $orderModel->belongsTo(Customer::class, 'customer_id'); - }); +Order::resolveRelationUsing('customer', function (Order $orderModel) { + return $orderModel->belongsTo(Customer::class, 'customer_id'); +}); +``` -> {note} When defining dynamic relationships, always provide explicit key name arguments to the Eloquent relationship methods. +> [!WARNING] +> When defining dynamic relationships, always provide explicit key name arguments to the Eloquent relationship methods. ## Querying Relations @@ -1105,30 +1508,35 @@ Since all Eloquent relationships are defined via methods, you may call those met For example, imagine a blog application in which a `User` model has many associated `Post` models: - hasMany(Post::class); - } + return $this->hasMany(Post::class); } +} +``` You may query the `posts` relationship and add additional constraints to the relationship like so: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $user->posts()->where('active', 1)->get(); +$user->posts()->where('active', 1)->get(); +``` You are able to use any of the Laravel [query builder's](/docs/{{version}}/queries) methods on the relationship, so be sure to explore the query builder documentation to learn about all of the methods that are available to you. @@ -1137,12 +1545,14 @@ You are able to use any of the Laravel [query builder's](/docs/{{version}}/queri As demonstrated in the example above, you are free to add additional constraints to relationships when querying them. However, use caution when chaining `orWhere` clauses onto a relationship, as the `orWhere` clauses will be logically grouped at the same level as the relationship constraint: - $user->posts() - ->where('active', 1) - ->orWhere('votes', '>=', 100) - ->get(); +```php +$user->posts() + ->where('active', 1) + ->orWhere('votes', '>=', 100) + ->get(); +``` -The example above will generate the following SQL. As you can see, the `or` clause instructs the query to return _any_ user with greater than 100 votes. The query is no longer constrained to a specific user: +The example above will generate the following SQL. As you can see, the `or` clause instructs the query to return _any_ post with greater than 100 votes. The query is no longer constrained to a specific user: ```sql select * @@ -1152,14 +1562,16 @@ where user_id = ? and active = 1 or votes >= 100 In most situations, you should use [logical groups](/docs/{{version}}/queries#logical-grouping) to group the conditional checks between parentheses: - use Illuminate\Database\Eloquent\Builder; - - $user->posts() - ->where(function (Builder $query) { - return $query->where('active', 1) - ->orWhere('votes', '>=', 100); - }) - ->get(); +```php +use Illuminate\Database\Eloquent\Builder; + +$user->posts() + ->where(function (Builder $query) { + return $query->where('active', 1) + ->orWhere('votes', '>=', 100); + }) + ->get(); +``` The example above will produce the following SQL. Note that the logical grouping has properly grouped the constraints and the query remains constrained to a specific user: @@ -1170,17 +1582,19 @@ where user_id = ? and (active = 1 or votes >= 100) ``` -### Relationship Methods Vs. Dynamic Properties +### Relationship Methods vs. Dynamic Properties If you do not need to add additional constraints to an Eloquent relationship query, you may access the relationship as if it were a property. For example, continuing to use our `User` and `Post` example models, we may access all of a user's posts like so: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - foreach ($user->posts as $post) { - // - } +foreach ($user->posts as $post) { + // ... +} +``` Dynamic relationship properties perform "lazy loading", meaning they will only load their relationship data when you actually access them. Because of this, developers often use [eager loading](#eager-loading) to pre-load relationships they know will be accessed after loading the model. Eager loading provides a significant reduction in SQL queries that must be executed to load a model's relations. @@ -1189,129 +1603,179 @@ Dynamic relationship properties perform "lazy loading", meaning they will only l When retrieving model records, you may wish to limit your results based on the existence of a relationship. For example, imagine you want to retrieve all blog posts that have at least one comment. To do so, you may pass the name of the relationship to the `has` and `orHas` methods: - use App\Models\Post; +```php +use App\Models\Post; - // Retrieve all posts that have at least one comment... - $posts = Post::has('comments')->get(); +// Retrieve all posts that have at least one comment... +$posts = Post::has('comments')->get(); +``` You may also specify an operator and count value to further customize the query: - // Retrieve all posts that have three or more comments... - $posts = Post::has('comments', '>=', 3)->get(); +```php +// Retrieve all posts that have three or more comments... +$posts = Post::has('comments', '>=', 3)->get(); +``` Nested `has` statements may be constructed using "dot" notation. For example, you may retrieve all posts that have at least one comment that has at least one image: - // Retrieve posts that have at least one comment with images... - $posts = Post::has('comments.images')->get(); +```php +// Retrieve posts that have at least one comment with images... +$posts = Post::has('comments.images')->get(); +``` If you need even more power, you may use the `whereHas` and `orWhereHas` methods to define additional query constraints on your `has` queries, such as inspecting the content of a comment: - use Illuminate\Database\Eloquent\Builder; +```php +use Illuminate\Database\Eloquent\Builder; + +// Retrieve posts with at least one comment containing words like code%... +$posts = Post::whereHas('comments', function (Builder $query) { + $query->where('content', 'like', 'code%'); +})->get(); + +// Retrieve posts with at least ten comments containing words like code%... +$posts = Post::whereHas('comments', function (Builder $query) { + $query->where('content', 'like', 'code%'); +}, '>=', 10)->get(); +``` + +> [!WARNING] +> Eloquent does not currently support querying for relationship existence across databases. The relationships must exist within the same database. + + +#### Many to Many Relationship Existence Queries + +The `whereAttachedTo` method may be used to query for models that have a many to many attachment to a model or collection of models: + +```php +$users = User::whereAttachedTo($role)->get(); +``` - // Retrieve posts with at least one comment containing words like code%... - $posts = Post::whereHas('comments', function (Builder $query) { - $query->where('content', 'like', 'code%'); - })->get(); +You may also provide a [collection](/docs/{{version}}/eloquent-collections) instance to the `whereAttachedTo` method. When doing so, Laravel will retrieve models that are attached to any of the models within the collection: - // Retrieve posts with at least ten comments containing words like code%... - $posts = Post::whereHas('comments', function (Builder $query) { - $query->where('content', 'like', 'code%'); - }, '>=', 10)->get(); +```php +$tags = Tag::whereLike('name', '%laravel%')->get(); -> {note} Eloquent does not currently support querying for relationship existence across databases. The relationships must exist within the same database. +$posts = Post::whereAttachedTo($tags)->get(); +``` #### Inline Relationship Existence Queries -If you would like to query for a relationship's existence with a single, simple where condition attached to the relationship query, you may find it more convenient to use the `whereRelation` and `whereMorphRelation` methods. For example, we may query for all posts that have unapproved comments: +If you would like to query for a relationship's existence with a single, simple where condition attached to the relationship query, you may find it more convenient to use the `whereRelation`, `orWhereRelation`, `whereMorphRelation`, and `orWhereMorphRelation` methods. For example, we may query for all posts that have unapproved comments: - use App\Models\Post; +```php +use App\Models\Post; - $posts = Post::whereRelation('comments', 'is_approved', false)->get(); +$posts = Post::whereRelation('comments', 'is_approved', false)->get(); +``` Of course, like calls to the query builder's `where` method, you may also specify an operator: - $posts = Post::whereRelation( - 'comments', 'created_at', '>=', now()->subHour() - )->get(); +```php +$posts = Post::whereRelation( + 'comments', 'created_at', '>=', now()->subHour() +)->get(); +``` ### Querying Relationship Absence When retrieving model records, you may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that **don't** have any comments. To do so, you may pass the name of the relationship to the `doesntHave` and `orDoesntHave` methods: - use App\Models\Post; +```php +use App\Models\Post; - $posts = Post::doesntHave('comments')->get(); +$posts = Post::doesntHave('comments')->get(); +``` If you need even more power, you may use the `whereDoesntHave` and `orWhereDoesntHave` methods to add additional query constraints to your `doesntHave` queries, such as inspecting the content of a comment: - use Illuminate\Database\Eloquent\Builder; +```php +use Illuminate\Database\Eloquent\Builder; - $posts = Post::whereDoesntHave('comments', function (Builder $query) { - $query->where('content', 'like', 'code%'); - })->get(); +$posts = Post::whereDoesntHave('comments', function (Builder $query) { + $query->where('content', 'like', 'code%'); +})->get(); +``` -You may use "dot" notation to execute a query against a nested relationship. For example, the following query will retrieve all posts that do not have comments; however, posts that have comments from authors that are not banned will be included in the results: +You may use "dot" notation to execute a query against a nested relationship. For example, the following query will retrieve all posts that do not have comments as well as posts that have comments where none of the comments are from banned users: - use Illuminate\Database\Eloquent\Builder; +```php +use Illuminate\Database\Eloquent\Builder; - $posts = Post::whereDoesntHave('comments.author', function (Builder $query) { - $query->where('banned', 0); - })->get(); +$posts = Post::whereDoesntHave('comments.author', function (Builder $query) { + $query->where('banned', 1); +})->get(); +``` ### Querying Morph To Relationships -To query the existence of "morph to" relationships, you may use the `whereHasMorph` and `whereDoesntHaveMorph` methods. These methods accept the name of the relationship as their first argument. Next, the methods accept the names of the related models that you wish to include in the query. Finally, you may provide a closure which customizes the relationship query: +To query the existence of "morph to" relationships, you may use the `whereHasMorph` and `whereDoesntHaveMorph` methods. These methods accept the name of the relationship as their first argument. Next, the methods accept the names of the related models that you wish to include in the query. Finally, you may provide a closure which customizes the relationship query: + +```php +use App\Models\Comment; +use App\Models\Post; +use App\Models\Video; +use Illuminate\Database\Eloquent\Builder; + +// Retrieve comments associated to posts or videos with a title like code%... +$comments = Comment::whereHasMorph( + 'commentable', + [Post::class, Video::class], + function (Builder $query) { + $query->where('title', 'like', 'code%'); + } +)->get(); + +// Retrieve comments associated to posts with a title not like code%... +$comments = Comment::whereDoesntHaveMorph( + 'commentable', + Post::class, + function (Builder $query) { + $query->where('title', 'like', 'code%'); + } +)->get(); +``` + +You may occasionally need to add query constraints based on the "type" of the related polymorphic model. The closure passed to the `whereHasMorph` method may receive a `$type` value as its second argument. This argument allows you to inspect the "type" of the query that is being built: - use App\Models\Comment; - use App\Models\Post; - use App\Models\Video; - use Illuminate\Database\Eloquent\Builder; - - // Retrieve comments associated to posts or videos with a title like code%... - $comments = Comment::whereHasMorph( - 'commentable', - [Post::class, Video::class], - function (Builder $query) { - $query->where('title', 'like', 'code%'); - } - )->get(); - - // Retrieve comments associated to posts with a title not like code%... - $comments = Comment::whereDoesntHaveMorph( - 'commentable', - Post::class, - function (Builder $query) { - $query->where('title', 'like', 'code%'); - } - )->get(); +```php +use Illuminate\Database\Eloquent\Builder; -You may occasionally need to add query constraints based on the "type" of the related polymorphic model. The closure passed to the `whereHasMorph` method may receive a `$type` value as its second argument. This argument allows you to inspect the "type" of the query that is being built: +$comments = Comment::whereHasMorph( + 'commentable', + [Post::class, Video::class], + function (Builder $query, string $type) { + $column = $type === Post::class ? 'content' : 'title'; - use Illuminate\Database\Eloquent\Builder; + $query->where($column, 'like', 'code%'); + } +)->get(); +``` - $comments = Comment::whereHasMorph( - 'commentable', - [Post::class, Video::class], - function (Builder $query, $type) { - $column = $type === Post::class ? 'content' : 'title'; +Sometimes you may want to query for the children of a "morph to" relationship's parent. You may accomplish this using the `whereMorphedTo` and `whereNotMorphedTo` methods, which will automatically determine the proper morph type mapping for the given model. These methods accept the name of the `morphTo` relationship as their first argument and the related parent model as their second argument: - $query->where($column, 'like', 'code%'); - } - )->get(); +```php +$comments = Comment::whereMorphedTo('commentable', $post) + ->orWhereMorphedTo('commentable', $video) + ->get(); +``` #### Querying All Related Models Instead of passing an array of possible polymorphic models, you may provide `*` as a wildcard value. This will instruct Laravel to retrieve all of the possible polymorphic types from the database. Laravel will execute an additional query in order to perform this operation: - use Illuminate\Database\Eloquent\Builder; +```php +use Illuminate\Database\Eloquent\Builder; - $comments = Comment::whereHasMorph('commentable', '*', function (Builder $query) { - $query->where('title', 'like', 'foo%'); - })->get(); +$comments = Comment::whereHasMorph('commentable', '*', function (Builder $query) { + $query->where('title', 'like', 'foo%'); +})->get(); +``` ## Aggregating Related Models @@ -1321,98 +1785,118 @@ Instead of passing an array of possible polymorphic models, you may provide `*` Sometimes you may want to count the number of related models for a given relationship without actually loading the models. To accomplish this, you may use the `withCount` method. The `withCount` method will place a `{relation}_count` attribute on the resulting models: - use App\Models\Post; +```php +use App\Models\Post; - $posts = Post::withCount('comments')->get(); +$posts = Post::withCount('comments')->get(); - foreach ($posts as $post) { - echo $post->comments_count; - } +foreach ($posts as $post) { + echo $post->comments_count; +} +``` By passing an array to the `withCount` method, you may add the "counts" for multiple relations as well as add additional constraints to the queries: - use Illuminate\Database\Eloquent\Builder; +```php +use Illuminate\Database\Eloquent\Builder; - $posts = Post::withCount(['votes', 'comments' => function (Builder $query) { - $query->where('content', 'like', 'code%'); - }])->get(); +$posts = Post::withCount(['votes', 'comments' => function (Builder $query) { + $query->where('content', 'like', 'code%'); +}])->get(); - echo $posts[0]->votes_count; - echo $posts[0]->comments_count; +echo $posts[0]->votes_count; +echo $posts[0]->comments_count; +``` You may also alias the relationship count result, allowing multiple counts on the same relationship: - use Illuminate\Database\Eloquent\Builder; +```php +use Illuminate\Database\Eloquent\Builder; - $posts = Post::withCount([ - 'comments', - 'comments as pending_comments_count' => function (Builder $query) { - $query->where('approved', false); - }, - ])->get(); +$posts = Post::withCount([ + 'comments', + 'comments as pending_comments_count' => function (Builder $query) { + $query->where('approved', false); + }, +])->get(); - echo $posts[0]->comments_count; - echo $posts[0]->pending_comments_count; +echo $posts[0]->comments_count; +echo $posts[0]->pending_comments_count; +``` #### Deferred Count Loading Using the `loadCount` method, you may load a relationship count after the parent model has already been retrieved: - $book = Book::first(); +```php +$book = Book::first(); - $book->loadCount('genres'); +$book->loadCount('genres'); +``` If you need to set additional query constraints on the count query, you may pass an array keyed by the relationships you wish to count. The array values should be closures which receive the query builder instance: - $book->loadCount(['reviews' => function ($query) { - $query->where('rating', 5); - }]) +```php +$book->loadCount(['reviews' => function (Builder $query) { + $query->where('rating', 5); +}]) +``` -#### Relationship Counting & Custom Select Statements +#### Relationship Counting and Custom Select Statements If you're combining `withCount` with a `select` statement, ensure that you call `withCount` after the `select` method: - $posts = Post::select(['title', 'body']) - ->withCount('comments') - ->get(); +```php +$posts = Post::select(['title', 'body']) + ->withCount('comments') + ->get(); +``` ### Other Aggregate Functions In addition to the `withCount` method, Eloquent provides `withMin`, `withMax`, `withAvg`, `withSum`, and `withExists` methods. These methods will place a `{relation}_{function}_{column}` attribute on your resulting models: - use App\Models\Post; +```php +use App\Models\Post; - $posts = Post::withSum('comments', 'votes')->get(); +$posts = Post::withSum('comments', 'votes')->get(); - foreach ($posts as $post) { - echo $post->comments_sum_votes; - } +foreach ($posts as $post) { + echo $post->comments_sum_votes; +} +``` If you wish to access the result of the aggregate function using another name, you may specify your own alias: - $posts = Post::withSum('comments as total_comments', 'votes')->get(); +```php +$posts = Post::withSum('comments as total_comments', 'votes')->get(); - foreach ($posts as $post) { - echo $post->total_comments; - } +foreach ($posts as $post) { + echo $post->total_comments; +} +``` Like the `loadCount` method, deferred versions of these methods are also available. These additional aggregate operations may be performed on Eloquent models that have already been retrieved: - $post = Post::first(); +```php +$post = Post::first(); - $post->loadSum('comments', 'votes'); +$post->loadSum('comments', 'votes'); +``` If you're combining these aggregate methods with a `select` statement, ensure that you call the aggregate methods after the `select` method: - $posts = Post::select(['title', 'body']) - ->withExists('comments') - ->get(); +```php +$posts = Post::select(['title', 'body']) + ->withExists('comments') + ->get(); +``` -### Counting Related Models On Morph To Relationships +### Counting Related Models on Morph To Relationships If you would like to eager load a "morph to" relationship, as well as related model counts for the various entities that may be returned by that relationship, you may utilize the `with` method in combination with the `morphTo` relationship's `morphWithCount` method. @@ -1420,69 +1904,80 @@ In this example, let's assume that `Photo` and `Post` models may create `Activit Now, let's imagine we want to retrieve `ActivityFeed` instances and eager load the `parentable` parent models for each `ActivityFeed` instance. In addition, we want to retrieve the number of tags that are associated with each parent photo and the number of comments that are associated with each parent post: - use Illuminate\Database\Eloquent\Relations\MorphTo; +```php +use Illuminate\Database\Eloquent\Relations\MorphTo; - $activities = ActivityFeed::with([ - 'parentable' => function (MorphTo $morphTo) { - $morphTo->morphWithCount([ - Photo::class => ['tags'], - Post::class => ['comments'], - ]); - }])->get(); +$activities = ActivityFeed::with([ + 'parentable' => function (MorphTo $morphTo) { + $morphTo->morphWithCount([ + Photo::class => ['tags'], + Post::class => ['comments'], + ]); + }])->get(); +``` #### Deferred Count Loading Let's assume we have already retrieved a set of `ActivityFeed` models and now we would like to load the nested relationship counts for the various `parentable` models associated with the activity feeds. You may use the `loadMorphCount` method to accomplish this: - $activities = ActivityFeed::with('parentable')->get(); +```php +$activities = ActivityFeed::with('parentable')->get(); - $activities->loadMorphCount('parentable', [ - Photo::class => ['tags'], - Post::class => ['comments'], - ]); +$activities->loadMorphCount('parentable', [ + Photo::class => ['tags'], + Post::class => ['comments'], +]); +``` ## Eager Loading When accessing Eloquent relationships as properties, the related models are "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the "N + 1" query problem. To illustrate the N + 1 query problem, consider a `Book` model that "belongs to" to an `Author` model: - belongsTo(Author::class); - } + return $this->belongsTo(Author::class); } +} +``` Now, let's retrieve all books and their authors: - use App\Models\Book; +```php +use App\Models\Book; - $books = Book::all(); +$books = Book::all(); - foreach ($books as $book) { - echo $book->author->name; - } +foreach ($books as $book) { + echo $book->author->name; +} +``` This loop will execute one query to retrieve all of the books within the database table, then another query for each book in order to retrieve the book's author. So, if we have 25 books, the code above would run 26 queries: one for the original book, and 25 additional queries to retrieve the author of each book. Thankfully, we can use eager loading to reduce this operation to just two queries. When building a query, you may specify which relationships should be eager loaded using the `with` method: - $books = Book::with('author')->get(); +```php +$books = Book::with('author')->get(); - foreach ($books as $book) { - echo $book->author->name; - } +foreach ($books as $book) { + echo $book->author->name; +} +``` For this operation, only two queries will be executed - one query to retrieve all of the books and one query to retrieve all of the authors for all of the books: @@ -1497,200 +1992,304 @@ select * from authors where id in (1, 2, 3, 4, 5, ...) Sometimes you may need to eager load several different relationships. To do so, just pass an array of relationships to the `with` method: - $books = Book::with(['author', 'publisher'])->get(); +```php +$books = Book::with(['author', 'publisher'])->get(); +``` #### Nested Eager Loading To eager load a relationship's relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts: - $books = Book::with('author.contacts')->get(); +```php +$books = Book::with('author.contacts')->get(); +``` + +Alternatively, you may specify nested eager loaded relationships by providing a nested array to the `with` method, which can be convenient when eager loading multiple nested relationships: + +```php +$books = Book::with([ + 'author' => [ + 'contacts', + 'publisher', + ], +])->get(); +``` #### Nested Eager Loading `morphTo` Relationships If you would like to eager load a `morphTo` relationship, as well as nested relationships on the various entities that may be returned by that relationship, you may use the `with` method in combination with the `morphTo` relationship's `morphWith` method. To help illustrate this method, let's consider the following model: - morphTo(); - } + return $this->morphTo(); } +} +``` In this example, let's assume `Event`, `Photo`, and `Post` models may create `ActivityFeed` models. Additionally, let's assume that `Event` models belong to a `Calendar` model, `Photo` models are associated with `Tag` models, and `Post` models belong to an `Author` model. Using these model definitions and relationships, we may retrieve `ActivityFeed` model instances and eager load all `parentable` models and their respective nested relationships: - use Illuminate\Database\Eloquent\Relations\MorphTo; +```php +use Illuminate\Database\Eloquent\Relations\MorphTo; - $activities = ActivityFeed::query() - ->with(['parentable' => function (MorphTo $morphTo) { - $morphTo->morphWith([ - Event::class => ['calendar'], - Photo::class => ['tags'], - Post::class => ['author'], - ]); - }])->get(); +$activities = ActivityFeed::query() + ->with(['parentable' => function (MorphTo $morphTo) { + $morphTo->morphWith([ + Event::class => ['calendar'], + Photo::class => ['tags'], + Post::class => ['author'], + ]); + }])->get(); +``` #### Eager Loading Specific Columns You may not always need every column from the relationships you are retrieving. For this reason, Eloquent allows you to specify which columns of the relationship you would like to retrieve: - $books = Book::with('author:id,name,book_id')->get(); +```php +$books = Book::with('author:id,name,book_id')->get(); +``` -> {note} When using this feature, you should always include the `id` column and any relevant foreign key columns in the list of columns you wish to retrieve. +> [!WARNING] +> When using this feature, you should always include the `id` column and any relevant foreign key columns in the list of columns you wish to retrieve. -#### Eager Loading By Default +#### Eager Loading by Default Sometimes you might want to always load some relationships when retrieving a model. To accomplish this, you may define a `$with` property on the model: - belongsTo(Author::class); - } + return $this->belongsTo(Author::class); + } - /** - * Get the genre of the book. - */ - public function genre() - { - return $this->belongsTo(Genre::class); - } + /** + * Get the genre of the book. + */ + public function genre(): BelongsTo + { + return $this->belongsTo(Genre::class); } +} +``` If you would like to remove an item from the `$with` property for a single query, you may use the `without` method: - $books = Book::without('author')->get(); +```php +$books = Book::without('author')->get(); +``` If you would like to override all items within the `$with` property for a single query, you may use the `withOnly` method: - $books = Book::withOnly('genre')->get(); +```php +$books = Book::withOnly('genre')->get(); +``` ### Constraining Eager Loads Sometimes you may wish to eager load a relationship but also specify additional query conditions for the eager loading query. You can accomplish this by passing an array of relationships to the `with` method where the array key is a relationship name and the array value is a closure that adds additional constraints to the eager loading query: - use App\Models\User; +```php +use App\Models\User; +use Illuminate\Database\Eloquent\Builder; - $users = User::with(['posts' => function ($query) { - $query->where('title', 'like', '%code%'); - }])->get(); +$users = User::with(['posts' => function (Builder $query) { + $query->where('title', 'like', '%code%'); +}])->get(); +``` In this example, Eloquent will only eager load posts where the post's `title` column contains the word `code`. You may call other [query builder](/docs/{{version}}/queries) methods to further customize the eager loading operation: - $users = User::with(['posts' => function ($query) { - $query->orderBy('created_at', 'desc'); - }])->get(); - -> {note} The `limit` and `take` query builder methods may not be used when constraining eager loads. +```php +$users = User::with(['posts' => function (Builder $query) { + $query->orderBy('created_at', 'desc'); +}])->get(); +``` -#### Constraining Eager Loading Of `morphTo` Relationships +#### Constraining Eager Loading of `morphTo` Relationships If you are eager loading a `morphTo` relationship, Eloquent will run multiple queries to fetch each type of related model. You may add additional constraints to each of these queries using the `MorphTo` relation's `constrain` method: - use Illuminate\Database\Eloquent\Builder; - use Illuminate\Database\Eloquent\Relations\MorphTo; - - $comments = Comment::with(['commentable' => function (MorphTo $morphTo) { - $morphTo->constrain([ - Post::class => function (Builder $query) { - $query->whereNull('hidden_at'); - }, - Video::class => function (Builder $query) { - $query->where('type', 'educational'); - }, - ]); - }])->get(); +```php +use Illuminate\Database\Eloquent\Relations\MorphTo; + +$comments = Comment::with(['commentable' => function (MorphTo $morphTo) { + $morphTo->constrain([ + Post::class => function ($query) { + $query->whereNull('hidden_at'); + }, + Video::class => function ($query) { + $query->where('type', 'educational'); + }, + ]); +}])->get(); +``` -In this example, Eloquent will only eager load posts that have not been hidden and videos have a `type` value of "educational". +In this example, Eloquent will only eager load posts that have not been hidden and videos that have a `type` value of "educational". + + +#### Constraining Eager Loads With Relationship Existence + +You may sometimes find yourself needing to check for the existence of a relationship while simultaneously loading the relationship based on the same conditions. For example, you may wish to only retrieve `User` models that have child `Post` models matching a given query condition while also eager loading the matching posts. You may accomplish this using the `withWhereHas` method: + +```php +use App\Models\User; + +$users = User::withWhereHas('posts', function ($query) { + $query->where('featured', true); +})->get(); +``` ### Lazy Eager Loading Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models: - use App\Models\Book; +```php +use App\Models\Book; - $books = Book::all(); +$books = Book::all(); - if ($someCondition) { - $books->load('author', 'publisher'); - } +if ($condition) { + $books->load('author', 'publisher'); +} +``` If you need to set additional query constraints on the eager loading query, you may pass an array keyed by the relationships you wish to load. The array values should be closure instances which receive the query instance: - $author->load(['books' => function ($query) { - $query->orderBy('published_date', 'asc'); - }]); +```php +$author->load(['books' => function (Builder $query) { + $query->orderBy('published_date', 'asc'); +}]); +``` To load a relationship only when it has not already been loaded, use the `loadMissing` method: - $book->loadMissing('author'); +```php +$book->loadMissing('author'); +``` -#### Nested Lazy Eager Loading & `morphTo` +#### Nested Lazy Eager Loading and `morphTo` If you would like to eager load a `morphTo` relationship, as well as nested relationships on the various entities that may be returned by that relationship, you may use the `loadMorph` method. This method accepts the name of the `morphTo` relationship as its first argument, and an array of model / relationship pairs as its second argument. To help illustrate this method, let's consider the following model: - morphTo(); - } + return $this->morphTo(); } +} +``` In this example, let's assume `Event`, `Photo`, and `Post` models may create `ActivityFeed` models. Additionally, let's assume that `Event` models belong to a `Calendar` model, `Photo` models are associated with `Tag` models, and `Post` models belong to an `Author` model. Using these model definitions and relationships, we may retrieve `ActivityFeed` model instances and eager load all `parentable` models and their respective nested relationships: - $activities = ActivityFeed::with('parentable') - ->get() - ->loadMorph('parentable', [ - Event::class => ['calendar'], - Photo::class => ['tags'], - Post::class => ['author'], - ]); +```php +$activities = ActivityFeed::with('parentable') + ->get() + ->loadMorph('parentable', [ + Event::class => ['calendar'], + Photo::class => ['tags'], + Post::class => ['author'], + ]); +``` + + +### Automatic Eager Loading + +> [!WARNING] +> This feature is currently in beta in order to gather community feedback. The behavior and functionality of this feature may change even on patch releases. + +In many cases, Laravel can automatically eager load the relationships you access. To enable automatic eager loading, you should invoke the `Model::automaticallyEagerLoadRelationships` method within the `boot` method of your application's `AppServiceProvider`: + +```php +use Illuminate\Database\Eloquent\Model; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Model::automaticallyEagerLoadRelationships(); +} +``` + +When this feature is enabled, Laravel will attempt to automatically load any relationships you access that have not been previously loaded. For example, consider the following scenario: + +```php +use App\Models\User; + +$users = User::all(); + +foreach ($users as $user) { + foreach ($user->posts as $post) { + foreach ($post->comments as $comment) { + echo $comment->content; + } + } +} +``` + +Typically, the code above would execute a query for each user in order to retrieve their posts, as well as a query for each post to retrieve its comments. However, when the `automaticallyEagerLoadRelationships` feature has been enabled, Laravel will automatically [lazy eager load](#lazy-eager-loading) the posts for all users in the user collection when you attempt to access the posts on any of the retrieved users. Likewise, when you attempt to access the comments for any retrieved post, all comments will be lazy eager loaded for all posts that were originally retrieved. + +If you do not want to globally enable automatic eager loading, you can still enable this feature for a single Eloquent collection instance by invoking the `withRelationshipAutoloading` method on the collection: + +```php +$users = User::where('vip', true)->get(); + +return $users->withRelationshipAutoloading(); +``` ### Preventing Lazy Loading @@ -1704,10 +2303,8 @@ use Illuminate\Database\Eloquent\Model; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Model::preventLazyLoading(! $this->app->isProduction()); } @@ -1718,180 +2315,247 @@ After preventing lazy loading, Eloquent will throw a `Illuminate\Database\LazyLo You may customize the behavior of lazy loading violations using the `handleLazyLoadingViolationsUsing` method. For example, using this method, you may instruct lazy loading violations to only be logged instead of interrupting the application's execution with exceptions: ```php -Model::handleLazyLoadingViolationUsing(function ($model, $relation) { - $class = get_class($model); +Model::handleLazyLoadingViolationUsing(function (Model $model, string $relation) { + $class = $model::class; info("Attempted to lazy load [{$relation}] on model [{$class}]."); }); ``` -## Inserting & Updating Related Models +## Inserting and Updating Related Models ### The `save` Method Eloquent provides convenient methods for adding new models to relationships. For example, perhaps you need to add a new comment to a post. Instead of manually setting the `post_id` attribute on the `Comment` model you may insert the comment using the relationship's `save` method: - use App\Models\Comment; - use App\Models\Post; +```php +use App\Models\Comment; +use App\Models\Post; - $comment = new Comment(['message' => 'A new comment.']); +$comment = new Comment(['message' => 'A new comment.']); - $post = Post::find(1); +$post = Post::find(1); - $post->comments()->save($comment); +$post->comments()->save($comment); +``` Note that we did not access the `comments` relationship as a dynamic property. Instead, we called the `comments` method to obtain an instance of the relationship. The `save` method will automatically add the appropriate `post_id` value to the new `Comment` model. If you need to save multiple related models, you may use the `saveMany` method: - $post = Post::find(1); +```php +$post = Post::find(1); - $post->comments()->saveMany([ - new Comment(['message' => 'A new comment.']), - new Comment(['message' => 'Another new comment.']), - ]); +$post->comments()->saveMany([ + new Comment(['message' => 'A new comment.']), + new Comment(['message' => 'Another new comment.']), +]); +``` The `save` and `saveMany` methods will persist the given model instances, but will not add the newly persisted models to any in-memory relationships that are already loaded onto the parent model. If you plan on accessing the relationship after using the `save` or `saveMany` methods, you may wish to use the `refresh` method to reload the model and its relationships: - $post->comments()->save($comment); +```php +$post->comments()->save($comment); - $post->refresh(); +$post->refresh(); - // All comments, including the newly saved comment... - $post->comments; +// All comments, including the newly saved comment... +$post->comments; +``` -#### Recursively Saving Models & Relationships +#### Recursively Saving Models and Relationships If you would like to `save` your model and all of its associated relationships, you may use the `push` method. In this example, the `Post` model will be saved as well as its comments and the comment's authors: - $post = Post::find(1); +```php +$post = Post::find(1); + +$post->comments[0]->message = 'Message'; +$post->comments[0]->author->name = 'Author Name'; + +$post->push(); +``` - $post->comments[0]->message = 'Message'; - $post->comments[0]->author->name = 'Author Name'; +The `pushQuietly` method may be used to save a model and its associated relationships without raising any events: - $post->push(); +```php +$post->pushQuietly(); +``` ### The `create` Method In addition to the `save` and `saveMany` methods, you may also use the `create` method, which accepts an array of attributes, creates a model, and inserts it into the database. The difference between `save` and `create` is that `save` accepts a full Eloquent model instance while `create` accepts a plain PHP `array`. The newly created model will be returned by the `create` method: - use App\Models\Post; +```php +use App\Models\Post; - $post = Post::find(1); +$post = Post::find(1); - $comment = $post->comments()->create([ - 'message' => 'A new comment.', - ]); +$comment = $post->comments()->create([ + 'message' => 'A new comment.', +]); +``` You may use the `createMany` method to create multiple related models: - $post = Post::find(1); +```php +$post = Post::find(1); - $post->comments()->createMany([ - ['message' => 'A new comment.'], - ['message' => 'Another new comment.'], - ]); +$post->comments()->createMany([ + ['message' => 'A new comment.'], + ['message' => 'Another new comment.'], +]); +``` + +The `createQuietly` and `createManyQuietly` methods may be used to create a model(s) without dispatching any events: + +```php +$user = User::find(1); + +$user->posts()->createQuietly([ + 'title' => 'Post title.', +]); + +$user->posts()->createManyQuietly([ + ['title' => 'First post.'], + ['title' => 'Second post.'], +]); +``` You may also use the `findOrNew`, `firstOrNew`, `firstOrCreate`, and `updateOrCreate` methods to [create and update models on relationships](/docs/{{version}}/eloquent#upserts). -> {tip} Before using the `create` method, be sure to review the [mass assignment](/docs/{{version}}/eloquent#mass-assignment) documentation. +> [!NOTE] +> Before using the `create` method, be sure to review the [mass assignment](/docs/{{version}}/eloquent#mass-assignment) documentation. ### Belongs To Relationships If you would like to assign a child model to a new parent model, you may use the `associate` method. In this example, the `User` model defines a `belongsTo` relationship to the `Account` model. This `associate` method will set the foreign key on the child model: - use App\Models\Account; +```php +use App\Models\Account; - $account = Account::find(10); +$account = Account::find(10); - $user->account()->associate($account); +$user->account()->associate($account); - $user->save(); +$user->save(); +``` To remove a parent model from a child model, you may use the `dissociate` method. This method will set the relationship's foreign key to `null`: - $user->account()->dissociate(); +```php +$user->account()->dissociate(); - $user->save(); +$user->save(); +``` -### Many To Many Relationships +### Many to Many Relationships #### Attaching / Detaching Eloquent also provides methods to make working with many-to-many relationships more convenient. For example, let's imagine a user can have many roles and a role can have many users. You may use the `attach` method to attach a role to a user by inserting a record in the relationship's intermediate table: - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - $user->roles()->attach($roleId); +$user->roles()->attach($roleId); +``` When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table: - $user->roles()->attach($roleId, ['expires' => $expires]); +```php +$user->roles()->attach($roleId, ['expires' => $expires]); +``` Sometimes it may be necessary to remove a role from a user. To remove a many-to-many relationship record, use the `detach` method. The `detach` method will delete the appropriate record out of the intermediate table; however, both models will remain in the database: - // Detach a single role from the user... - $user->roles()->detach($roleId); +```php +// Detach a single role from the user... +$user->roles()->detach($roleId); - // Detach all roles from the user... - $user->roles()->detach(); +// Detach all roles from the user... +$user->roles()->detach(); +``` For convenience, `attach` and `detach` also accept arrays of IDs as input: - $user = User::find(1); +```php +$user = User::find(1); - $user->roles()->detach([1, 2, 3]); +$user->roles()->detach([1, 2, 3]); - $user->roles()->attach([ - 1 => ['expires' => $expires], - 2 => ['expires' => $expires], - ]); +$user->roles()->attach([ + 1 => ['expires' => $expires], + 2 => ['expires' => $expires], +]); +``` #### Syncing Associations You may also use the `sync` method to construct many-to-many associations. The `sync` method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table: - $user->roles()->sync([1, 2, 3]); +```php +$user->roles()->sync([1, 2, 3]); +``` You may also pass additional intermediate table values with the IDs: - $user->roles()->sync([1 => ['expires' => true], 2, 3]); +```php +$user->roles()->sync([1 => ['expires' => true], 2, 3]); +``` If you would like to insert the same intermediate table values with each of the synced model IDs, you may use the `syncWithPivotValues` method: - $user->roles()->syncWithPivotValues([1, 2, 3], ['active' => true]); +```php +$user->roles()->syncWithPivotValues([1, 2, 3], ['active' => true]); +``` If you do not want to detach existing IDs that are missing from the given array, you may use the `syncWithoutDetaching` method: - $user->roles()->syncWithoutDetaching([1, 2, 3]); +```php +$user->roles()->syncWithoutDetaching([1, 2, 3]); +``` #### Toggling Associations The many-to-many relationship also provides a `toggle` method which "toggles" the attachment status of the given related model IDs. If the given ID is currently attached, it will be detached. Likewise, if it is currently detached, it will be attached: - $user->roles()->toggle([1, 2, 3]); +```php +$user->roles()->toggle([1, 2, 3]); +``` + +You may also pass additional intermediate table values with the IDs: + +```php +$user->roles()->toggle([ + 1 => ['expires' => true], + 2 => ['expires' => true], +]); +``` -#### Updating A Record On The Intermediate Table +#### Updating a Record on the Intermediate Table If you need to update an existing row in your relationship's intermediate table, you may use the `updateExistingPivot` method. This method accepts the intermediate record foreign key and an array of attributes to update: - $user = User::find(1); +```php +$user = User::find(1); - $user->roles()->updateExistingPivot($roleId, [ - 'active' => false, - ]); +$user->roles()->updateExistingPivot($roleId, [ + 'active' => false, +]); +``` ## Touching Parent Timestamps @@ -1900,28 +2564,32 @@ When a model defines a `belongsTo` or `belongsToMany` relationship to another mo For example, when a `Comment` model is updated, you may want to automatically "touch" the `updated_at` timestamp of the owning `Post` so that it is set to the current date and time. To accomplish this, you may add a `touches` property to your child model containing the names of the relationships that should have their `updated_at` timestamps updated when the child model is updated: - belongsTo(Post::class); - } + return $this->belongsTo(Post::class); } +} +``` -> {note} Parent model timestamps will only be updated if the child model is updated using Eloquent's `save` method. +> [!WARNING] +> Parent model timestamps will only be updated if the child model is updated using Eloquent's `save` method. diff --git a/eloquent-resources.md b/eloquent-resources.md index d5b2759f643..efc2619fb5f 100644 --- a/eloquent-resources.md +++ b/eloquent-resources.md @@ -44,60 +44,86 @@ php artisan make:resource UserCollection ## Concept Overview -> {tip} This is a high-level overview of resources and resource collections. You are highly encouraged to read the other sections of this documentation to gain a deeper understanding of the customization and power offered to you by resources. +> [!NOTE] +> This is a high-level overview of resources and resource collections. You are highly encouraged to read the other sections of this documentation to gain a deeper understanding of the customization and power offered to you by resources. Before diving into all of the options available to you when writing resources, let's first take a high-level look at how resources are used within Laravel. A resource class represents a single model that needs to be transformed into a JSON structure. For example, here is a simple `UserResource` resource class: - + */ + public function toArray(Request $request): array { - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'email' => $this->email, - 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at, - ]; - } + return [ + 'id' => $this->id, + 'name' => $this->name, + 'email' => $this->email, + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, + ]; } +} +``` Every resource class defines a `toArray` method which returns the array of attributes that should be converted to JSON when the resource is returned as a response from a route or controller method. Note that we can access model properties directly from the `$this` variable. This is because a resource class will automatically proxy property and method access down to the underlying model for convenient access. Once the resource is defined, it may be returned from a route or controller. The resource accepts the underlying model instance via its constructor: - use App\Http\Resources\UserResource; - use App\Models\User; +```php +use App\Http\Resources\UserResource; +use App\Models\User; + +Route::get('/user/{id}', function (string $id) { + return new UserResource(User::findOrFail($id)); +}); +``` + +For convenience, you may use the model's `toResource` method, which will use framework conventions to automatically discover the model's underlying resource: - Route::get('/user/{id}', function ($id) { - return new UserResource(User::findOrFail($id)); - }); +```php +return User::findOrFail($id)->toResource(); +``` + +When invoking the `toResource` method, Laravel will attempt to locate a resource that matches the model's name and is optionally suffixed with `Resource` within the `Http\Resources` namespace closest to the model's namespace. ### Resource Collections If you are returning a collection of resources or a paginated response, you should use the `collection` method provided by your resource class when creating the resource instance in your route or controller: - use App\Http\Resources\UserResource; - use App\Models\User; +```php +use App\Http\Resources\UserResource; +use App\Models\User; + +Route::get('/users', function () { + return UserResource::collection(User::all()); +}); +``` + +Or, for convenience, you may use the Eloquent collection's `toResourceCollection` method, which will use framework conventions to automatically discover the model's underlying resource collection: - Route::get('/users', function () { - return UserResource::collection(User::all()); - }); +```php +return User::all()->toResourceCollection(); +``` + +When invoking the `toResourceCollection` method, Laravel will attempt to locate a resource collection that matches the model's name and is suffixed with `Collection` within the `Http\Resources` namespace closest to the model's namespace. + + +#### Custom Resource Collections -Note that this does not allow any addition of custom meta data that may need to be returned with your collection. If you would like to customize the resource collection response, you may create a dedicated resource to represent the collection: +By default, resource collections do not allow any addition of custom meta data that may need to be returned with your collection. If you would like to customize the resource collection response, you may create a dedicated resource to represent the collection: ```shell php artisan make:resource UserCollection @@ -105,209 +131,247 @@ php artisan make:resource UserCollection Once the resource collection class has been generated, you may easily define any meta data that should be included with the response: - + */ + public function toArray(Request $request): array { - /** - * Transform the resource collection into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'data' => $this->collection, - 'links' => [ - 'self' => 'link-value', - ], - ]; - } + return [ + 'data' => $this->collection, + 'links' => [ + 'self' => 'link-value', + ], + ]; } +} +``` After defining your resource collection, it may be returned from a route or controller: - use App\Http\Resources\UserCollection; - use App\Models\User; +```php +use App\Http\Resources\UserCollection; +use App\Models\User; + +Route::get('/users', function () { + return new UserCollection(User::all()); +}); +``` + +Or, for convenience, you may use the Eloquent collection's `toResourceCollection` method, which will use framework conventions to automatically discover the model's underlying resource collection: + +```php +return User::all()->toResourceCollection(); +``` - Route::get('/users', function () { - return new UserCollection(User::all()); - }); +When invoking the `toResourceCollection` method, Laravel will attempt to locate a resource collection that matches the model's name and is suffixed with `Collection` within the `Http\Resources` namespace closest to the model's namespace. #### Preserving Collection Keys When returning a resource collection from a route, Laravel resets the collection's keys so that they are in numerical order. However, you may add a `preserveKeys` property to your resource class indicating whether a collection's original keys should be preserved: - keyBy->id); - }); +Route::get('/users', function () { + return UserResource::collection(User::all()->keyBy->id); +}); +``` -#### Customizing The Underlying Resource Class +#### Customizing the Underlying Resource Class Typically, the `$this->collection` property of a resource collection is automatically populated with the result of mapping each item of the collection to its singular resource class. The singular resource class is assumed to be the collection's class name without the trailing `Collection` portion of the class name. In addition, depending on your personal preference, the singular resource class may or may not be suffixed with `Resource`. For example, `UserCollection` will attempt to map the given user instances into the `UserResource` resource. To customize this behavior, you may override the `$collects` property of your resource collection: - ## Writing Resources -> {tip} If you have not read the [concept overview](#concept-overview), you are highly encouraged to do so before proceeding with this documentation. +> [!NOTE] +> If you have not read the [concept overview](#concept-overview), you are highly encouraged to do so before proceeding with this documentation. -In essence, resources are simple. They only need to transform a given model into an array. So, each resource contains a `toArray` method which translates your model's attributes into an API friendly array that can be returned from your application's routes or controllers: +Resources only need to transform a given model into an array. So, each resource contains a `toArray` method which translates your model's attributes into an API friendly array that can be returned from your application's routes or controllers: - $this->id, - 'name' => $this->name, - 'email' => $this->email, - 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at, - ]; - } - } - -Once a resource has been defined, it may be returned directly from a route or controller: - - use App\Http\Resources\UserResource; - use App\Models\User; - - Route::get('/user/{id}', function ($id) { - return new UserResource(User::findOrFail($id)); - }); - - -#### Relationships - -If you would like to include related resources in your response, you may add them to the array returned by your resource's `toArray` method. In this example, we will use the `PostResource` resource's `collection` method to add the user's blog posts to the resource response: - - use App\Http\Resources\PostResource; +use Illuminate\Http\Request; +use Illuminate\Http\Resources\Json\JsonResource; +class UserResource extends JsonResource +{ /** * Transform the resource into an array. * - * @param \Illuminate\Http\Request $request - * @return array + * @return array */ - public function toArray($request) + public function toArray(Request $request): array { return [ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email, - 'posts' => PostResource::collection($this->posts), 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } +} +``` + +Once a resource has been defined, it may be returned directly from a route or controller: + +```php +use App\Models\User; + +Route::get('/user/{id}', function (string $id) { + return User::findOrFail($id)->toUserResource(); +}); +``` + + +#### Relationships + +If you would like to include related resources in your response, you may add them to the array returned by your resource's `toArray` method. In this example, we will use the `PostResource` resource's `collection` method to add the user's blog posts to the resource response: + +```php +use App\Http\Resources\PostResource; +use Illuminate\Http\Request; + +/** + * Transform the resource into an array. + * + * @return array + */ +public function toArray(Request $request): array +{ + return [ + 'id' => $this->id, + 'name' => $this->name, + 'email' => $this->email, + 'posts' => PostResource::collection($this->posts), + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, + ]; +} +``` -> {tip} If you would like to include relationships only when they have already been loaded, check out the documentation on [conditional relationships](#conditional-relationships). +> [!NOTE] +> If you would like to include relationships only when they have already been loaded, check out the documentation on [conditional relationships](#conditional-relationships). #### Resource Collections -While resources transform a single model into an array, resource collections transform a collection of models into an array. However, it is not absolutely necessary to define a resource collection class for each one of your models since all resources provide a `collection` method to generate an "ad-hoc" resource collection on the fly: +While resources transform a single model into an array, resource collections transform a collection of models into an array. However, it is not absolutely necessary to define a resource collection class for each one of your models since all Eloquent model collections provide a `toResourceCollection` method to generate an "ad-hoc" resource collection on the fly: - use App\Http\Resources\UserResource; - use App\Models\User; +```php +use App\Models\User; - Route::get('/users', function () { - return UserResource::collection(User::all()); - }); +Route::get('/users', function () { + return User::all()->toResourceCollection(); +}); +``` However, if you need to customize the meta data returned with the collection, it is necessary to define your own resource collection: - + */ + public function toArray(Request $request): array { - /** - * Transform the resource collection into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'data' => $this->collection, - 'links' => [ - 'self' => 'link-value', - ], - ]; - } + return [ + 'data' => $this->collection, + 'links' => [ + 'self' => 'link-value', + ], + ]; } +} +``` Like singular resources, resource collections may be returned directly from routes or controllers: - use App\Http\Resources\UserCollection; - use App\Models\User; +```php +use App\Http\Resources\UserCollection; +use App\Models\User; + +Route::get('/users', function () { + return new UserCollection(User::all()); +}); +``` - Route::get('/users', function () { - return new UserCollection(User::all()); - }); +Or, for convenience, you may use the Eloquent collection's `toResourceCollection` method, which will use framework conventions to automatically discover the model's underlying resource collection: + +```php +return User::all()->toResourceCollection(); +``` + +When invoking the `toResourceCollection` method, Laravel will attempt to locate a resource collection that matches the model's name and is suffixed with `Collection` within the `Http\Resources` namespace closest to the model's namespace. ### Data Wrapping @@ -320,68 +384,49 @@ By default, your outermost resource is wrapped in a `data` key when the resource { "id": 1, "name": "Eladio Schroeder Sr.", - "email": "therese28@example.com", + "email": "therese28@example.com" }, { "id": 2, "name": "Liliana Mayert", - "email": "evandervort@example.com", + "email": "evandervort@example.com" } ] } ``` -If you would like to use a custom key instead of `data`, you may define a `$wrap` attribute on the resource class: +If you would like to disable the wrapping of the outermost resource, you should invoke the `withoutWrapping` method on the base `Illuminate\Http\Resources\Json\JsonResource` class. Typically, you should call this method from your `AppServiceProvider` or another [service provider](/docs/{{version}}/providers) that is loaded on every request to your application: - {note} The `withoutWrapping` method only affects the outermost response and will not remove `data` keys that you manually add to your own resource collections. +> [!WARNING] +> The `withoutWrapping` method only affects the outermost response and will not remove `data` keys that you manually add to your own resource collections. #### Wrapping Nested Resources @@ -390,28 +435,29 @@ You have total freedom to determine how your resource's relationships are wrappe You may be wondering if this will cause your outermost resource to be wrapped in two `data` keys. Don't worry, Laravel will never let your resources be accidentally double-wrapped, so you don't have to be concerned about the nesting level of the resource collection you are transforming: - + */ + public function toArray(Request $request): array { - /** - * Transform the resource collection into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return ['data' => $this->collection]; - } + return ['data' => $this->collection]; } +} +``` -#### Data Wrapping And Pagination +#### Data Wrapping and Pagination When returning paginated collections via a resource response, Laravel will wrap your resource data in a `data` key even if the `withoutWrapping` method has been called. This is because paginated responses always contain `meta` and `links` keys with information about the paginator's state: @@ -421,17 +467,17 @@ When returning paginated collections via a resource response, Laravel will wrap { "id": 1, "name": "Eladio Schroeder Sr.", - "email": "therese28@example.com", + "email": "therese28@example.com" }, { "id": 2, "name": "Liliana Mayert", - "email": "evandervort@example.com", + "email": "evandervort@example.com" } ], "links":{ - "first": "http://example.com/pagination?page=1", - "last": "http://example.com/pagination?page=1", + "first": "http://example.com/users?page=1", + "last": "http://example.com/users?page=1", "prev": null, "next": null }, @@ -439,7 +485,7 @@ When returning paginated collections via a resource response, Laravel will wrap "current_page": 1, "from": 1, "last_page": 1, - "path": "http://example.com/pagination", + "path": "http://example.com/users", "per_page": 15, "to": 10, "total": 10 @@ -452,12 +498,20 @@ When returning paginated collections via a resource response, Laravel will wrap You may pass a Laravel paginator instance to the `collection` method of a resource or to a custom resource collection: - use App\Http\Resources\UserCollection; - use App\Models\User; +```php +use App\Http\Resources\UserCollection; +use App\Models\User; - Route::get('/users', function () { - return new UserCollection(User::paginate()); - }); +Route::get('/users', function () { + return new UserCollection(User::paginate()); +}); +``` + +Or, for convenience, you may use the paginator's `toResourceCollection` method, which will use framework conventions to automatically discover the paginated model's underlying resource collection: + +```php +return User::paginate()->toResourceCollection(); +``` Paginated responses always contain `meta` and `links` keys with information about the paginator's state: @@ -467,17 +521,17 @@ Paginated responses always contain `meta` and `links` keys with information abou { "id": 1, "name": "Eladio Schroeder Sr.", - "email": "therese28@example.com", + "email": "therese28@example.com" }, { "id": 2, "name": "Liliana Mayert", - "email": "evandervort@example.com", + "email": "evandervort@example.com" } ], "links":{ - "first": "http://example.com/pagination?page=1", - "last": "http://example.com/pagination?page=1", + "first": "http://example.com/users?page=1", + "last": "http://example.com/users?page=1", "prev": null, "next": null }, @@ -485,7 +539,7 @@ Paginated responses always contain `meta` and `links` keys with information abou "current_page": 1, "from": 1, "last_page": 1, - "path": "http://example.com/pagination", + "path": "http://example.com/users", "per_page": 15, "to": 10, "total": 10 @@ -493,68 +547,105 @@ Paginated responses always contain `meta` and `links` keys with information abou } ``` + +#### Customizing the Pagination Information + +If you would like to customize the information included in the `links` or `meta` keys of the pagination response, you may define a `paginationInformation` method on the resource. This method will receive the `$paginated` data and the array of `$default` information, which is an array containing the `links` and `meta` keys: + +```php +/** + * Customize the pagination information for the resource. + * + * @param \Illuminate\Http\Request $request + * @param array $paginated + * @param array $default + * @return array + */ +public function paginationInformation($request, $paginated, $default) +{ + $default['links']['custom'] = 'https://example.com/'; + + return $default; +} +``` + ### Conditional Attributes Sometimes you may wish to only include an attribute in a resource response if a given condition is met. For example, you may wish to only include a value if the current user is an "administrator". Laravel provides a variety of helper methods to assist you in this situation. The `when` method may be used to conditionally add an attribute to a resource response: - use Illuminate\Support\Facades\Auth; - - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'email' => $this->email, - 'secret' => $this->when(Auth::user()->isAdmin(), 'secret-value'), - 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at, - ]; - } +```php +/** + * Transform the resource into an array. + * + * @return array + */ +public function toArray(Request $request): array +{ + return [ + 'id' => $this->id, + 'name' => $this->name, + 'email' => $this->email, + 'secret' => $this->when($request->user()->isAdmin(), 'secret-value'), + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, + ]; +} +``` In this example, the `secret` key will only be returned in the final resource response if the authenticated user's `isAdmin` method returns `true`. If the method returns `false`, the `secret` key will be removed from the resource response before it is sent to the client. The `when` method allows you to expressively define your resources without resorting to conditional statements when building the array. The `when` method also accepts a closure as its second argument, allowing you to calculate the resulting value only if the given condition is `true`: - 'secret' => $this->when(Auth::user()->isAdmin(), function () { - return 'secret-value'; - }), +```php +'secret' => $this->when($request->user()->isAdmin(), function () { + return 'secret-value'; +}), +``` + +The `whenHas` method may be used to include an attribute if it is actually present on the underlying model: + +```php +'name' => $this->whenHas('name'), +``` + +Additionally, the `whenNotNull` method may be used to include an attribute in the resource response if the attribute is not null: + +```php +'name' => $this->whenNotNull($this->name), +``` #### Merging Conditional Attributes Sometimes you may have several attributes that should only be included in the resource response based on the same condition. In this case, you may use the `mergeWhen` method to include the attributes in the response only when the given condition is `true`: - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'email' => $this->email, - $this->mergeWhen(Auth::user()->isAdmin(), [ - 'first-secret' => 'value', - 'second-secret' => 'value', - ]), - 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at, - ]; - } +```php +/** + * Transform the resource into an array. + * + * @return array + */ +public function toArray(Request $request): array +{ + return [ + 'id' => $this->id, + 'name' => $this->name, + 'email' => $this->email, + $this->mergeWhen($request->user()->isAdmin(), [ + 'first-secret' => 'value', + 'second-secret' => 'value', + ]), + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, + ]; +} +``` Again, if the given condition is `false`, these attributes will be removed from the resource response before it is sent to the client. -> {note} The `mergeWhen` method should not be used within arrays that mix string and numeric keys. Furthermore, it should not be used within arrays with numeric keys that are not ordered sequentially. +> [!WARNING] +> The `mergeWhen` method should not be used within arrays that mix string and numeric keys. Furthermore, it should not be used within arrays with numeric keys that are not ordered sequentially. ### Conditional Relationships @@ -563,95 +654,142 @@ In addition to conditionally loading attributes, you may conditionally include r The `whenLoaded` method may be used to conditionally load a relationship. In order to avoid unnecessarily loading relationships, this method accepts the name of the relationship instead of the relationship itself: - use App\Http\Resources\PostResource; +```php +use App\Http\Resources\PostResource; - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'email' => $this->email, - 'posts' => PostResource::collection($this->whenLoaded('posts')), - 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at, - ]; - } +/** + * Transform the resource into an array. + * + * @return array + */ +public function toArray(Request $request): array +{ + return [ + 'id' => $this->id, + 'name' => $this->name, + 'email' => $this->email, + 'posts' => PostResource::collection($this->whenLoaded('posts')), + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, + ]; +} +``` In this example, if the relationship has not been loaded, the `posts` key will be removed from the resource response before it is sent to the client. + +#### Conditional Relationship Counts + +In addition to conditionally including relationships, you may conditionally include relationship "counts" on your resource responses based on if the relationship's count has been loaded on the model: + +```php +new UserResource($user->loadCount('posts')); +``` + +The `whenCounted` method may be used to conditionally include a relationship's count in your resource response. This method avoids unnecessarily including the attribute if the relationships' count is not present: + +```php +/** + * Transform the resource into an array. + * + * @return array + */ +public function toArray(Request $request): array +{ + return [ + 'id' => $this->id, + 'name' => $this->name, + 'email' => $this->email, + 'posts_count' => $this->whenCounted('posts'), + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, + ]; +} +``` + +In this example, if the `posts` relationship's count has not been loaded, the `posts_count` key will be removed from the resource response before it is sent to the client. + +Other types of aggregates, such as `avg`, `sum`, `min`, and `max` may also be conditionally loaded using the `whenAggregated` method: + +```php +'words_avg' => $this->whenAggregated('posts', 'words', 'avg'), +'words_sum' => $this->whenAggregated('posts', 'words', 'sum'), +'words_min' => $this->whenAggregated('posts', 'words', 'min'), +'words_max' => $this->whenAggregated('posts', 'words', 'max'), +``` + #### Conditional Pivot Information In addition to conditionally including relationship information in your resource responses, you may conditionally include data from the intermediate tables of many-to-many relationships using the `whenPivotLoaded` method. The `whenPivotLoaded` method accepts the name of the pivot table as its first argument. The second argument should be a closure that returns the value to be returned if the pivot information is available on the model: - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'expires_at' => $this->whenPivotLoaded('role_user', function () { - return $this->pivot->expires_at; - }), - ]; - } +```php +/** + * Transform the resource into an array. + * + * @return array + */ +public function toArray(Request $request): array +{ + return [ + 'id' => $this->id, + 'name' => $this->name, + 'expires_at' => $this->whenPivotLoaded('role_user', function () { + return $this->pivot->expires_at; + }), + ]; +} +``` If your relationship is using a [custom intermediate table model](/docs/{{version}}/eloquent-relationships#defining-custom-intermediate-table-models), you may pass an instance of the intermediate table model as the first argument to the `whenPivotLoaded` method: - 'expires_at' => $this->whenPivotLoaded(new Membership, function () { - return $this->pivot->expires_at; - }), +```php +'expires_at' => $this->whenPivotLoaded(new Membership, function () { + return $this->pivot->expires_at; +}), +``` If your intermediate table is using an accessor other than `pivot`, you may use the `whenPivotLoadedAs` method: - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'expires_at' => $this->whenPivotLoadedAs('subscription', 'role_user', function () { - return $this->subscription->expires_at; - }), - ]; - } +```php +/** + * Transform the resource into an array. + * + * @return array + */ +public function toArray(Request $request): array +{ + return [ + 'id' => $this->id, + 'name' => $this->name, + 'expires_at' => $this->whenPivotLoadedAs('subscription', 'role_user', function () { + return $this->subscription->expires_at; + }), + ]; +} +``` ### Adding Meta Data -Some JSON API standards require the addition of meta data to your resource and resource collections responses. This often includes things like `links` to the resource or related resources, or meta data about the resource itself. If you need to return additional meta data about a resource, include it in your `toArray` method. For example, you might include `link` information when transforming a resource collection: +Some JSON API standards require the addition of meta data to your resource and resource collections responses. This often includes things like `links` to the resource or related resources, or meta data about the resource itself. If you need to return additional meta data about a resource, include it in your `toArray` method. For example, you might include `links` information when transforming a resource collection: - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'data' => $this->collection, - 'links' => [ - 'self' => 'link-value', - ], - ]; - } +```php +/** + * Transform the resource into an array. + * + * @return array + */ +public function toArray(Request $request): array +{ + return [ + 'data' => $this->collection, + 'links' => [ + 'self' => 'link-value', + ], + ]; +} +``` When returning additional meta data from your resources, you never have to worry about accidentally overriding the `links` or `meta` keys that are automatically added by Laravel when returning paginated responses. Any additional `links` you define will be merged with the links provided by the paginator. @@ -660,106 +798,113 @@ When returning additional meta data from your resources, you never have to worry Sometimes you may wish to only include certain meta data with a resource response if the resource is the outermost resource being returned. Typically, this includes meta information about the response as a whole. To define this meta data, add a `with` method to your resource class. This method should return an array of meta data to be included with the resource response only when the resource is the outermost resource being transformed: - + */ + public function toArray(Request $request): array { - /** - * Transform the resource collection into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return parent::toArray($request); - } + return parent::toArray($request); + } - /** - * Get additional data that should be returned with the resource array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function with($request) - { - return [ - 'meta' => [ - 'key' => 'value', - ], - ]; - } + /** + * Get additional data that should be returned with the resource array. + * + * @return array + */ + public function with(Request $request): array + { + return [ + 'meta' => [ + 'key' => 'value', + ], + ]; } +} +``` #### Adding Meta Data When Constructing Resources You may also add top-level data when constructing resource instances in your route or controller. The `additional` method, which is available on all resources, accepts an array of data that should be added to the resource response: - return (new UserCollection(User::all()->load('roles'))) - ->additional(['meta' => [ - 'key' => 'value', - ]]); +```php +return User::all() + ->load('roles') + ->toResourceCollection() + ->additional(['meta' => [ + 'key' => 'value', + ]]); +``` ## Resource Responses As you have already read, resources may be returned directly from routes and controllers: - use App\Http\Resources\UserResource; - use App\Models\User; +```php +use App\Models\User; - Route::get('/user/{id}', function ($id) { - return new UserResource(User::findOrFail($id)); - }); +Route::get('/user/{id}', function (string $id) { + return User::findOrFail($id)->toResource(); +}); +``` However, sometimes you may need to customize the outgoing HTTP response before it is sent to the client. There are two ways to accomplish this. First, you may chain the `response` method onto the resource. This method will return an `Illuminate\Http\JsonResponse` instance, giving you full control over the response's headers: - use App\Http\Resources\UserResource; - use App\Models\User; +```php +use App\Http\Resources\UserResource; +use App\Models\User; - Route::get('/user', function () { - return (new UserResource(User::find(1))) - ->response() - ->header('X-Value', 'True'); - }); +Route::get('/user', function () { + return User::find(1) + ->toResource() + ->response() + ->header('X-Value', 'True'); +}); +``` Alternatively, you may define a `withResponse` method within the resource itself. This method will be called when the resource is returned as the outermost resource in a response: - + */ + public function toArray(Request $request): array { - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - ]; - } + return [ + 'id' => $this->id, + ]; + } - /** - * Customize the outgoing response for the resource. - * - * @param \Illuminate\Http\Request $request - * @param \Illuminate\Http\Response $response - * @return void - */ - public function withResponse($request, $response) - { - $response->header('X-Value', 'True'); - } + /** + * Customize the outgoing response for the resource. + */ + public function withResponse(Request $request, JsonResponse $response): void + { + $response->header('X-Value', 'True'); } +} +``` diff --git a/eloquent-serialization.md b/eloquent-serialization.md index 3b7dac91dd3..91606b6d606 100644 --- a/eloquent-serialization.md +++ b/eloquent-serialization.md @@ -1,11 +1,11 @@ # Eloquent: Serialization - [Introduction](#introduction) -- [Serializing Models & Collections](#serializing-models-and-collections) - - [Serializing To Arrays](#serializing-to-arrays) - - [Serializing To JSON](#serializing-to-json) +- [Serializing Models and Collections](#serializing-models-and-collections) + - [Serializing to Arrays](#serializing-to-arrays) + - [Serializing to JSON](#serializing-to-json) - [Hiding Attributes From JSON](#hiding-attributes-from-json) -- [Appending Values To JSON](#appending-values-to-json) +- [Appending Values to JSON](#appending-values-to-json) - [Date Serialization](#date-serialization) @@ -13,56 +13,69 @@ When building APIs using Laravel, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in the serialized representation of your models. -> {tip} For an even more robust way of handling Eloquent model and collection JSON serialization, check out the documentation on [Eloquent API resources](/docs/{{version}}/eloquent-resources). +> [!NOTE] +> For an even more robust way of handling Eloquent model and collection JSON serialization, check out the documentation on [Eloquent API resources](/docs/{{version}}/eloquent-resources). -## Serializing Models & Collections +## Serializing Models and Collections -### Serializing To Arrays +### Serializing to Arrays To convert a model and its loaded [relationships](/docs/{{version}}/eloquent-relationships) to an array, you should use the `toArray` method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays: - use App\Models\User; +```php +use App\Models\User; - $user = User::with('roles')->first(); +$user = User::with('roles')->first(); - return $user->toArray(); +return $user->toArray(); +``` The `attributesToArray` method may be used to convert a model's attributes to an array but not its relationships: - $user = User::first(); +```php +$user = User::first(); - return $user->attributesToArray(); +return $user->attributesToArray(); +``` You may also convert entire [collections](/docs/{{version}}/eloquent-collections) of models to arrays by calling the `toArray` method on the collection instance: - $users = User::all(); +```php +$users = User::all(); - return $users->toArray(); +return $users->toArray(); +``` -### Serializing To JSON +### Serializing to JSON To convert a model to JSON, you should use the `toJson` method. Like `toArray`, the `toJson` method is recursive, so all attributes and relations will be converted to JSON. You may also specify any JSON encoding options that are [supported by PHP](https://secure.php.net/manual/en/function.json-encode.php): - use App\Models\User; +```php +use App\Models\User; - $user = User::find(1); +$user = User::find(1); - return $user->toJson(); +return $user->toJson(); - return $user->toJson(JSON_PRETTY_PRINT); +return $user->toJson(JSON_PRETTY_PRINT); +``` Alternatively, you may cast a model or collection to a string, which will automatically call the `toJson` method on the model or collection: - return (string) User::find(1); +```php +return (string) User::find(1); +``` Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers. Laravel will automatically serialize your Eloquent models and collections to JSON when they are returned from routes or controllers: - Route::get('users', function () { - return User::all(); - }); +```php +Route::get('/users', function () { + return User::all(); +}); +``` #### Relationships @@ -72,136 +85,167 @@ When an Eloquent model is converted to JSON, its loaded relationships will autom ## Hiding Attributes From JSON -Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a `$hidden` property to your model. In attributes that are listed in the `$hidden` property's array will not be included in the serialized representation of your model: +Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a `$hidden` property to your model. Attributes that are listed in the `$hidden` property's array will not be included in the serialized representation of your model: - + */ + protected $hidden = ['password']; +} +``` -> {tip} To hide relationships, add the relationship's method name to your Eloquent model's `$hidden` property. +> [!NOTE] +> To hide relationships, add the relationship's method name to your Eloquent model's `$hidden` property. Alternatively, you may use the `visible` property to define an "allow list" of attributes that should be included in your model's array and JSON representation. All attributes that are not present in the `$visible` array will be hidden when the model is converted to an array or JSON: - #### Temporarily Modifying Attribute Visibility -If you would like to make some typically hidden attributes visible on a given model instance, you may use the `makeVisible` method. The `makeVisible` method returns the model instance: +If you would like to make some typically hidden attributes visible on a given model instance, you may use the `makeVisible` or `mergeVisible` methods. The `makeVisible` method returns the model instance: + +```php +return $user->makeVisible('attribute')->toArray(); + +return $user->mergeVisible(['name', 'email'])->toArray(); +``` + +Likewise, if you would like to hide some attributes that are typically visible, you may use the `makeHidden` or `mergeHidden` methods: + +```php +return $user->makeHidden('attribute')->toArray(); - return $user->makeVisible('attribute')->toArray(); +return $user->mergeHidden(['name', 'email'])->toArray(); +``` -Likewise, if you would like to hide some attributes that are typically visible, you may use the `makeHidden` method. +If you wish to temporarily override all of the visible or hidden attributes, you may use the `setVisible` and `setHidden` methods respectively: - return $user->makeHidden('attribute')->toArray(); +```php +return $user->setVisible(['id', 'name'])->toArray(); + +return $user->setHidden(['email', 'password', 'remember_token'])->toArray(); +``` -## Appending Values To JSON +## Appending Values to JSON Occasionally, when converting models to arrays or JSON, you may wish to add attributes that do not have a corresponding column in your database. To do so, first define an [accessor](/docs/{{version}}/eloquent-mutators) for the value: - 'yes', - ); - } + return new Attribute( + get: fn () => 'yes', + ); } +} +``` -After creating the accessor, add the attribute name to the `appends` property of your model. Note that attribute names are typically referenced using their "snake case" serialized representation, even though the accessor's PHP method is defined using "camel case": +If you would like the accessor to always be appended to your model's array and JSON representations, you may add the attribute name to the `appends` property of your model. Note that attribute names are typically referenced using their "snake case" serialized representation, even though the accessor's PHP method is defined using "camel case": - -#### Appending At Run Time +#### Appending at Run Time + +At runtime, you may instruct a model instance to append additional attributes using the `append` or `mergeAppends` methods. Or, you may use the `setAppends` method to override the entire array of appended properties for a given model instance: -At runtime, you may instruct a model instance to append additional attributes using the `append` method. Or, you may use the `setAppends` method to override the entire array of appended properties for a given model instance: +```php +return $user->append('is_admin')->toArray(); - return $user->append('is_admin')->toArray(); +return $user->mergeAppends(['is_admin', 'status'])->toArray(); - return $user->setAppends(['is_admin'])->toArray(); +return $user->setAppends(['is_admin'])->toArray(); +``` ## Date Serialization -#### Customizing The Default Date Format +#### Customizing the Default Date Format You may customize the default serialization format by overriding the `serializeDate` method. This method does not affect how your dates are formatted for storage in the database: - /** - * Prepare a date for array / JSON serialization. - * - * @param \DateTimeInterface $date - * @return string - */ - protected function serializeDate(DateTimeInterface $date) - { - return $date->format('Y-m-d'); - } +```php +/** + * Prepare a date for array / JSON serialization. + */ +protected function serializeDate(DateTimeInterface $date): string +{ + return $date->format('Y-m-d'); +} +``` -#### Customizing The Date Format Per Attribute +#### Customizing the Date Format per Attribute You may customize the serialization format of individual Eloquent date attributes by specifying the date format in the model's [cast declarations](/docs/{{version}}/eloquent-mutators#attribute-casting): - protected $casts = [ +```php +protected function casts(): array +{ + return [ 'birthday' => 'date:Y-m-d', 'joined_at' => 'datetime:Y-m-d H:00', ]; +} +``` diff --git a/eloquent.md b/eloquent.md index b378ad1caa9..c8356bf2a14 100644 --- a/eloquent.md +++ b/eloquent.md @@ -5,9 +5,11 @@ - [Eloquent Model Conventions](#eloquent-model-conventions) - [Table Names](#table-names) - [Primary Keys](#primary-keys) + - [UUID and ULID Keys](#uuid-and-ulid-keys) - [Timestamps](#timestamps) - [Database Connections](#database-connections) - [Default Attribute Values](#default-attribute-values) + - [Configuring Eloquent Strictness](#configuring-eloquent-strictness) - [Retrieving Models](#retrieving-models) - [Collections](#collections) - [Chunking Results](#chunking-results) @@ -15,9 +17,9 @@ - [Cursors](#cursors) - [Advanced Subqueries](#advanced-subqueries) - [Retrieving Single Models / Aggregates](#retrieving-single-models) - - [Retrieving Or Creating Models](#retrieving-or-creating-models) + - [Retrieving or Creating Models](#retrieving-or-creating-models) - [Retrieving Aggregates](#retrieving-aggregates) -- [Inserting & Updating Models](#inserting-and-updating-models) +- [Inserting and Updating Models](#inserting-and-updating-models) - [Inserts](#inserts) - [Updates](#updates) - [Mass Assignment](#mass-assignment) @@ -30,6 +32,7 @@ - [Query Scopes](#query-scopes) - [Global Scopes](#global-scopes) - [Local Scopes](#local-scopes) + - [Pending Attributes](#pending-attributes) - [Comparing Models](#comparing-models) - [Events](#events) - [Using Closures](#events-using-closures) @@ -41,7 +44,8 @@ Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well. -> {tip} Before getting started, be sure to configure a database connection in your application's `config/database.php` configuration file. For more information on configuring your database, check out [the database configuration documentation](/docs/{{version}}/database#configuration). +> [!NOTE] +> Before getting started, be sure to configure a database connection in your application's `config/database.php` configuration file. For more information on configuring your database, check out [the database configuration documentation](/docs/{{version}}/database#configuration). ## Generating Model Classes @@ -85,9 +89,20 @@ php artisan make:model Flight -mfsc # Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests... php artisan make:model Flight --all +php artisan make:model Flight -a # Generate a pivot model... php artisan make:model Member --pivot +php artisan make:model Member -p +``` + + +#### Inspecting Models + +Sometimes it can be difficult to determine all of a model's available attributes and relationships just by skimming its code. Instead, try the `model:show` Artisan command, which provides a convenient overview of all the model's attributes and relations: + +```shell +php artisan model:show Flight ``` @@ -95,16 +110,18 @@ php artisan make:model Member --pivot Models generated by the `make:model` command will be placed in the `app/Models` directory. Let's examine a basic model class and discuss some of Eloquent's key conventions: - ### Table Names @@ -113,210 +130,336 @@ After glancing at the example above, you may have noticed that we did not tell E If your model's corresponding database table does not fit this convention, you may manually specify the model's table name by defining a `table` property on the model: - ### Primary Keys Eloquent will also assume that each model's corresponding database table has a primary key column named `id`. If necessary, you may define a protected `$primaryKey` property on your model to specify a different column that serves as your model's primary key: - #### "Composite" Primary Keys Eloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by Eloquent models. However, you are free to add additional multi-column, unique indexes to your database tables in addition to the table's uniquely identifying primary key. + +### UUID and ULID Keys + +Instead of using auto-incrementing integers as your Eloquent model's primary keys, you may choose to use UUIDs instead. UUIDs are universally unique alpha-numeric identifiers that are 36 characters long. + +If you would like a model to use a UUID key instead of an auto-incrementing integer key, you may use the `Illuminate\Database\Eloquent\Concerns\HasUuids` trait on the model. Of course, you should ensure that the model has a [UUID equivalent primary key column](/docs/{{version}}/migrations#column-method-uuid): + +```php +use Illuminate\Database\Eloquent\Concerns\HasUuids; +use Illuminate\Database\Eloquent\Model; + +class Article extends Model +{ + use HasUuids; + + // ... +} + +$article = Article::create(['title' => 'Traveling to Europe']); + +$article->id; // "8f8e8478-9035-4d23-b9a7-62f4d2612ce5" +``` + +By default, The `HasUuids` trait will generate ["ordered" UUIDs](/docs/{{version}}/strings#method-str-ordered-uuid) for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically. + +You can override the UUID generation process for a given model by defining a `newUniqueId` method on the model. In addition, you may specify which columns should receive UUIDs by defining a `uniqueIds` method on the model: + +```php +use Ramsey\Uuid\Uuid; + +/** + * Generate a new UUID for the model. + */ +public function newUniqueId(): string +{ + return (string) Uuid::uuid4(); +} + +/** + * Get the columns that should receive a unique identifier. + * + * @return array + */ +public function uniqueIds(): array +{ + return ['id', 'discount_code']; +} +``` + +If you wish, you may choose to utilize "ULIDs" instead of UUIDs. ULIDs are similar to UUIDs; however, they are only 26 characters in length. Like ordered UUIDs, ULIDs are lexicographically sortable for efficient database indexing. To utilize ULIDs, you should use the `Illuminate\Database\Eloquent\Concerns\HasUlids` trait on your model. You should also ensure that the model has a [ULID equivalent primary key column](/docs/{{version}}/migrations#column-method-ulid): + +```php +use Illuminate\Database\Eloquent\Concerns\HasUlids; +use Illuminate\Database\Eloquent\Model; + +class Article extends Model +{ + use HasUlids; + + // ... +} + +$article = Article::create(['title' => 'Traveling to Asia']); + +$article->id; // "01gd4d3tgrrfqeda94gdbtdk5c" +``` + ### Timestamps -By default, Eloquent expects `created_at` and `updated_at` columns to exist on your model's corresponding database table. Eloquent will automatically set these column's values when models are created or updated. If you do not want these columns to be automatically managed by Eloquent, you should define a `$timestamps` property on your model with a value of `false`: +By default, Eloquent expects `created_at` and `updated_at` columns to exist on your model's corresponding database table. Eloquent will automatically set these column's values when models are created or updated. If you do not want these columns to be automatically managed by Eloquent, you should define a `$timestamps` property on your model with a value of `false`: - $post->increment('reads')); +``` ### Database Connections By default, all Eloquent models will use the default database connection that is configured for your application. If you would like to specify a different connection that should be used when interacting with a particular model, you should define a `$connection` property on the model: - ### Default Attribute Values -By default, a newly instantiated model instance will not contain any attribute values. If you would like to define the default values for some of your model's attributes, you may define an `$attributes` property on your model: +By default, a newly instantiated model instance will not contain any attribute values. If you would like to define the default values for some of your model's attributes, you may define an `$attributes` property on your model. Attribute values placed in the `$attributes` array should be in their raw, "storable" format as if they were just read from the database: - false, - ]; - } +class Flight extends Model +{ + /** + * The model's default values for attributes. + * + * @var array + */ + protected $attributes = [ + 'options' => '[]', + 'delayed' => false, + ]; +} +``` + + +### Configuring Eloquent Strictness + +Laravel offers several methods that allow you to configure Eloquent's behavior and "strictness" in a variety of situations. + +First, the `preventLazyLoading` method accepts an optional boolean argument that indicates if lazy loading should be prevented. For example, you may wish to only disable lazy loading in non-production environments so that your production environment will continue to function normally even if a lazy loaded relationship is accidentally present in production code. Typically, this method should be invoked in the `boot` method of your application's `AppServiceProvider`: + +```php +use Illuminate\Database\Eloquent\Model; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Model::preventLazyLoading(! $this->app->isProduction()); +} +``` + +Also, you may instruct Laravel to throw an exception when attempting to fill an unfillable attribute by invoking the `preventSilentlyDiscardingAttributes` method. This can help prevent unexpected errors during local development when attempting to set an attribute that has not been added to the model's `fillable` array: + +```php +Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction()); +``` ## Retrieving Models -Once you have created a model and [its associated database table](/docs/{{version}}/migrations#writing-migrations), you are ready to start retrieving data from your database. You can think of each Eloquent model as a powerful [query builder](/docs/{{version}}/queries) allowing you to fluently query the database table associated with the model. The model's `all` method will retrieve all of the records from the model's associated database table: +Once you have created a model and [its associated database table](/docs/{{version}}/migrations#generating-migrations), you are ready to start retrieving data from your database. You can think of each Eloquent model as a powerful [query builder](/docs/{{version}}/queries) allowing you to fluently query the database table associated with the model. The model's `all` method will retrieve all of the records from the model's associated database table: - use App\Models\Flight; +```php +use App\Models\Flight; - foreach (Flight::all() as $flight) { - echo $flight->name; - } +foreach (Flight::all() as $flight) { + echo $flight->name; +} +``` #### Building Queries The Eloquent `all` method will return all of the results in the model's table. However, since each Eloquent model serves as a [query builder](/docs/{{version}}/queries), you may add additional constraints to queries and then invoke the `get` method to retrieve the results: - $flights = Flight::where('active', 1) - ->orderBy('name') - ->take(10) - ->get(); +```php +$flights = Flight::where('active', 1) + ->orderBy('name') + ->limit(10) + ->get(); +``` -> {tip} Since Eloquent models are query builders, you should review all of the methods provided by Laravel's [query builder](/docs/{{version}}/queries). You may use any of these methods when writing your Eloquent queries. +> [!NOTE] +> Since Eloquent models are query builders, you should review all of the methods provided by Laravel's [query builder](/docs/{{version}}/queries). You may use any of these methods when writing your Eloquent queries. #### Refreshing Models If you already have an instance of an Eloquent model that was retrieved from the database, you can "refresh" the model using the `fresh` and `refresh` methods. The `fresh` method will re-retrieve the model from the database. The existing model instance will not be affected: - $flight = Flight::where('number', 'FR 900')->first(); +```php +$flight = Flight::where('number', 'FR 900')->first(); - $freshFlight = $flight->fresh(); +$freshFlight = $flight->fresh(); +``` The `refresh` method will re-hydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well: - $flight = Flight::where('number', 'FR 900')->first(); +```php +$flight = Flight::where('number', 'FR 900')->first(); - $flight->number = 'FR 456'; +$flight->number = 'FR 456'; - $flight->refresh(); +$flight->refresh(); - $flight->number; // "FR 900" +$flight->number; // "FR 900" +``` ### Collections @@ -328,7 +471,7 @@ The Eloquent `Collection` class extends Laravel's base `Illuminate\Support\Colle ```php $flights = Flight::where('destination', 'Paris')->get(); -$flights = $flights->reject(function ($flight) { +$flights = $flights->reject(function (Flight $flight) { return $flight->cancelled; }); ``` @@ -352,10 +495,11 @@ The `chunk` method will retrieve a subset of Eloquent models, passing them to a ```php use App\Models\Flight; +use Illuminate\Database\Eloquent\Collection; -Flight::chunk(200, function ($flights) { +Flight::chunk(200, function (Collection $flights) { foreach ($flights as $flight) { - // + // ... } }); ``` @@ -366,21 +510,34 @@ If you are filtering the results of the `chunk` method based on a column that yo ```php Flight::where('departed', true) - ->chunkById(200, function ($flights) { + ->chunkById(200, function (Collection $flights) { $flights->each->update(['departed' => false]); - }, $column = 'id'); + }, column: 'id'); +``` + +Since the `chunkById` and `lazyById` methods add their own "where" conditions to the query being executed, you should typically [logically group](/docs/{{version}}/queries#logical-grouping) your own conditions within a closure: + +```php +Flight::where(function ($query) { + $query->where('delayed', true)->orWhere('cancelled', true); +})->chunkById(200, function (Collection $flights) { + $flights->each->update([ + 'departed' => false, + 'cancelled' => true + ]); +}, column: 'id'); ``` ### Chunking Using Lazy Collections -The `lazy` method works similarly to [the `chunk` method](#chunking-results) in the sense that, behind the scenes, it executes the query in chunks. However, instead of passing each chunk directly into a callback as is, the `lazy` method returns a flattened [`LazyCollection`](/docs/{{version}}/collections#lazy-collections) of Eloquent models, which lets you interact with the results as a single stream: +The `lazy` method works similarly to [the `chunk` method](#chunking-results) in the sense that, behind the scenes, it executes the query in chunks. However, instead of passing each chunk directly into a callback as is, the `lazy` method returns a flattened [LazyCollection](/docs/{{version}}/collections#lazy-collections) of Eloquent models, which lets you interact with the results as a single stream: ```php use App\Models\Flight; foreach (Flight::lazy() as $flight) { - // + // ... } ``` @@ -388,7 +545,7 @@ If you are filtering the results of the `lazy` method based on a column that you ```php Flight::where('departed', true) - ->lazyById(200, $column = 'id') + ->lazyById(200, column: 'id') ->each->update(['departed' => false]); ``` @@ -401,7 +558,8 @@ Similar to the `lazy` method, the `cursor` method may be used to significantly r The `cursor` method will only execute a single database query; however, the individual Eloquent models will not be hydrated until they are actually iterated over. Therefore, only one Eloquent model is kept in memory at any given time while iterating over the cursor. -> {note} Since the `cursor` method only ever holds a single Eloquent model in memory at a time, it cannot eager load relationships. If you need to eager load relationships, consider using [the `lazy` method](#streaming-results-lazily) instead. +> [!WARNING] +> Since the `cursor` method only ever holds a single Eloquent model in memory at a time, it cannot eager load relationships. If you need to eager load relationships, consider using [the `lazy` method](#chunking-using-lazy-collections) instead. Internally, the `cursor` method uses PHP [generators](https://www.php.net/manual/en/language.generators.overview.php) to implement this functionality: @@ -409,7 +567,7 @@ Internally, the `cursor` method uses PHP [generators](https://www.php.net/manual use App\Models\Flight; foreach (Flight::where('destination', 'Zurich')->cursor() as $flight) { - // + // ... } ``` @@ -418,7 +576,7 @@ The `cursor` returns an `Illuminate\Support\LazyCollection` instance. [Lazy coll ```php use App\Models\User; -$users = User::cursor()->filter(function ($user) { +$users = User::cursor()->filter(function (User $user) { return $user->id > 500; }); @@ -427,7 +585,7 @@ foreach ($users as $user) { } ``` -Although the `cursor` method uses far less memory than a regular query (by only holding a single Eloquent model in memory at a time), it will still eventually run out of memory. This is [due to PHP's PDO driver internally caching all raw query results in its buffer](https://www.php.net/manual/en/mysqlinfo.concepts.buffering.php). If you're dealing with a very large number of Eloquent records, consider using [the `lazy` method](#streaming-results-lazily) instead. +Although the `cursor` method uses far less memory than a regular query (by only holding a single Eloquent model in memory at a time), it will still eventually run out of memory. This is [due to PHP's PDO driver internally caching all raw query results in its buffer](https://www.php.net/manual/en/mysqlinfo.concepts.buffering.php). If you're dealing with a very large number of Eloquent records, consider using [the `lazy` method](#chunking-using-lazy-collections) instead. ### Advanced Subqueries @@ -439,151 +597,174 @@ Eloquent also offers advanced subquery support, which allows you to pull informa Using the subquery functionality available to the query builder's `select` and `addSelect` methods, we can select all of the `destinations` and the name of the flight that most recently arrived at that destination using a single query: - use App\Models\Destination; - use App\Models\Flight; +```php +use App\Models\Destination; +use App\Models\Flight; - return Destination::addSelect(['last_flight' => Flight::select('name') - ->whereColumn('destination_id', 'destinations.id') - ->orderByDesc('arrived_at') - ->limit(1) - ])->get(); +return Destination::addSelect(['last_flight' => Flight::select('name') + ->whereColumn('destination_id', 'destinations.id') + ->orderByDesc('arrived_at') + ->limit(1) +])->get(); +``` #### Subquery Ordering In addition, the query builder's `orderBy` function supports subqueries. Continuing to use our flight example, we may use this functionality to sort all destinations based on when the last flight arrived at that destination. Again, this may be done while executing a single database query: - return Destination::orderByDesc( - Flight::select('arrived_at') - ->whereColumn('destination_id', 'destinations.id') - ->orderByDesc('arrived_at') - ->limit(1) - )->get(); +```php +return Destination::orderByDesc( + Flight::select('arrived_at') + ->whereColumn('destination_id', 'destinations.id') + ->orderByDesc('arrived_at') + ->limit(1) +)->get(); +``` ## Retrieving Single Models / Aggregates In addition to retrieving all of the records matching a given query, you may also retrieve single records using the `find`, `first`, or `firstWhere` methods. Instead of returning a collection of models, these methods return a single model instance: - use App\Models\Flight; +```php +use App\Models\Flight; - // Retrieve a model by its primary key... - $flight = Flight::find(1); +// Retrieve a model by its primary key... +$flight = Flight::find(1); - // Retrieve the first model matching the query constraints... - $flight = Flight::where('active', 1)->first(); +// Retrieve the first model matching the query constraints... +$flight = Flight::where('active', 1)->first(); - // Alternative to retrieving the first model matching the query constraints... - $flight = Flight::firstWhere('active', 1); +// Alternative to retrieving the first model matching the query constraints... +$flight = Flight::firstWhere('active', 1); +``` -Sometimes you may wish to retrieve the first result of a query or perform some other action if no results are found. The `firstOr` method will return the first result matching the query or, if no results are found, execute the given closure. The value returned by the closure will be considered the result of the `firstOr` method: +Sometimes you may wish to perform some other action if no results are found. The `findOr` and `firstOr` methods will return a single model instance or, if no results are found, execute the given closure. The value returned by the closure will be considered the result of the method: - $model = Flight::where('legs', '>', 3)->firstOr(function () { - // ... - }); +```php +$flight = Flight::findOr(1, function () { + // ... +}); + +$flight = Flight::where('legs', '>', 3)->firstOr(function () { + // ... +}); +``` #### Not Found Exceptions Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The `findOrFail` and `firstOrFail` methods will retrieve the first result of the query; however, if no result is found, an `Illuminate\Database\Eloquent\ModelNotFoundException` will be thrown: - $flight = Flight::findOrFail(1); +```php +$flight = Flight::findOrFail(1); - $flight = Flight::where('legs', '>', 3)->firstOrFail(); +$flight = Flight::where('legs', '>', 3)->firstOrFail(); +``` If the `ModelNotFoundException` is not caught, a 404 HTTP response is automatically sent back to the client: - use App\Models\Flight; +```php +use App\Models\Flight; - Route::get('/api/flights/{id}', function ($id) { - return Flight::findOrFail($id); - }); +Route::get('/api/flights/{id}', function (string $id) { + return Flight::findOrFail($id); +}); +``` -### Retrieving Or Creating Models +### Retrieving or Creating Models -The `firstOrCreate` method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument: +The `firstOrCreate` method will attempt to locate a database record using the given column / value pairs. If the model cannot be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument. The `firstOrNew` method, like `firstOrCreate`, will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by `firstOrNew` has not yet been persisted to the database. You will need to manually call the `save` method to persist it: - use App\Models\Flight; - - // Retrieve flight by name or create it if it doesn't exist... - $flight = Flight::firstOrCreate([ - 'name' => 'London to Paris' - ]); - - // Retrieve flight by name or create it with the name, delayed, and arrival_time attributes... - $flight = Flight::firstOrCreate( - ['name' => 'London to Paris'], - ['delayed' => 1, 'arrival_time' => '11:30'] - ); - - // Retrieve flight by name or instantiate a new Flight instance... - $flight = Flight::firstOrNew([ - 'name' => 'London to Paris' - ]); +```php +use App\Models\Flight; - // Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes... - $flight = Flight::firstOrNew( - ['name' => 'Tokyo to Sydney'], - ['delayed' => 1, 'arrival_time' => '11:30'] - ); +// Retrieve flight by name or create it if it doesn't exist... +$flight = Flight::firstOrCreate([ + 'name' => 'London to Paris' +]); + +// Retrieve flight by name or create it with the name, delayed, and arrival_time attributes... +$flight = Flight::firstOrCreate( + ['name' => 'London to Paris'], + ['delayed' => 1, 'arrival_time' => '11:30'] +); + +// Retrieve flight by name or instantiate a new Flight instance... +$flight = Flight::firstOrNew([ + 'name' => 'London to Paris' +]); + +// Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes... +$flight = Flight::firstOrNew( + ['name' => 'Tokyo to Sydney'], + ['delayed' => 1, 'arrival_time' => '11:30'] +); +``` ### Retrieving Aggregates When interacting with Eloquent models, you may also use the `count`, `sum`, `max`, and other [aggregate methods](/docs/{{version}}/queries#aggregates) provided by the Laravel [query builder](/docs/{{version}}/queries). As you might expect, these methods return a scalar value instead of an Eloquent model instance: - $count = Flight::where('active', 1)->count(); +```php +$count = Flight::where('active', 1)->count(); - $max = Flight::where('active', 1)->max('price'); +$max = Flight::where('active', 1)->max('price'); +``` -## Inserting & Updating Models +## Inserting and Updating Models ### Inserts Of course, when using Eloquent, we don't only need to retrieve models from the database. We also need to insert new records. Thankfully, Eloquent makes it simple. To insert a new record into the database, you should instantiate a new model instance and set attributes on the model. Then, call the `save` method on the model instance: - name = $request->name; - - $flight->save(); - } + // Validate the request... + + $flight = new Flight; + + $flight->name = $request->name; + + $flight->save(); + + return redirect('/flights'); } +} +``` In this example, we assign the `name` field from the incoming HTTP request to the `name` attribute of the `App\Models\Flight` model instance. When we call the `save` method, a record will be inserted into the database. The model's `created_at` and `updated_at` timestamps will automatically be set when the `save` method is called, so there is no need to set them manually. Alternatively, you may use the `create` method to "save" a new model using a single PHP statement. The inserted model instance will be returned to you by the `create` method: - use App\Models\Flight; +```php +use App\Models\Flight; - $flight = Flight::create([ - 'name' => 'London to Paris', - ]); +$flight = Flight::create([ + 'name' => 'London to Paris', +]); +``` However, before using the `create` method, you will need to specify either a `fillable` or `guarded` property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default. To learn more about mass assignment, please consult the [mass assignment documentation](#mass-assignment). @@ -592,100 +773,168 @@ However, before using the `create` method, you will need to specify either a `fi The `save` method may also be used to update models that already exist in the database. To update a model, you should retrieve it and set any attributes you wish to update. Then, you should call the model's `save` method. Again, the `updated_at` timestamp will automatically be updated, so there is no need to manually set its value: - use App\Models\Flight; +```php +use App\Models\Flight; + +$flight = Flight::find(1); + +$flight->name = 'Paris to London'; + +$flight->save(); +``` + +Occasionally, you may need to update an existing model or create a new model if no matching model exists. Like the `firstOrCreate` method, the `updateOrCreate` method persists the model, so there's no need to manually call the `save` method. + +In the example below, if a flight exists with a `departure` location of `Oakland` and a `destination` location of `San Diego`, its `price` and `discounted` columns will be updated. If no such flight exists, a new flight will be created which has the attributes resulting from merging the first argument array with the second argument array: + +```php +$flight = Flight::updateOrCreate( + ['departure' => 'Oakland', 'destination' => 'San Diego'], + ['price' => 99, 'discounted' => 1] +); +``` - $flight = Flight::find(1); +When using methods such as `firstOrCreate` or `updateOrCreate`, you may not know whether a new model has been created or an existing one has been updated. The `wasRecentlyCreated` property indicates if the model was created during its current lifecycle: - $flight->name = 'Paris to London'; +```php +$flight = Flight::updateOrCreate( + // ... +); - $flight->save(); +if ($flight->wasRecentlyCreated) { + // New flight record was inserted... +} +``` #### Mass Updates Updates can also be performed against models that match a given query. In this example, all flights that are `active` and have a `destination` of `San Diego` will be marked as delayed: - Flight::where('active', 1) - ->where('destination', 'San Diego') - ->update(['delayed' => 1]); +```php +Flight::where('active', 1) + ->where('destination', 'San Diego') + ->update(['delayed' => 1]); +``` The `update` method expects an array of column and value pairs representing the columns that should be updated. The `update` method returns the number of affected rows. -> {note} When issuing a mass update via Eloquent, the `saving`, `saved`, `updating`, and `updated` model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update. +> [!WARNING] +> When issuing a mass update via Eloquent, the `saving`, `saved`, `updating`, and `updated` model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update. #### Examining Attribute Changes Eloquent provides the `isDirty`, `isClean`, and `wasChanged` methods to examine the internal state of your model and determine how its attributes have changed from when the model was originally retrieved. -The `isDirty` method determines if any of the model's attributes have been changed since the model was retrieved. You may pass a specific attribute name or an array of attributes to the `isDirty` method to determine if any of the attributes are "dirty". The `isClean` will determine if an attribute has remained unchanged since the model was retrieved. This method also accepts an optional attribute argument: +The `isDirty` method determines if any of the model's attributes have been changed since the model was retrieved. You may pass a specific attribute name or an array of attributes to the `isDirty` method to determine if any of the attributes are "dirty". The `isClean` method will determine if an attribute has remained unchanged since the model was retrieved. This method also accepts an optional attribute argument: - use App\Models\User; +```php +use App\Models\User; - $user = User::create([ - 'first_name' => 'Taylor', - 'last_name' => 'Otwell', - 'title' => 'Developer', - ]); +$user = User::create([ + 'first_name' => 'Taylor', + 'last_name' => 'Otwell', + 'title' => 'Developer', +]); - $user->title = 'Painter'; +$user->title = 'Painter'; - $user->isDirty(); // true - $user->isDirty('title'); // true - $user->isDirty('first_name'); // false - $user->isDirty(['first_name', 'title']); // true +$user->isDirty(); // true +$user->isDirty('title'); // true +$user->isDirty('first_name'); // false +$user->isDirty(['first_name', 'title']); // true - $user->isClean(); // false - $user->isClean('title'); // false - $user->isClean('first_name'); // true - $user->isClean(['first_name', 'title']); // false +$user->isClean(); // false +$user->isClean('title'); // false +$user->isClean('first_name'); // true +$user->isClean(['first_name', 'title']); // false - $user->save(); +$user->save(); - $user->isDirty(); // false - $user->isClean(); // true +$user->isDirty(); // false +$user->isClean(); // true +``` The `wasChanged` method determines if any attributes were changed when the model was last saved within the current request cycle. If needed, you may pass an attribute name to see if a particular attribute was changed: - $user = User::create([ - 'first_name' => 'Taylor', - 'last_name' => 'Otwell', - 'title' => 'Developer', - ]); +```php +$user = User::create([ + 'first_name' => 'Taylor', + 'last_name' => 'Otwell', + 'title' => 'Developer', +]); - $user->title = 'Painter'; +$user->title = 'Painter'; - $user->save(); +$user->save(); - $user->wasChanged(); // true - $user->wasChanged('title'); // true - $user->wasChanged(['title', 'slug']); // true - $user->wasChanged('first_name'); // false - $user->wasChanged(['first_name', 'title']); // true +$user->wasChanged(); // true +$user->wasChanged('title'); // true +$user->wasChanged(['title', 'slug']); // true +$user->wasChanged('first_name'); // false +$user->wasChanged(['first_name', 'title']); // true +``` The `getOriginal` method returns an array containing the original attributes of the model regardless of any changes to the model since it was retrieved. If needed, you may pass a specific attribute name to get the original value of a particular attribute: - $user = User::find(1); +```php +$user = User::find(1); + +$user->name; // John +$user->email; // john@example.com + +$user->name = 'Jack'; +$user->name; // Jack + +$user->getOriginal('name'); // John +$user->getOriginal(); // Array of original attributes... +``` + +The `getChanges` method returns an array containing the attributes that changed when the model was last saved, while the `getPrevious` method returns an array containing the original attribute values before the model was last saved: + +```php +$user = User::find(1); + +$user->name; // John +$user->email; // john@example.com - $user->name; // John - $user->email; // john@example.com +$user->update([ + 'name' => 'Jack', + 'email' => 'jack@example.com', +]); - $user->name = "Jack"; - $user->name; // Jack +$user->getChanges(); - $user->getOriginal('name'); // John - $user->getOriginal(); // Array of original attributes... +/* + [ + 'name' => 'Jack', + 'email' => 'jack@example.com', + ] +*/ + +$user->getPrevious(); + +/* + [ + 'name' => 'John', + 'email' => 'john@example.com', + ] +*/ +``` ### Mass Assignment You may use the `create` method to "save" a new model using a single PHP statement. The inserted model instance will be returned to you by the method: - use App\Models\Flight; +```php +use App\Models\Flight; - $flight = Flight::create([ - 'name' => 'London to Paris', - ]); +$flight = Flight::create([ + 'name' => 'London to Paris', +]); +``` However, before using the `create` method, you will need to specify either a `fillable` or `guarded` property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default. @@ -693,181 +942,239 @@ A mass assignment vulnerability occurs when a user passes an unexpected HTTP req So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the `$fillable` property on the model. For example, let's make the `name` attribute of our `Flight` model mass assignable: - + */ + protected $fillable = ['name']; +} +``` Once you have specified which attributes are mass assignable, you may use the `create` method to insert a new record in the database. The `create` method returns the newly created model instance: - $flight = Flight::create(['name' => 'London to Paris']); +```php +$flight = Flight::create(['name' => 'London to Paris']); +``` If you already have a model instance, you may use the `fill` method to populate it with an array of attributes: - $flight->fill(['name' => 'Amsterdam to Frankfurt']); +```php +$flight->fill(['name' => 'Amsterdam to Frankfurt']); +``` -#### Mass Assignment & JSON Columns +#### Mass Assignment and JSON Columns When assigning JSON columns, each column's mass assignable key must be specified in your model's `$fillable` array. For security, Laravel does not support updating nested JSON attributes when using the `guarded` property: - /** - * The attributes that are mass assignable. - * - * @var array - */ - protected $fillable = [ - 'options->enabled', - ]; +```php +/** + * The attributes that are mass assignable. + * + * @var array + */ +protected $fillable = [ + 'options->enabled', +]; +``` #### Allowing Mass Assignment If you would like to make all of your attributes mass assignable, you may define your model's `$guarded` property as an empty array. If you choose to unguard your model, you should take special care to always hand-craft the arrays passed to Eloquent's `fill`, `create`, and `update` methods: - /** - * The attributes that aren't mass assignable. - * - * @var array - */ - protected $guarded = []; +```php +/** + * The attributes that aren't mass assignable. + * + * @var array|bool + */ +protected $guarded = []; +``` - -### Upserts + +#### Mass Assignment Exceptions -Occasionally, you may need to update an existing model or create a new model if no matching model exists. Like the `firstOrCreate` method, the `updateOrCreate` method persists the model, so there's no need to manually call the `save` method. +By default, attributes that are not included in the `$fillable` array are silently discarded when performing mass-assignment operations. In production, this is expected behavior; however, during local development it can lead to confusion as to why model changes are not taking effect. -In the example below, if a flight exists with a `departure` location of `Oakland` and a `destination` location of `San Diego`, its `price` and `discounted` columns will be updated. If no such flight exists, a new flight will be created which has the attributes resulting from merging the first argument array with the second argument array: +If you wish, you may instruct Laravel to throw an exception when attempting to fill an unfillable attribute by invoking the `preventSilentlyDiscardingAttributes` method. Typically, this method should be invoked in the `boot` method of your application's `AppServiceProvider` class: - $flight = Flight::updateOrCreate( - ['departure' => 'Oakland', 'destination' => 'San Diego'], - ['price' => 99, 'discounted' => 1] - ); +```php +use Illuminate\Database\Eloquent\Model; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Model::preventSilentlyDiscardingAttributes($this->app->isLocal()); +} +``` -If you would like to perform multiple "upserts" in a single query, then you should use the `upsert` method instead. The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database. The `upsert` method will automatically set the `created_at` and `updated_at` timestamps if timestamps are enabled on the model: + +### Upserts + +Eloquent's `upsert` method may be used to update or create records in a single, atomic operation. The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database. The `upsert` method will automatically set the `created_at` and `updated_at` timestamps if timestamps are enabled on the model: - Flight::upsert([ - ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99], - ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150] - ], ['departure', 'destination'], ['price']); +```php +Flight::upsert([ + ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99], + ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150] +], uniqueBy: ['departure', 'destination'], update: ['price']); +``` + +> [!WARNING] +> All databases except SQL Server require the columns in the second argument of the `upsert` method to have a "primary" or "unique" index. In addition, the MariaDB and MySQL database drivers ignore the second argument of the `upsert` method and always use the "primary" and "unique" indexes of the table to detect existing records. ## Deleting Models To delete a model, you may call the `delete` method on the model instance: - use App\Models\Flight; +```php +use App\Models\Flight; - $flight = Flight::find(1); +$flight = Flight::find(1); - $flight->delete(); +$flight->delete(); +``` -You may call the `truncate` method to delete all of the model's associated database records. The `truncate` operation will also reset any auto-incrementing IDs on the model's associated table: + +#### Deleting an Existing Model by its Primary Key - Flight::truncate(); +In the example above, we are retrieving the model from the database before calling the `delete` method. However, if you know the primary key of the model, you may delete the model without explicitly retrieving it by calling the `destroy` method. In addition to accepting the single primary key, the `destroy` method will accept multiple primary keys, an array of primary keys, or a [collection](/docs/{{version}}/collections) of primary keys: - -#### Deleting An Existing Model By Its Primary Key +```php +Flight::destroy(1); -In the example above, we are retrieving the model from the database before calling the `delete` method. However, if you know the primary key of the model, you may delete the model without explicitly retrieving it by calling the `destroy` method. In addition to accepting the single primary key, the `destroy` method will accept multiple primary keys, an array of primary keys, or a [collection](/docs/{{version}}/collections) of primary keys: +Flight::destroy(1, 2, 3); - Flight::destroy(1); +Flight::destroy([1, 2, 3]); - Flight::destroy(1, 2, 3); +Flight::destroy(collect([1, 2, 3])); +``` - Flight::destroy([1, 2, 3]); +If you are utilizing [soft deleting models](#soft-deleting), you may permanently delete models via the `forceDestroy` method: - Flight::destroy(collect([1, 2, 3])); +```php +Flight::forceDestroy(1); +``` -> {note} The `destroy` method loads each model individually and calls the `delete` method so that the `deleting` and `deleted` events are properly dispatched for each model. +> [!WARNING] +> The `destroy` method loads each model individually and calls the `delete` method so that the `deleting` and `deleted` events are properly dispatched for each model. #### Deleting Models Using Queries Of course, you may build an Eloquent query to delete all models matching your query's criteria. In this example, we will delete all flights that are marked as inactive. Like mass updates, mass deletes will not dispatch model events for the models that are deleted: - $deleted = Flight::where('active', 0)->delete(); +```php +$deleted = Flight::where('active', 0)->delete(); +``` + +To delete all models in a table, you should execute a query without adding any conditions: -> {note} When executing a mass delete statement via Eloquent, the `deleting` and `deleted` model events will not be dispatched for the deleted models. This is because the models are never actually retrieved when executing the delete statement. +```php +$deleted = Flight::query()->delete(); +``` + +> [!WARNING] +> When executing a mass delete statement via Eloquent, the `deleting` and `deleted` model events will not be dispatched for the deleted models. This is because the models are never actually retrieved when executing the delete statement. ### Soft Deleting In addition to actually removing records from your database, Eloquent can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a `deleted_at` attribute is set on the model indicating the date and time at which the model was "deleted". To enable soft deletes for a model, add the `Illuminate\Database\Eloquent\SoftDeletes` trait to the model: - {tip} The `SoftDeletes` trait will automatically cast the `deleted_at` attribute to a `DateTime` / `Carbon` instance for you. +> [!NOTE] +> The `SoftDeletes` trait will automatically cast the `deleted_at` attribute to a `DateTime` / `Carbon` instance for you. You should also add the `deleted_at` column to your database table. The Laravel [schema builder](/docs/{{version}}/migrations) contains a helper method to create this column: - use Illuminate\Database\Schema\Blueprint; - use Illuminate\Support\Facades\Schema; +```php +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; - Schema::table('flights', function (Blueprint $table) { - $table->softDeletes(); - }); +Schema::table('flights', function (Blueprint $table) { + $table->softDeletes(); +}); - Schema::table('flights', function (Blueprint $table) { - $table->dropSoftDeletes(); - }); +Schema::table('flights', function (Blueprint $table) { + $table->dropSoftDeletes(); +}); +``` Now, when you call the `delete` method on the model, the `deleted_at` column will be set to the current date and time. However, the model's database record will be left in the table. When querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results. To determine if a given model instance has been soft deleted, you may use the `trashed` method: - if ($flight->trashed()) { - // - } +```php +if ($flight->trashed()) { + // ... +} +``` #### Restoring Soft Deleted Models Sometimes you may wish to "un-delete" a soft deleted model. To restore a soft deleted model, you may call the `restore` method on a model instance. The `restore` method will set the model's `deleted_at` column to `null`: - $flight->restore(); +```php +$flight->restore(); +``` You may also use the `restore` method in a query to restore multiple models. Again, like other "mass" operations, this will not dispatch any model events for the models that are restored: - Flight::withTrashed() - ->where('airline_id', 1) - ->restore(); +```php +Flight::withTrashed() + ->where('airline_id', 1) + ->restore(); +``` The `restore` method may also be used when building [relationship](/docs/{{version}}/eloquent-relationships) queries: - $flight->history()->restore(); +```php +$flight->history()->restore(); +``` #### Permanently Deleting Models Sometimes you may need to truly remove a model from your database. You may use the `forceDelete` method to permanently remove a soft deleted model from the database table: - $flight->forceDelete(); +```php +$flight->forceDelete(); +``` You may also use the `forceDelete` method when building Eloquent relationship queries: - $flight->history()->forceDelete(); +```php +$flight->history()->forceDelete(); +``` ### Querying Soft Deleted Models @@ -877,88 +1184,94 @@ You may also use the `forceDelete` method when building Eloquent relationship qu As noted above, soft deleted models will automatically be excluded from query results. However, you may force soft deleted models to be included in a query's results by calling the `withTrashed` method on the query: - use App\Models\Flight; +```php +use App\Models\Flight; - $flights = Flight::withTrashed() - ->where('account_id', 1) - ->get(); +$flights = Flight::withTrashed() + ->where('account_id', 1) + ->get(); +``` The `withTrashed` method may also be called when building a [relationship](/docs/{{version}}/eloquent-relationships) query: - $flight->history()->withTrashed()->get(); +```php +$flight->history()->withTrashed()->get(); +``` #### Retrieving Only Soft Deleted Models The `onlyTrashed` method will retrieve **only** soft deleted models: - $flights = Flight::onlyTrashed() - ->where('airline_id', 1) - ->get(); +```php +$flights = Flight::onlyTrashed() + ->where('airline_id', 1) + ->get(); +``` ## Pruning Models Sometimes you may want to periodically delete models that are no longer needed. To accomplish this, you may add the `Illuminate\Database\Eloquent\Prunable` or `Illuminate\Database\Eloquent\MassPrunable` trait to the models you would like to periodically prune. After adding one of the traits to the model, implement a `prunable` method which returns an Eloquent query builder that resolves the models that are no longer needed: - subMonth()); - } - } +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Prunable; -When marking models as `Prunable`, you may also define a `pruning` method on the model. This method will be called before the model is deleted. This method can be useful for deleting any additional resources associated with the model, such as stored files, before the model is permanently removed from the database: +class Flight extends Model +{ + use Prunable; /** - * Prepare the model for pruning. - * - * @return void + * Get the prunable model query. */ - protected function pruning() + public function prunable(): Builder { - // + return static::where('created_at', '<=', now()->subMonth()); } +} +``` -After configuring your prunable model, you should schedule the `model:prune` Artisan command in your application's `App\Console\Kernel` class. You are free to choose the appropriate interval at which this command should be run: +When marking models as `Prunable`, you may also define a `pruning` method on the model. This method will be called before the model is deleted. This method can be useful for deleting any additional resources associated with the model, such as stored files, before the model is permanently removed from the database: - /** - * Define the application's command schedule. - * - * @param \Illuminate\Console\Scheduling\Schedule $schedule - * @return void - */ - protected function schedule(Schedule $schedule) - { - $schedule->command('model:prune')->daily(); - } +```php +/** + * Prepare the model for pruning. + */ +protected function pruning(): void +{ + // ... +} +``` + +After configuring your prunable model, you should schedule the `model:prune` Artisan command in your application's `routes/console.php` file. You are free to choose the appropriate interval at which this command should be run: + +```php +use Illuminate\Support\Facades\Schedule; + +Schedule::command('model:prune')->daily(); +``` Behind the scenes, the `model:prune` command will automatically detect "Prunable" models within your application's `app/Models` directory. If your models are in a different location, you may use the `--model` option to specify the model class names: - $schedule->command('model:prune', [ - '--model' => [Address::class, Flight::class], - ])->daily(); +```php +Schedule::command('model:prune', [ + '--model' => [Address::class, Flight::class], +])->daily(); +``` If you wish to exclude certain models from being pruned while pruning all other detected models, you may use the `--except` option: - $schedule->command('model:prune', [ - '--except' => [Address::class, Flight::class], - ])->daily(); +```php +Schedule::command('model:prune', [ + '--except' => [Address::class, Flight::class], +])->daily(); +``` You may test your `prunable` query by executing the `model:prune` command with the `--pretend` option. When pretending, the `model:prune` command will simply report how many records would be pruned if the command were to actually run: @@ -966,69 +1279,75 @@ You may test your `prunable` query by executing the `model:prune` command with t php artisan model:prune --pretend ``` -> {note} Soft deleting models will be permanently deleted (`forceDelete`) if they match the prunable query. +> [!WARNING] +> Soft deleting models will be permanently deleted (`forceDelete`) if they match the prunable query. #### Mass Pruning When models are marked with the `Illuminate\Database\Eloquent\MassPrunable` trait, models are deleted from the database using mass-deletion queries. Therefore, the `pruning` method will not be invoked, nor will the `deleting` and `deleted` model events be dispatched. This is because the models are never actually retrieved before deletion, thus making the pruning process much more efficient: - subMonth()); - } + return static::where('created_at', '<=', now()->subMonth()); } +} +``` ## Replicating Models You may create an unsaved copy of an existing model instance using the `replicate` method. This method is particularly useful when you have model instances that share many of the same attributes: - use App\Models\Address; +```php +use App\Models\Address; - $shipping = Address::create([ - 'type' => 'shipping', - 'line_1' => '123 Example Street', - 'city' => 'Victorville', - 'state' => 'CA', - 'postcode' => '90001', - ]); +$shipping = Address::create([ + 'type' => 'shipping', + 'line_1' => '123 Example Street', + 'city' => 'Victorville', + 'state' => 'CA', + 'postcode' => '90001', +]); - $billing = $shipping->replicate()->fill([ - 'type' => 'billing' - ]); +$billing = $shipping->replicate()->fill([ + 'type' => 'billing' +]); - $billing->save(); +$billing->save(); +``` To exclude one or more attributes from being replicated to the new model, you may pass an array to the `replicate` method: - $flight = Flight::create([ - 'destination' => 'LAX', - 'origin' => 'LHR', - 'last_flown' => '2020-03-04 11:00:00', - 'last_pilot_id' => 747, - ]); - - $flight = $flight->replicate([ - 'last_flown', - 'last_pilot_id' - ]); +```php +$flight = Flight::create([ + 'destination' => 'LAX', + 'origin' => 'LHR', + 'last_flown' => '2020-03-04 11:00:00', + 'last_pilot_id' => 747, +]); + +$flight = $flight->replicate([ + 'last_flown', + 'last_pilot_id' +]); +``` ## Query Scopes @@ -1038,62 +1357,85 @@ To exclude one or more attributes from being replicated to the new model, you ma Global scopes allow you to add constraints to all queries for a given model. Laravel's own [soft delete](#soft-deleting) functionality utilizes global scopes to only retrieve "non-deleted" models from the database. Writing your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constraints. + +#### Generating Scopes + +To generate a new global scope, you may invoke the `make:scope` Artisan command, which will place the generated scope in your application's `app/Models/Scopes` directory: + +```shell +php artisan make:scope AncientScope +``` + #### Writing Global Scopes -Writing a global scope is simple. First, define a class that implements the `Illuminate\Database\Eloquent\Scope` interface. Laravel does not have a conventional location where you should place scope classes, so you are free to place this class in any directory that you wish. +Writing a global scope is simple. First, use the `make:scope` command to generate a class that implements the `Illuminate\Database\Eloquent\Scope` interface. The `Scope` interface requires you to implement one method: `apply`. The `apply` method may add `where` constraints or other types of clauses to the query as needed: -The `Scope` interface requires you to implement one method: `apply`. The `apply` method may add `where` constraints or other types of clauses to the query as needed: - - where('created_at', '<', now()->subYears(2000)); - } + $builder->where('created_at', '<', now()->subYears(2000)); } +} +``` -> {tip} If your global scope is adding columns to the select clause of the query, you should use the `addSelect` method instead of `select`. This will prevent the unintentional replacement of the query's existing select clause. +> [!NOTE] +> If your global scope is adding columns to the select clause of the query, you should use the `addSelect` method instead of `select`. This will prevent the unintentional replacement of the query's existing select clause. #### Applying Global Scopes -To assign a global scope to a model, you should override the model's `booted` method and invoke the model's `addGlobalScope` method. The `addGlobalScope` method accepts an instance of your scope as its only argument: +To assign a global scope to a model, you may simply place the `ScopedBy` attribute on the model: + +```php +where('created_at', '<', now()->subYears(2000)); - }); - } + static::addGlobalScope('ancient', function (Builder $builder) { + $builder->where('created_at', '<', now()->subYears(2000)); + }); } +} +``` #### Removing Global Scopes If you would like to remove a global scope for a given query, you may use the `withoutGlobalScope` method. This method accepts the class name of the global scope as its only argument: - User::withoutGlobalScope(AncientScope::class)->get(); +```php +User::withoutGlobalScope(AncientScope::class)->get(); +``` Or, if you defined the global scope using a closure, you should pass the string name that you assigned to the global scope: - User::withoutGlobalScope('ancient')->get(); - -If you would like to remove several or even all of the query's global scopes, you may use the `withoutGlobalScopes` method: +```php +User::withoutGlobalScope('ancient')->get(); +``` - // Remove all of the global scopes... - User::withoutGlobalScopes()->get(); +If you would like to remove several or even all of the query's global scopes, you may use the `withoutGlobalScopes` and `withoutGlobalScopesExcept` methods: - // Remove some of the global scopes... - User::withoutGlobalScopes([ - FirstScope::class, SecondScope::class - ])->get(); +```php +// Remove all of the global scopes... +User::withoutGlobalScopes()->get(); + +// Remove some of the global scopes... +User::withoutGlobalScopes([ + FirstScope::class, SecondScope::class +])->get(); + +// Remove all global scopes except the given ones... +User::withoutGlobalScopesExcept([ + SecondScope::class, +])->get(); +``` ### Local Scopes -Local scopes allow you to define common sets of query constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, prefix an Eloquent model method with `scope`. +Local scopes allow you to define common sets of query constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, add the `Scope` attribute to an Eloquent method. Scopes should always return the same query builder instance or `void`: - where('votes', '>', 100); + } - class User extends Model + /** + * Scope a query to only include active users. + */ + #[Scope] + protected function active(Builder $query): void { - /** - * Scope a query to only include popular users. - * - * @param \Illuminate\Database\Eloquent\Builder $query - * @return \Illuminate\Database\Eloquent\Builder - */ - public function scopePopular($query) - { - return $query->where('votes', '>', 100); - } - - /** - * Scope a query to only include active users. - * - * @param \Illuminate\Database\Eloquent\Builder $query - * @return void - */ - public function scopeActive($query) - { - $query->where('active', 1); - } + $query->where('active', 1); } +} +``` -#### Utilizing A Local Scope +#### Utilizing a Local Scope -Once the scope has been defined, you may call the scope methods when querying the model. However, you should not include the `scope` prefix when calling the method. You can even chain calls to various scopes: +Once the scope has been defined, you may call the scope methods when querying the model. You can even chain calls to various scopes: - use App\Models\User; +```php +use App\Models\User; - $users = User::popular()->active()->orderBy('created_at')->get(); +$users = User::popular()->active()->orderBy('created_at')->get(); +``` Combining multiple Eloquent model scopes via an `or` query operator may require the use of closures to achieve the correct [logical grouping](/docs/{{version}}/queries#logical-grouping): - $users = User::popular()->orWhere(function (Builder $query) { - $query->active(); - })->get(); +```php +$users = User::popular()->orWhere(function (Builder $query) { + $query->active(); +})->get(); +``` However, since this can be cumbersome, Laravel provides a "higher order" `orWhere` method that allows you to fluently chain scopes together without the use of closures: - $users = App\Models\User::popular()->orWhere->active()->get(); +```php +$users = User::popular()->orWhere->active()->get(); +``` #### Dynamic Scopes Sometimes you may wish to define a scope that accepts parameters. To get started, just add your additional parameters to your scope method's signature. Scope parameters should be defined after the `$query` parameter: - where('type', $type); - } + $query->where('type', $type); } +} +``` Once the expected arguments have been added to your scope method's signature, you may pass the arguments when calling the scope: - $users = User::ofType('admin')->get(); +```php +$users = User::ofType('admin')->get(); +``` + + +### Pending Attributes + +If you would like to use scopes to create models that have the same attributes as those used to constrain the scope, you may use the `withAttributes` method when building the scope query: + +```php +withAttributes([ + 'hidden' => true, + ]); + } +} +``` + +The `withAttributes` method will add `where` conditions to the query using the given attributes, and it will also add the given attributes to any models created via the scope: + +```php +$draft = Post::draft()->create(['title' => 'In Progress']); + +$draft->hidden; // true +``` + +To instruct the `withAttributes` method to not add `where` conditions to the query, you may set the `asConditions` argument to `false`: + +```php +$query->withAttributes([ + 'hidden' => true, +], asConditions: false); +``` ## Comparing Models Sometimes you may need to determine if two models are the "same" or not. The `is` and `isNot` methods may be used to quickly verify two models have the same primary key, table, and database connection or not: - if ($post->is($anotherPost)) { - // - } +```php +if ($post->is($anotherPost)) { + // ... +} - if ($post->isNot($anotherPost)) { - // - } +if ($post->isNot($anotherPost)) { + // ... +} +``` The `is` and `isNot` methods are also available when using the `belongsTo`, `hasOne`, `morphTo`, and `morphOne` [relationships](/docs/{{version}}/eloquent-relationships). This method is particularly helpful when you would like to compare a related model without issuing a query to retrieve that model: - if ($post->author()->is($user)) { - // - } +```php +if ($post->author()->is($user)) { + // ... +} +``` ## Events -> {tip} Want to broadcast your Eloquent events directly to your client-side application? Check out Laravel's [model event broadcasting](/docs/{{version}}/broadcasting#model-broadcasting). +> [!NOTE] +> Want to broadcast your Eloquent events directly to your client-side application? Check out Laravel's [model event broadcasting](/docs/{{version}}/broadcasting#model-broadcasting). -Eloquent models dispatch several events, allowing you to hook into the following moments in a model's lifecycle: `retrieved`, `creating`, `created`, `updating`, `updated`, `saving`, `saved`, `deleting`, `deleted`, `restoring`, `restored`, and `replicating`. +Eloquent models dispatch several events, allowing you to hook into the following moments in a model's lifecycle: `retrieved`, `creating`, `created`, `updating`, `updated`, `saving`, `saved`, `deleting`, `deleted`, `trashed`, `forceDeleting`, `forceDeleted`, `restoring`, `restored`, and `replicating`. The `retrieved` event will dispatch when an existing model is retrieved from the database. When a new model is saved for the first time, the `creating` and `created` events will dispatch. The `updating` / `updated` events will dispatch when an existing model is modified and the `save` method is called. The `saving` / `saved` events will dispatch when a model is created or updated - even if the model's attributes have not been changed. Event names ending with `-ing` are dispatched before any changes to the model are persisted, while events ending with `-ed` are dispatched after the changes to the model are persisted. To start listening to model events, define a `$dispatchesEvents` property on your Eloquent model. This property maps various points of the Eloquent model's lifecycle to your own [event classes](/docs/{{version}}/events). Each model event class should expect to receive an instance of the affected model via its constructor: - UserSaved::class, - 'deleted' => UserDeleted::class, - ]; - } +class User extends Authenticatable +{ + use Notifiable; + + /** + * The event map for the model. + * + * @var array + */ + protected $dispatchesEvents = [ + 'saved' => UserSaved::class, + 'deleted' => UserDeleted::class, + ]; +} +``` After defining and mapping your Eloquent events, you may use [event listeners](/docs/{{version}}/events#defining-listeners) to handle the events. -> {note} When issuing a mass update or delete query via Eloquent, the `saved`, `updated`, `deleting`, and `deleted` model events will not be dispatched for the affected models. This is because the models are never actually retrieved when performing mass updates or deletes. +> [!WARNING] +> When issuing a mass update or delete query via Eloquent, the `saved`, `updated`, `deleting`, and `deleted` model events will not be dispatched for the affected models. This is because the models are never actually retrieved when performing mass updates or deletes. ### Using Closures Instead of using custom event classes, you may register closures that execute when various model events are dispatched. Typically, you should register these closures in the `booted` method of your model: - ### Observers @@ -1339,144 +1757,147 @@ If you are listening for many events on a given model, you may use observers to php artisan make:observer UserObserver --model=User ``` -This command will place the new observer in your `App/Observers` directory. If this directory does not exist, Artisan will create it for you. Your fresh observer will look like the following: +This command will place the new observer in your `app/Observers` directory. If this directory does not exist, Artisan will create it for you. Your fresh observer will look like the following: - [UserObserver::class], - ]; + public function forceDeleted(User $user): void + { + // ... + } +} +``` + +To register an observer, you may place the `ObservedBy` attribute on the corresponding model: + +```php +use App\Observers\UserObserver; +use Illuminate\Database\Eloquent\Attributes\ObservedBy; + +#[ObservedBy([UserObserver::class])] +class User extends Authenticatable +{ + // +} +``` + +Or, you may manually register an observer by invoking the `observe` method on the model you wish to observe. You may register observers in the `boot` method of your application's `AppServiceProvider` class: + +```php +use App\Models\User; +use App\Observers\UserObserver; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + User::observe(UserObserver::class); +} +``` -> {tip} There are additional events an observer can listen to, such as `saving` and `retrieved`. These events are described within the [events](#events) documentation. +> [!NOTE] +> There are additional events an observer can listen to, such as `saving` and `retrieved`. These events are described within the [events](#events) documentation. -#### Observers & Database Transactions +#### Observers and Database Transactions -When models are being created within a database transaction, you may want to instruct an observer to only execute its event handlers after the database transaction is committed. You may accomplish this by defining an `$afterCommit` property on the observer. If a database transaction is not in progress, the event handlers will execute immediately: +When models are being created within a database transaction, you may want to instruct an observer to only execute its event handlers after the database transaction is committed. You may accomplish this by implementing the `ShouldHandleEventsAfterCommit` interface on your observer. If a database transaction is not in progress, the event handlers will execute immediately: - ### Muting Events You may occasionally need to temporarily "mute" all events fired by a model. You may achieve this using the `withoutEvents` method. The `withoutEvents` method accepts a closure as its only argument. Any code executed within this closure will not dispatch model events, and any value returned by the closure will be returned by the `withoutEvents` method: - use App\Models\User; +```php +use App\Models\User; - $user = User::withoutEvents(function () use () { - User::findOrFail(1)->delete(); +$user = User::withoutEvents(function () { + User::findOrFail(1)->delete(); - return User::find(2); - }); + return User::find(2); +}); +``` -#### Saving A Single Model Without Events +#### Saving a Single Model Without Events Sometimes you may wish to "save" a given model without dispatching any events. You may accomplish this using the `saveQuietly` method: - $user = User::findOrFail(1); +```php +$user = User::findOrFail(1); + +$user->name = 'Victoria Faith'; - $user->name = 'Victoria Faith'; +$user->saveQuietly(); +``` + +You may also "update", "delete", "soft delete", "restore", and "replicate" a given model without dispatching any events: - $user->saveQuietly(); +```php +$user->deleteQuietly(); +$user->forceDeleteQuietly(); +$user->restoreQuietly(); +``` diff --git a/encryption.md b/encryption.md index 42cc97df4d1..6123a6ce6bc 100644 --- a/encryption.md +++ b/encryption.md @@ -2,61 +2,80 @@ - [Introduction](#introduction) - [Configuration](#configuration) -- [Using The Encrypter](#using-the-encrypter) + - [Gracefully Rotating Encryption Keys](#gracefully-rotating-encryption-keys) +- [Using the Encrypter](#using-the-encrypter) ## Introduction -Laravel's encryption services provide a simple, convenient interface for encrypting and decrypting text via OpenSSL using AES-256 and AES-128 encryption. All of Laravel's encrypted values are signed using a message authentication code (MAC) so that their underlying value can not be modified or tampered with once encrypted. +Laravel's encryption services provide a simple, convenient interface for encrypting and decrypting text via OpenSSL using AES-256 and AES-128 encryption. All of Laravel's encrypted values are signed using a message authentication code (MAC) so that their underlying value cannot be modified or tampered with once encrypted. ## Configuration Before using Laravel's encrypter, you must set the `key` configuration option in your `config/app.php` configuration file. This configuration value is driven by the `APP_KEY` environment variable. You should use the `php artisan key:generate` command to generate this variable's value since the `key:generate` command will use PHP's secure random bytes generator to build a cryptographically secure key for your application. Typically, the value of the `APP_KEY` environment variable will be generated for you during [Laravel's installation](/docs/{{version}}/installation). + +### Gracefully Rotating Encryption Keys + +If you change your application's encryption key, all authenticated user sessions will be logged out of your application. This is because every cookie, including session cookies, are encrypted by Laravel. In addition, it will no longer be possible to decrypt any data that was encrypted with your previous encryption key. + +To mitigate this issue, Laravel allows you to list your previous encryption keys in your application's `APP_PREVIOUS_KEYS` environment variable. This variable may contain a comma-delimited list of all of your previous encryption keys: + +```ini +APP_KEY="base64:J63qRTDLub5NuZvP+kb8YIorGS6qFYHKVo6u7179stY=" +APP_PREVIOUS_KEYS="base64:2nLsGFGzyoae2ax3EF2Lyq/hH6QghBGLIq5uL+Gp8/w=" +``` + +When you set this environment variable, Laravel will always use the "current" encryption key when encrypting values. However, when decrypting values, Laravel will first try the current key, and if decryption fails using the current key, Laravel will try all previous keys until one of the keys is able to decrypt the value. + +This approach to graceful decryption allows users to keep using your application uninterrupted even if your encryption key is rotated. + -## Using The Encrypter +## Using the Encrypter -#### Encrypting A Value +#### Encrypting a Value You may encrypt a value using the `encryptString` method provided by the `Crypt` facade. All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC). The integrated message authentication code will prevent the decryption of any values that have been tampered with by malicious users: - user()->fill([ - 'token' => Crypt::encryptString($request->token), - ])->save(); - } + $request->user()->fill([ + 'token' => Crypt::encryptString($request->token), + ])->save(); + + return redirect('/secrets'); } +} +``` -#### Decrypting A Value +#### Decrypting a Value -You may decrypt values using the `decryptString` method provided by the `Crypt` facade. If the value can not be properly decrypted, such as when the message authentication code is invalid, an `Illuminate\Contracts\Encryption\DecryptException` will be thrown: +You may decrypt values using the `decryptString` method provided by the `Crypt` facade. If the value cannot be properly decrypted, such as when the message authentication code is invalid, an `Illuminate\Contracts\Encryption\DecryptException` will be thrown: - use Illuminate\Contracts\Encryption\DecryptException; - use Illuminate\Support\Facades\Crypt; +```php +use Illuminate\Contracts\Encryption\DecryptException; +use Illuminate\Support\Facades\Crypt; - try { - $decrypted = Crypt::decryptString($encryptedValue); - } catch (DecryptException $e) { - // - } +try { + $decrypted = Crypt::decryptString($encryptedValue); +} catch (DecryptException $e) { + // ... +} +``` diff --git a/envoy.md b/envoy.md index 88483b61e31..89c0af51c6f 100644 --- a/envoy.md +++ b/envoy.md @@ -323,7 +323,7 @@ Envoy also supports sending notifications to [Telegram](https://telegram.org) af ### Microsoft Teams -Envoy also supports sending notifications to [Microsoft Teams](https://www.microsoft.com/en-us/microsoft-teams) after each task is executed. The `@microsoftTeams` directive accepts a Teams Webhook (required), a message, theme color (success, info, warning, error), and an array of options. You may retrieve your Teams Webook by creating a new [incoming webhook](https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook). The Teams API has many other attributes to customize your message box like title, summary, and sections. You can find more information on the [Microsoft Teams documentation](https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#example-of-connector-message). You should pass the entire Webhook URL into the `@microsoftTeams` directive: +Envoy also supports sending notifications to [Microsoft Teams](https://www.microsoft.com/en-us/microsoft-teams) after each task is executed. The `@microsoftTeams` directive accepts a Teams Webhook (required), a message, theme color (success, info, warning, error), and an array of options. You may retrieve your Teams Webhook by creating a new [incoming webhook](https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook). The Teams API has many other attributes to customize your message box like title, summary, and sections. You can find more information on the [Microsoft Teams documentation](https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#example-of-connector-message). You should pass the entire Webhook URL into the `@microsoftTeams` directive: ```blade @finished diff --git a/errors.md b/errors.md index 94295e68cb4..dc6e7ea0584 100644 --- a/errors.md +++ b/errors.md @@ -2,18 +2,22 @@ - [Introduction](#introduction) - [Configuration](#configuration) -- [The Exception Handler](#the-exception-handler) +- [Handling Exceptions](#handling-exceptions) - [Reporting Exceptions](#reporting-exceptions) - - [Ignoring Exceptions By Type](#ignoring-exceptions-by-type) + - [Exception Log Levels](#exception-log-levels) + - [Ignoring Exceptions by Type](#ignoring-exceptions-by-type) - [Rendering Exceptions](#rendering-exceptions) - - [Reportable & Renderable Exceptions](#renderable-exceptions) + - [Reportable and Renderable Exceptions](#renderable-exceptions) +- [Throttling Reported Exceptions](#throttling-reported-exceptions) - [HTTP Exceptions](#http-exceptions) - [Custom HTTP Error Pages](#custom-http-error-pages) ## Introduction -When you start a new Laravel project, error and exception handling is already configured for you. The `App\Exceptions\Handler` class is where all exceptions thrown by your application are logged and then rendered to the user. We'll dive deeper into this class throughout this documentation. +When you start a new Laravel project, error and exception handling is already configured for you; however, at any point, you may use the `withExceptions` method in your application's `bootstrap/app.php` to manage how exceptions are reported and rendered by your application. + +The `$exceptions` object provided to the `withExceptions` closure is an instance of `Illuminate\Foundation\Configuration\Exceptions` and is responsible for managing exception handling in your application. We'll dive deeper into this object throughout this documentation. ## Configuration @@ -22,239 +26,459 @@ The `debug` option in your `config/app.php` configuration file determines how mu During local development, you should set the `APP_DEBUG` environment variable to `true`. **In your production environment, this value should always be `false`. If the value is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.** - -## The Exception Handler + +## Handling Exceptions ### Reporting Exceptions -All exceptions are handled by the `App\Exceptions\Handler` class. This class contains a `register` method where you may register custom exception reporting and rendering callbacks. We'll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like [Flare](https://flareapp.io), [Bugsnag](https://bugsnag.com) or [Sentry](https://github.com/getsentry/sentry-laravel). By default, exceptions will be logged based on your [logging](/docs/{{version}}/logging) configuration. However, you are free to log exceptions however you wish. +In Laravel, exception reporting is used to log exceptions or send them to an external service like [Sentry](https://github.com/getsentry/sentry-laravel) or [Flare](https://flareapp.io). By default, exceptions will be logged based on your [logging](/docs/{{version}}/logging) configuration. However, you are free to log exceptions however you wish. -For example, if you need to report different types of exceptions in different ways, you may use the `reportable` method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure: +If you need to report different types of exceptions in different ways, you may use the `report` exception method in your application's `bootstrap/app.php` to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will determine what type of exception the closure reports by examining the type-hint of the closure: - use App\Exceptions\InvalidOrderException; +```php +use App\Exceptions\InvalidOrderException; - /** - * Register the exception handling callbacks for the application. - * - * @return void - */ - public function register() - { - $this->reportable(function (InvalidOrderException $e) { - // - }); - } +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->report(function (InvalidOrderException $e) { + // ... + }); +}) +``` + +When you register a custom exception reporting callback using the `report` method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the `stop` method when defining your reporting callback or return `false` from the callback: -When you register a custom exception reporting callback using the `reportable` method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the `stop` method when defining your reporting callback or return `false` from the callback: +```php +use App\Exceptions\InvalidOrderException; - $this->reportable(function (InvalidOrderException $e) { - // +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->report(function (InvalidOrderException $e) { + // ... })->stop(); - $this->reportable(function (InvalidOrderException $e) { + $exceptions->report(function (InvalidOrderException $e) { return false; }); +}) +``` -> {tip} To customize the exception reporting for a given exception, you may also utilize [reportable exceptions](/docs/{{version}}/errors#renderable-exceptions). +> [!NOTE] +> To customize the exception reporting for a given exception, you may also utilize [reportable exceptions](/docs/{{version}}/errors#renderable-exceptions). #### Global Log Context -If available, Laravel automatically adds the current user's ID to every exception's log message as contextual data. You may define your own global contextual data by overriding the `context` method of your application's `App\Exceptions\Handler` class. This information will be included in every exception's log message written by your application: +If available, Laravel automatically adds the current user's ID to every exception's log message as contextual data. You may define your own global contextual data using the `context` exception method in your application's `bootstrap/app.php` file. This information will be included in every exception's log message written by your application: - /** - * Get the default context variables for logging. - * - * @return array - */ - protected function context() - { - return array_merge(parent::context(), [ - 'foo' => 'bar', - ]); - } +```php +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->context(fn () => [ + 'foo' => 'bar', + ]); +}) +``` #### Exception Log Context -While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a `context` method on one of your application's custom exceptions, you may specify any data relevant to that exception that should be added to the exception's log entry: +While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a `context` method on one of your application's exceptions, you may specify any data relevant to that exception that should be added to the exception's log entry: - $this->orderId]; - } + /** + * Get the exception's context information. + * + * @return array + */ + public function context(): array + { + return ['order_id' => $this->orderId]; } +} +``` #### The `report` Helper -Sometimes you may need to report an exception but continue handling the current request. The `report` helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user: +Sometimes you may need to report an exception but continue handling the current request. The `report` helper function allows you to quickly report an exception without rendering an error page to the user: - public function isValid($value) - { - try { - // Validate the value... - } catch (Throwable $e) { - report($e); +```php +public function isValid(string $value): bool +{ + try { + // Validate the value... + } catch (Throwable $e) { + report($e); - return false; - } + return false; } +} +``` + + +#### Deduplicating Reported Exceptions + +If you are using the `report` function throughout your application, you may occasionally report the same exception multiple times, creating duplicate entries in your logs. + +If you would like to ensure that a single instance of an exception is only ever reported once, you may invoke the `dontReportDuplicates` exception method in your application's `bootstrap/app.php` file: + +```php +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->dontReportDuplicates(); +}) +``` + +Now, when the `report` helper is called with the same instance of an exception, only the first call will be reported: + +```php +$original = new RuntimeException('Whoops!'); + +report($original); // reported + +try { + throw $original; +} catch (Throwable $caught) { + report($caught); // ignored +} + +report($original); // ignored +report($caught); // ignored +``` + + +### Exception Log Levels + +When messages are written to your application's [logs](/docs/{{version}}/logging), the messages are written at a specified [log level](/docs/{{version}}/logging#log-levels), which indicates the severity or importance of the message being logged. + +As noted above, even when you register a custom exception reporting callback using the `report` method, Laravel will still log the exception using the default logging configuration for the application; however, since the log level can sometimes influence the channels on which a message is logged, you may wish to configure the log level that certain exceptions are logged at. + +To accomplish this, you may use the `level` exception method in your application's `bootstrap/app.php` file. This method receives the exception type as its first argument and the log level as its second argument: + +```php +use PDOException; +use Psr\Log\LogLevel; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->level(PDOException::class, LogLevel::CRITICAL); +}) +``` -### Ignoring Exceptions By Type +### Ignoring Exceptions by Type -When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application's exception handler contains a `$dontReport` property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic: +When building your application, there will be some types of exceptions you never want to report. To ignore these exceptions, you may use the `dontReport` exception method in your application's `bootstrap/app.php` file. Any class provided to this method will never be reported; however, they may still have custom rendering logic: - use App\Exceptions\InvalidOrderException; +```php +use App\Exceptions\InvalidOrderException; - /** - * A list of the exception types that should not be reported. - * - * @var array - */ - protected $dontReport = [ +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->dontReport([ InvalidOrderException::class, - ]; + ]); +}) +``` + +Alternatively, you may simply "mark" an exception class with the `Illuminate\Contracts\Debug\ShouldntReport` interface. When an exception is marked with this interface, it will never be reported by Laravel's exception handler: + +```php + {tip} Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP "not found" errors or 419 HTTP responses generated by invalid CSRF tokens. +```php +use App\Exceptions\InvalidOrderException; +use Throwable; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->dontReportWhen(function (Throwable $e) { + return $e instanceof PodcastProcessingException && + $e->reason() === 'Subscription expired'; + }); +}) +``` + +Internally, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP errors or 419 HTTP responses generated by invalid CSRF tokens. If you would like to instruct Laravel to stop ignoring a given type of exception, you may use the `stopIgnoring` exception method in your application's `bootstrap/app.php` file: + +```php +use Symfony\Component\HttpKernel\Exception\HttpException; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->stopIgnoring(HttpException::class); +}) +``` ### Rendering Exceptions -By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the `renderable` method of your exception handler. +By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this by using the `render` exception method in your application's `bootstrap/app.php` file. -The closure passed to the `renderable` method should return an instance of `Illuminate\Http\Response`, which may be generated via the `response` helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure: +The closure passed to the `render` method should return an instance of `Illuminate\Http\Response`, which may be generated via the `response` helper. Laravel will determine what type of exception the closure renders by examining the type-hint of the closure: - use App\Exceptions\InvalidOrderException; +```php +use App\Exceptions\InvalidOrderException; +use Illuminate\Http\Request; - /** - * Register the exception handling callbacks for the application. - * - * @return void - */ - public function register() - { - $this->renderable(function (InvalidOrderException $e, $request) { - return response()->view('errors.invalid-order', [], 500); - }); - } +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->render(function (InvalidOrderException $e, Request $request) { + return response()->view('errors.invalid-order', status: 500); + }); +}) +``` -You may also use the `renderable` method to override the rendering behavior for built-in Laravel or Symfony exceptions such as `NotFoundHttpException`. If the closure given to the `renderable` method does not return a value, Laravel's default exception rendering will be utilized: +You may also use the `render` method to override the rendering behavior for built-in Laravel or Symfony exceptions such as `NotFoundHttpException`. If the closure given to the `render` method does not return a value, Laravel's default exception rendering will be utilized: - use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +```php +use Illuminate\Http\Request; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; - /** - * Register the exception handling callbacks for the application. - * - * @return void - */ - public function register() - { - $this->renderable(function (NotFoundHttpException $e, $request) { - if ($request->is('api/*')) { - return response()->json([ - 'message' => 'Record not found.' - ], 404); - } - }); - } +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->render(function (NotFoundHttpException $e, Request $request) { + if ($request->is('api/*')) { + return response()->json([ + 'message' => 'Record not found.' + ], 404); + } + }); +}) +``` - -### Reportable & Renderable Exceptions + +#### Rendering Exceptions as JSON + +When rendering an exception, Laravel will automatically determine if the exception should be rendered as an HTML or JSON response based on the `Accept` header of the request. If you would like to customize how Laravel determines whether to render HTML or JSON exception responses, you may utilize the `shouldRenderJsonWhen` method: -Instead of type-checking exceptions in the exception handler's `register` method, you may define `report` and `render` methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework: +```php +use Illuminate\Http\Request; +use Throwable; - withExceptions(function (Exceptions $exceptions): void { + $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { + if ($request->is('admin/*')) { + return true; + } - namespace App\Exceptions; + return $request->expectsJson(); + }); +}) +``` - use Exception; + +#### Customizing the Exception Response - class InvalidOrderException extends Exception - { - /** - * Report the exception. - * - * @return bool|null - */ - public function report() - { - // - } +Rarely, you may need to customize the entire HTTP response rendered by Laravel's exception handler. To accomplish this, you may register a response customization closure using the `respond` method: - /** - * Render the exception into an HTTP response. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\Response - */ - public function render($request) - { - return response(...); +```php +use Symfony\Component\HttpFoundation\Response; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->respond(function (Response $response) { + if ($response->getStatusCode() === 419) { + return back()->with([ + 'message' => 'The page expired, please try again.', + ]); } - } -If your exception extends an exception that is already renderable, such as a built-in Laravel or Symfony exception, you may return `false` from the exception's `render` method to render the exception's default HTTP response: + return $response; + }); +}) +``` + + +### Reportable and Renderable Exceptions + +Instead of defining custom reporting and rendering behavior in your application's `bootstrap/app.php` file, you may define `report` and `render` methods directly on your application's exceptions. When these methods exist, they will automatically be called by the framework: + +```php + {tip} You may type-hint any required dependencies of the `report` method and they will automatically be injected into the method by Laravel's [service container](/docs/{{version}}/container). + return false; +} +``` + +> [!NOTE] +> You may type-hint any required dependencies of the `report` method and they will automatically be injected into the method by Laravel's [service container](/docs/{{version}}/container). + + +### Throttling Reported Exceptions + +If your application reports a very large number of exceptions, you may want to throttle how many exceptions are actually logged or sent to your application's external error tracking service. + +To take a random sample rate of exceptions, you may use the `throttle` exception method in your application's `bootstrap/app.php` file. The `throttle` method receives a closure that should return a `Lottery` instance: + +```php +use Illuminate\Support\Lottery; +use Throwable; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->throttle(function (Throwable $e) { + return Lottery::odds(1, 1000); + }); +}) +``` + +It is also possible to conditionally sample based on the exception type. If you would like to only sample instances of a specific exception class, you may return a `Lottery` instance only for that class: + +```php +use App\Exceptions\ApiMonitoringException; +use Illuminate\Support\Lottery; +use Throwable; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->throttle(function (Throwable $e) { + if ($e instanceof ApiMonitoringException) { + return Lottery::odds(1, 1000); + } + }); +}) +``` + +You may also rate limit exceptions logged or sent to an external error tracking service by returning a `Limit` instance instead of a `Lottery`. This is useful if you want to protect against sudden bursts of exceptions flooding your logs, for example, when a third-party service used by your application is down: + +```php +use Illuminate\Broadcasting\BroadcastException; +use Illuminate\Cache\RateLimiting\Limit; +use Throwable; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->throttle(function (Throwable $e) { + if ($e instanceof BroadcastException) { + return Limit::perMinute(300); + } + }); +}) +``` + +By default, limits will use the exception's class as the rate limit key. You can customize this by specifying your own key using the `by` method on the `Limit`: + +```php +use Illuminate\Broadcasting\BroadcastException; +use Illuminate\Cache\RateLimiting\Limit; +use Throwable; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->throttle(function (Throwable $e) { + if ($e instanceof BroadcastException) { + return Limit::perMinute(300)->by($e->getMessage()); + } + }); +}) +``` + +Of course, you may return a mixture of `Lottery` and `Limit` instances for different exceptions: + +```php +use App\Exceptions\ApiMonitoringException; +use Illuminate\Broadcasting\BroadcastException; +use Illuminate\Cache\RateLimiting\Limit; +use Illuminate\Support\Lottery; +use Throwable; + +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->throttle(function (Throwable $e) { + return match (true) { + $e instanceof BroadcastException => Limit::perMinute(300), + $e instanceof ApiMonitoringException => Lottery::odds(1, 1000), + default => Limit::none(), + }; + }); +}) +``` ## HTTP Exceptions -Some exceptions describe HTTP error codes from the server. For example, this may be a "page not found" error (404), an "unauthorized error" (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the `abort` helper: +Some exceptions describe HTTP error codes from the server. For example, this may be a "page not found" error (404), an "unauthorized error" (401), or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the `abort` helper: - abort(404); +```php +abort(404); +``` ### Custom HTTP Error Pages -Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a `resources/views/errors/404.blade.php` view template. This view will be rendered on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The `Symfony\Component\HttpKernel\Exception\HttpException` instance raised by the `abort` function will be passed to the view as an `$exception` variable: +Laravel makes it easy to display custom error pages for various HTTP status codes. For example, to customize the error page for 404 HTTP status codes, create a `resources/views/errors/404.blade.php` view template. This view will be rendered for all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The `Symfony\Component\HttpKernel\Exception\HttpException` instance raised by the `abort` function will be passed to the view as an `$exception` variable: -

{{ $exception->getMessage() }}

+```blade +

{{ $exception->getMessage() }}

+``` You may publish Laravel's default error page templates using the `vendor:publish` Artisan command. Once the templates have been published, you may customize them to your liking: @@ -266,3 +490,5 @@ php artisan vendor:publish --tag=laravel-errors #### Fallback HTTP Error Pages You may also define a "fallback" error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a `4xx.blade.php` template and a `5xx.blade.php` template in your application's `resources/views/errors` directory. + +When defining fallback error pages, the fallback pages will not affect `404`, `500`, and `503` error responses since Laravel has internal, dedicated pages for these status codes. To customize the pages rendered for these status codes, you should define a custom error page for each of them individually. diff --git a/events.md b/events.md index 653d4424a82..a5d0d189e9d 100644 --- a/events.md +++ b/events.md @@ -1,20 +1,28 @@ # Events - [Introduction](#introduction) -- [Registering Events & Listeners](#registering-events-and-listeners) - - [Generating Events & Listeners](#generating-events-and-listeners) - - [Manually Registering Events](#manually-registering-events) +- [Generating Events and Listeners](#generating-events-and-listeners) +- [Registering Events and Listeners](#registering-events-and-listeners) - [Event Discovery](#event-discovery) + - [Manually Registering Events](#manually-registering-events) + - [Closure Listeners](#closure-listeners) - [Defining Events](#defining-events) - [Defining Listeners](#defining-listeners) - [Queued Event Listeners](#queued-event-listeners) - - [Manually Interacting With The Queue](#manually-interacting-with-the-queue) - - [Queued Event Listeners & Database Transactions](#queued-event-listeners-and-database-transactions) + - [Manually Interacting With the Queue](#manually-interacting-with-the-queue) + - [Queued Event Listeners and Database Transactions](#queued-event-listeners-and-database-transactions) + - [Queued Listener Middleware](#queued-listener-middleware) + - [Encrypted Queued Listeners](#encrypted-queued-listeners) - [Handling Failed Jobs](#handling-failed-jobs) - [Dispatching Events](#dispatching-events) + - [Dispatching Events After Database Transactions](#dispatching-events-after-database-transactions) + - [Deferring Events](#deferring-events) - [Event Subscribers](#event-subscribers) - [Writing Event Subscribers](#writing-event-subscribers) - [Registering Event Subscribers](#registering-event-subscribers) +- [Testing](#testing) + - [Faking a Subset of Events](#faking-a-subset-of-events) + - [Scoped Events Fakes](#scoped-event-fakes) ## Introduction @@ -23,248 +31,251 @@ Laravel's events provide a simple observer pattern implementation, allowing you Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an `App\Events\OrderShipped` event which a listener can receive and use to dispatch a Slack notification. - -## Registering Events & Listeners - -The `App\Providers\EventServiceProvider` included with your Laravel application provides a convenient place to register all of your application's event listeners. The `listen` property contains an array of all events (keys) and their listeners (values). You may add as many events to this array as your application requires. For example, let's add an `OrderShipped` event: - - use App\Events\OrderShipped; - use App\Listeners\SendShipmentNotification; - - /** - * The event listener mappings for the application. - * - * @var array - */ - protected $listen = [ - OrderShipped::class => [ - SendShipmentNotification::class, - ], - ]; - -> {tip} The `event:list` command may be used to display a list of all events and listeners registered by your application. - -### Generating Events & Listeners +## Generating Events and Listeners -Of course, manually creating the files for each event and listener is cumbersome. Instead, add listeners and events to your `EventServiceProvider` and use the `event:generate` Artisan command. This command will generate any events or listeners that are listed in your `EventServiceProvider` that do not already exist: +To quickly generate events and listeners, you may use the `make:event` and `make:listener` Artisan commands: ```shell -php artisan event:generate +php artisan make:event PodcastProcessed + +php artisan make:listener SendPodcastNotification --event=PodcastProcessed ``` -Alternatively, you may use the `make:event` and `make:listener` Artisan commands to generate individual events and listeners: +For convenience, you may also invoke the `make:event` and `make:listener` Artisan commands without additional arguments. When you do so, Laravel will automatically prompt you for the class name and, when creating a listener, the event it should listen to: ```shell -php artisan make:event PodcastProcessed +php artisan make:event -php artisan make:listener SendPodcastNotification --event=PodcastProcessed +php artisan make:listener ``` - -### Manually Registering Events + +## Registering Events and Listeners -Typically, events should be registered via the `EventServiceProvider` `$listen` array; however, you may also register class or closure based event listeners manually in the `boot` method of your `EventServiceProvider`: + +### Event Discovery - use App\Events\PodcastProcessed; - use App\Listeners\SendPodcastNotification; - use Illuminate\Support\Facades\Event; +By default, Laravel will automatically find and register your event listeners by scanning your application's `Listeners` directory. When Laravel finds any listener class method that begins with `handle` or `__invoke`, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature: +```php +use App\Events\PodcastProcessed; + +class SendPodcastNotification +{ /** - * Register any other events for your application. - * - * @return void + * Handle the event. */ - public function boot() + public function handle(PodcastProcessed $event): void { - Event::listen( - PodcastProcessed::class, - [SendPodcastNotification::class, 'handle'] - ); - - Event::listen(function (PodcastProcessed $event) { - // - }); + // ... } +} +``` - -#### Queueable Anonymous Event Listeners +You may listen to multiple events using PHP's union types: -When registering closure based event listeners manually, you may wrap the listener closure within the `Illuminate\Events\queueable` function to instruct Laravel to execute the listener using the [queue](/docs/{{version}}/queues): +```php +/** + * Handle the event. + */ +public function handle(PodcastProcessed|PodcastPublished $event): void +{ + // ... +} +``` - use App\Events\PodcastProcessed; - use function Illuminate\Events\queueable; - use Illuminate\Support\Facades\Event; +If you plan to store your listeners in a different directory or within multiple directories, you may instruct Laravel to scan those directories using the `withEvents` method in your application's `bootstrap/app.php` file: - /** - * Register any other events for your application. - * - * @return void - */ - public function boot() - { - Event::listen(queueable(function (PodcastProcessed $event) { - // - })); - } +```php +->withEvents(discover: [ + __DIR__.'/../app/Domain/Orders/Listeners', +]) +``` -Like queued jobs, you may use the `onConnection`, `onQueue`, and `delay` methods to customize the execution of the queued listener: +You may scan for listeners in multiple similar directories using the `*` character as a wildcard: - Event::listen(queueable(function (PodcastProcessed $event) { - // - })->onConnection('redis')->onQueue('podcasts')->delay(now()->addSeconds(10))); +```php +->withEvents(discover: [ + __DIR__.'/../app/Domain/*/Listeners', +]) +``` -If you would like to handle anonymous queued listener failures, you may provide a closure to the `catch` method while defining the `queueable` listener. This closure will receive the event instance and the `Throwable` instance that caused the listener's failure: +The `event:list` command may be used to list all of the listeners registered within your application: - use App\Events\PodcastProcessed; - use function Illuminate\Events\queueable; - use Illuminate\Support\Facades\Event; - use Throwable; +```shell +php artisan event:list +``` - Event::listen(queueable(function (PodcastProcessed $event) { - // - })->catch(function (PodcastProcessed $event, Throwable $e) { - // The queued listener failed... - })); + +#### Event Discovery in Production - -#### Wildcard Event Listeners +To give your application a speed boost, you should cache a manifest of all of your application's listeners using the `optimize` or `event:cache` Artisan commands. Typically, this command should be run as part of your application's [deployment process](/docs/{{version}}/deployment#optimization). This manifest will be used by the framework to speed up the event registration process. The `event:clear` command may be used to destroy the event cache. + + +### Manually Registering Events + +Using the `Event` facade, you may manually register events and their corresponding listeners within the `boot` method of your application's `AppServiceProvider`: + +```php +use App\Domain\Orders\Events\PodcastProcessed; +use App\Domain\Orders\Listeners\SendPodcastNotification; +use Illuminate\Support\Facades\Event; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Event::listen( + PodcastProcessed::class, + SendPodcastNotification::class, + ); +} +``` + +The `event:list` command may be used to list all of the listeners registered within your application: + +```shell +php artisan event:list +``` -You may even register listeners using the `*` as a wildcard parameter, allowing you to catch multiple events on the same listener. Wildcard listeners receive the event name as their first argument and the entire event data array as their second argument: + +### Closure Listeners - Event::listen('event.*', function ($eventName, array $data) { - // +Typically, listeners are defined as classes; however, you may also manually register closure-based event listeners in the `boot` method of your application's `AppServiceProvider`: + +```php +use App\Events\PodcastProcessed; +use Illuminate\Support\Facades\Event; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Event::listen(function (PodcastProcessed $event) { + // ... }); +} +``` - -### Event Discovery + +#### Queueable Anonymous Event Listeners -Instead of registering events and listeners manually in the `$listen` array of the `EventServiceProvider`, you can enable automatic event discovery. When event discovery is enabled, Laravel will automatically find and register your events and listeners by scanning your application's `Listeners` directory. In addition, any explicitly defined events listed in the `EventServiceProvider` will still be registered. +When registering closure-based event listeners, you may wrap the listener closure within the `Illuminate\Events\queueable` function to instruct Laravel to execute the listener using the [queue](/docs/{{version}}/queues): -Laravel finds event listeners by scanning the listener classes using PHP's reflection services. When Laravel finds any listener class method that begins with `handle` or `__invoke`, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature: +```php +use App\Events\PodcastProcessed; +use function Illuminate\Events\queueable; +use Illuminate\Support\Facades\Event; - use App\Events\PodcastProcessed; +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Event::listen(queueable(function (PodcastProcessed $event) { + // ... + })); +} +``` - class SendPodcastNotification - { - /** - * Handle the given event. - * - * @param \App\Events\PodcastProcessed $event - * @return void - */ - public function handle(PodcastProcessed $event) - { - // - } - } +Like queued jobs, you may use the `onConnection`, `onQueue`, and `delay` methods to customize the execution of the queued listener: -Event discovery is disabled by default, but you can enable it by overriding the `shouldDiscoverEvents` method of your application's `EventServiceProvider`: +```php +Event::listen(queueable(function (PodcastProcessed $event) { + // ... +})->onConnection('redis')->onQueue('podcasts')->delay(now()->addSeconds(10))); +``` - /** - * Determine if events and listeners should be automatically discovered. - * - * @return bool - */ - public function shouldDiscoverEvents() - { - return true; - } +If you would like to handle anonymous queued listener failures, you may provide a closure to the `catch` method while defining the `queueable` listener. This closure will receive the event instance and the `Throwable` instance that caused the listener's failure: -By default, all listeners within your application's `app/Listeners` directory will be scanned. If you would like to define additional directories to scan, you may override the `discoverEventsWithin` method in your `EventServiceProvider`: +```php +use App\Events\PodcastProcessed; +use function Illuminate\Events\queueable; +use Illuminate\Support\Facades\Event; +use Throwable; + +Event::listen(queueable(function (PodcastProcessed $event) { + // ... +})->catch(function (PodcastProcessed $event, Throwable $e) { + // The queued listener failed... +})); +``` - /** - * Get the listener directories that should be used to discover events. - * - * @return array - */ - protected function discoverEventsWithin() - { - return [ - $this->app->path('Listeners'), - ]; - } + +#### Wildcard Event Listeners - -#### Event Discovery In Production +You may also register listeners using the `*` character as a wildcard parameter, allowing you to catch multiple events on the same listener. Wildcard listeners receive the event name as their first argument and the entire event data array as their second argument: -In production, it is not efficient for the framework to scan all of your listeners on every request. Therefore, during your deployment process, you should run the `event:cache` Artisan command to cache a manifest of all of your application's events and listeners. This manifest will be used by the framework to speed up the event registration process. The `event:clear` command may be used to destroy the cache. +```php +Event::listen('event.*', function (string $eventName, array $data) { + // ... +}); +``` ## Defining Events An event class is essentially a data container which holds the information related to the event. For example, let's assume an `App\Events\OrderShipped` event receives an [Eloquent ORM](/docs/{{version}}/eloquent) object: - order = $order; - } - } +class OrderShipped +{ + use Dispatchable, InteractsWithSockets, SerializesModels; + + /** + * Create a new event instance. + */ + public function __construct( + public Order $order, + ) {} +} +``` As you can see, this event class contains no logic. It is a container for the `App\Models\Order` instance that was purchased. The `SerializesModels` trait used by the event will gracefully serialize any Eloquent models if the event object is serialized using PHP's `serialize` function, such as when utilizing [queued listeners](#queued-event-listeners). ## Defining Listeners -Next, let's take a look at the listener for our example event. Event listeners receive event instances in their `handle` method. The `event:generate` and `make:listener` Artisan commands will automatically import the proper event class and type-hint the event on the `handle` method. Within the `handle` method, you may perform any actions necessary to respond to the event: +Next, let's take a look at the listener for our example event. Event listeners receive event instances in their `handle` method. The `make:listener` Artisan command, when invoked with the `--event` option, will automatically import the proper event class and type-hint the event in the `handle` method. Within the `handle` method, you may perform any actions necessary to respond to the event: - order... - } + /** + * Handle the event. + */ + public function handle(OrderShipped $event): void + { + // Access the order using $event->order... } +} +``` -> {tip} Your event listeners may also type-hint any dependencies they need on their constructors. All event listeners are resolved via the Laravel [service container](/docs/{{version}}/container), so dependencies will be injected automatically. +> [!NOTE] +> Your event listeners may also type-hint any dependencies they need on their constructors. All event listeners are resolved via the Laravel [service container](/docs/{{version}}/container), so dependencies will be injected automatically. #### Stopping The Propagation Of An Event @@ -276,284 +287,551 @@ Sometimes, you may wish to stop the propagation of an event to other listeners. Queueing listeners can be beneficial if your listener is going to perform a slow task such as sending an email or making an HTTP request. Before using queued listeners, make sure to [configure your queue](/docs/{{version}}/queues) and start a queue worker on your server or local development environment. -To specify that a listener should be queued, add the `ShouldQueue` interface to the listener class. Listeners generated by the `event:generate` and `make:listener` Artisan commands already have this interface imported into the current namespace so you can use it immediately: +To specify that a listener should be queued, add the `ShouldQueue` interface to the listener class. Listeners generated by the `make:listener` Artisan commands already have this interface imported into the current namespace so you can use it immediately: - -#### Customizing The Queue Connection & Queue Name +#### Customizing The Queue Connection, Name, & Delay If you would like to customize the queue connection, queue name, or queue delay time of an event listener, you may define the `$connection`, `$queue`, or `$delay` properties on your listener class: - highPriority ? 0 : 60; +} +``` #### Conditionally Queueing Listeners -Sometimes, you may need to determine whether a listener should be queued based on some data that are only available at runtime. To accomplish this, a `shouldQueue` method may be added to a listener to determine whether the listener should be queued. If the `shouldQueue` method returns `false`, the listener will not be executed: +Sometimes, you may need to determine whether a listener should be queued based on some data that are only available at runtime. To accomplish this, a `shouldQueue` method may be added to a listener to determine whether the listener should be queued. If the `shouldQueue` method returns `false`, the listener will not be queued: - order->subtotal >= 5000; - } + /** + * Determine whether the listener should be queued. + */ + public function shouldQueue(OrderCreated $event): bool + { + return $event->order->subtotal >= 5000; } +} +``` -### Manually Interacting With The Queue +### Manually Interacting With the Queue If you need to manually access the listener's underlying queue job's `delete` and `release` methods, you may do so using the `Illuminate\Queue\InteractsWithQueue` trait. This trait is imported by default on generated listeners and provides access to these methods: - release(30); - } + if ($condition) { + $this->release(30); } } +} +``` -### Queued Event Listeners & Database Transactions +### Queued Event Listeners and Database Transactions When queued listeners are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your listener depends on these models, unexpected errors can occur when the job that dispatches the queued listener is processed. -If your queue connection's `after_commit` configuration option is set to `false`, you may still indicate that a particular queued listener should be dispatched after all open database transactions have been committed by defining an `$afterCommit` property on the listener class: +If your queue connection's `after_commit` configuration option is set to `false`, you may still indicate that a particular queued listener should be dispatched after all open database transactions have been committed by implementing the `ShouldQueueAfterCommit` interface on the listener class: - [!NOTE] +> To learn more about working around these issues, please review the documentation regarding [queued jobs and database transactions](/docs/{{version}}/queues#jobs-and-database-transactions). + + +### Queued Listener Middleware + +Queued listeners can also utilize [job middleware](/docs/{{version}}/queues#job-middleware). Job middleware allow you to wrap custom logic around the execution of queued listeners, reducing boilerplate in the listeners themselves. After creating job middleware, they may be attached to a listener by returning them from the listener's `middleware` method: + +```php + + */ + public function middleware(OrderShipped $event): array + { + return [new RateLimited]; } +} +``` + + +#### Encrypted Queued Listeners -> {tip} To learn more about working around these issues, please review the documentation regarding [queued jobs and database transactions](/docs/{{version}}/queues#jobs-and-database-transactions). +Laravel allows you to ensure the privacy and integrity of a queued listener's data via [encryption](/docs/{{version}}/encryption). To get started, simply add the `ShouldBeEncrypted` interface to the listener class. Once this interface has been added to the class, Laravel will automatically encrypt your listener before pushing it onto a queue: + +```php + ### Handling Failed Jobs -Sometimes your queued event listeners may fail. If queued listener exceeds the maximum number of attempts as defined by your queue worker, the `failed` method will be called on your listener. The `failed` method receives the event instance and the `Throwable` that caused the failure: +Sometimes your queued event listeners may fail. If the queued listener exceeds the maximum number of attempts as defined by your queue worker, the `failed` method will be called on your listener. The `failed` method receives the event instance and the `Throwable` that caused the failure: - #### Specifying Queued Listener Maximum Attempts If one of your queued listeners is encountering an error, you likely do not want it to keep retrying indefinitely. Therefore, Laravel provides various ways to specify how many times or for how long a listener may be attempted. -You may define `$tries` property on your listener class to specify how many times the listener may be attempted before it is considered to have failed: +You may define a `tries` property or method on your listener class to specify how many times the listener may be attempted before it is considered to have failed: - addMinutes(5); +} +``` + +If both `retryUntil` and `tries` are defined, Laravel gives precedence to the `retryUntil` method. + + +#### Specifying Queued Listener Backoff + +If you would like to configure how many seconds Laravel should wait before retrying a listener that has encountered an exception, you may do so by defining a `backoff` property on your listener class: + +```php +/** + * The number of seconds to wait before retrying the queued listener. + * + * @var int + */ +public $backoff = 3; +``` + +If you require more complex logic for determining the listeners's backoff time, you may define a `backoff` method on your listener class: + +```php +/** + * Calculate the number of seconds to wait before retrying the queued listener. + */ +public function backoff(OrderShipped $event): int +{ + return 3; +} +``` + +You may easily configure "exponential" backoffs by returning an array of backoff values from the `backoff` method. In this example, the retry delay will be 1 second for the first retry, 5 seconds for the second retry, 10 seconds for the third retry, and 10 seconds for every subsequent retry if there are more attempts remaining: + +```php +/** + * Calculate the number of seconds to wait before retrying the queued listener. + * + * @return list + */ +public function backoff(OrderShipped $event): array +{ + return [1, 5, 10]; +} +``` + + +#### Specifying Queued Listener Max Exceptions + +Sometimes you may wish to specify that a queued listener may be attempted many times, but should fail if the retries are triggered by a given number of unhandled exceptions (as opposed to being released by the `release` method directly). To accomplish this, you may define a `maxExceptions` property on your listener class: + +```php +addMinutes(5); + // Process the event... } +} +``` + +In this example, the listener will be retried up to 25 times. However, the listener will fail if three unhandled exceptions are thrown by the listener. + + +#### Specifying Queued Listener Timeout + +Often, you know roughly how long you expect your queued listeners to take. For this reason, Laravel allows you to specify a "timeout" value. If a listener is processing for longer than the number of seconds specified by the timeout value, the worker processing the listener will exit with an error. You may define the maximum number of seconds a listener should be allowed to run by defining a `timeout` property on your listener class: + +```php + ## Dispatching Events To dispatch an event, you may call the static `dispatch` method on the event. This method is made available on the event by the `Illuminate\Foundation\Events\Dispatchable` trait. Any arguments passed to the `dispatch` method will be passed to the event's constructor: - order_id); - - // Order shipment logic... - - OrderShipped::dispatch($order); - } + $order = Order::findOrFail($request->order_id); + + // Order shipment logic... + + OrderShipped::dispatch($order); + + return redirect('/orders'); } +} +``` + +If you would like to conditionally dispatch an event, you may use the `dispatchIf` and `dispatchUnless` methods: + +```php +OrderShipped::dispatchIf($condition, $order); + +OrderShipped::dispatchUnless($condition, $order); +``` + +> [!NOTE] +> When testing, it can be helpful to assert that certain events were dispatched without actually triggering their listeners. Laravel's [built-in testing helpers](#testing) make it a cinch. + + +### Dispatching Events After Database Transactions + +Sometimes, you may want to instruct Laravel to only dispatch an event after the active database transaction has committed. To do so, you may implement the `ShouldDispatchAfterCommit` interface on the event class. + +This interface instructs Laravel to not dispatch the event until the current database transaction is committed. If the transaction fails, the event will be discarded. If no database transaction is in progress when the event is dispatched, the event will be dispatched immediately: + +```php + +### Deferring Events + +Deferred events allow you to delay the dispatching of model events and execution of event listeners until after a specific block of code has completed. This is particularly useful when you need to ensure that all related records are created before event listeners are triggered. -> {tip} When testing, it can be helpful to assert that certain events were dispatched without actually triggering their listeners. Laravel's [built-in testing helpers](/docs/{{version}}/mocking#event-fake) makes it a cinch. +To defer events, provide a closure to the `Event::defer()` method: + +```php +use App\Models\User; +use Illuminate\Support\Facades\Event; + +Event::defer(function () { + $user = User::create(['name' => 'Victoria Otwell']); + + $user->posts()->create(['title' => 'My first post!']); +}); +``` + +All events triggered within the closure will be dispatched after the closure is executed. This ensures that event listeners have access to all related records that were created during the deferred execution. If an exception occurs within the closure, the deferred events will not be dispatched. + +To defer only specific events, pass an array of events as the second argument to the `defer` method: + +```php +use App\Models\User; +use Illuminate\Support\Facades\Event; + +Event::defer(function () { + $user = User::create(['name' => 'Victoria Otwell']); + + $user->posts()->create(['title' => 'My first post!']); +}, ['eloquent.created: '.User::class]); +``` ## Event Subscribers @@ -561,112 +839,314 @@ To dispatch an event, you may call the static `dispatch` method on the event. Th ### Writing Event Subscribers -Event subscribers are classes that may subscribe to multiple events from within the subscriber class itself, allowing you to define several event handlers within a single class. Subscribers should define a `subscribe` method, which will be passed an event dispatcher instance. You may call the `listen` method on the given dispatcher to register event listeners: +Event subscribers are classes that may subscribe to multiple events from within the subscriber class itself, allowing you to define several event handlers within a single class. Subscribers should define a `subscribe` method, which receives an event dispatcher instance. You may call the `listen` method on the given dispatcher to register event listeners: + +```php +listen( - Login::class, - [UserEventSubscriber::class, 'handleUserLogin'] - ); - - $events->listen( - Logout::class, - [UserEventSubscriber::class, 'handleUserLogout'] - ); - } + $events->listen( + Login::class, + [UserEventSubscriber::class, 'handleUserLogin'] + ); + + $events->listen( + Logout::class, + [UserEventSubscriber::class, 'handleUserLogout'] + ); } +} +``` If your event listener methods are defined within the subscriber itself, you may find it more convenient to return an array of events and method names from the subscriber's `subscribe` method. Laravel will automatically determine the subscriber's class name when registering the event listeners: - + */ + public function subscribe(Dispatcher $events): array { - /** - * Handle user login events. - */ - public function handleUserLogin($event) {} - - /** - * Handle user logout events. - */ - public function handleUserLogout($event) {} - - /** - * Register the listeners for the subscriber. - * - * @param \Illuminate\Events\Dispatcher $events - * @return array - */ - public function subscribe($events) - { - return [ - Login::class => 'handleUserLogin', - Logout::class => 'handleUserLogout', - ]; - } + return [ + Login::class => 'handleUserLogin', + Logout::class => 'handleUserLogout', + ]; } +} +``` ### Registering Event Subscribers -After writing the subscriber, you are ready to register it with the event dispatcher. You may register subscribers using the `$subscribe` property on the `EventServiceProvider`. For example, let's add the `UserEventSubscriber` to the list: +After writing the subscriber, Laravel will automatically register handler methods within the subscriber if they follow Laravel's [event discovery conventions](#event-discovery). Otherwise, you may manually register your subscriber using the `subscribe` method of the `Event` facade. Typically, this should be done within the `boot` method of your application's `AppServiceProvider`: - +## Testing + +When testing code that dispatches events, you may wish to instruct Laravel to not actually execute the event's listeners, since the listener's code can be tested directly and separately of the code that dispatches the corresponding event. Of course, to test the listener itself, you may instantiate a listener instance and invoke the `handle` method directly in your test. + +Using the `Event` facade's `fake` method, you may prevent listeners from executing, execute the code under test, and then assert which events were dispatched by your application using the `assertDispatched`, `assertNotDispatched`, and `assertNothingDispatched` methods: + +```php tab=Pest +order->id === $order->id; +}); +``` + +If you would simply like to assert that an event listener is listening to a given event, you may use the `assertListening` method: + +```php +Event::assertListening( + OrderShipped::class, + SendShipmentNotification::class +); +``` + +> [!WARNING] +> After calling `Event::fake()`, no event listeners will be executed. So, if your tests use model factories that rely on events, such as creating a UUID during a model's `creating` event, you should call `Event::fake()` **after** using your factories. + + +### Faking a Subset of Events + +If you only want to fake event listeners for a specific set of events, you may pass them to the `fake` or `fakeFor` method: + +```php tab=Pest +test('orders can be processed', function () { + Event::fake([ + OrderCreated::class, + ]); + + $order = Order::factory()->create(); + + Event::assertDispatched(OrderCreated::class); + + // Other events are dispatched as normal... + $order->update([ + // ... + ]); +}); +``` + +```php tab=PHPUnit +/** + * Test order process. + */ +public function test_orders_can_be_processed(): void +{ + Event::fake([ + OrderCreated::class, + ]); + + $order = Order::factory()->create(); + + Event::assertDispatched(OrderCreated::class); + + // Other events are dispatched as normal... + $order->update([ + // ... + ]); +} +``` + +You may fake all events except for a set of specified events using the `except` method: + +```php +Event::fake()->except([ + OrderCreated::class, +]); +``` + + +### Scoped Event Fakes + +If you only want to fake event listeners for a portion of your test, you may use the `fakeFor` method: + +```php tab=Pest +create(); + + Event::assertDispatched(OrderCreated::class); + + return $order; + }); + + // Events are dispatched as normal and observers will run... + $order->update([ + // ... + ]); +}); +``` + +```php tab=PHPUnit +create(); + + Event::assertDispatched(OrderCreated::class); + + return $order; + }); + + // Events are dispatched as normal and observers will run... + $order->update([ + // ... + ]); } +} +``` diff --git a/facades.md b/facades.md index 2b4aec683fa..6371f913dae 100644 --- a/facades.md +++ b/facades.md @@ -1,9 +1,9 @@ # Facades - [Introduction](#introduction) -- [When To Use Facades](#when-to-use-facades) - - [Facades Vs. Dependency Injection](#facades-vs-dependency-injection) - - [Facades Vs. Helper Functions](#facades-vs-helper-functions) +- [When to Utilize Facades](#when-to-use-facades) + - [Facades vs. Dependency Injection](#facades-vs-dependency-injection) + - [Facades vs. Helper Functions](#facades-vs-helper-functions) - [How Facades Work](#how-facades-work) - [Real-Time Facades](#real-time-facades) - [Facade Class Reference](#facade-class-reference) @@ -13,16 +13,18 @@ Throughout the Laravel documentation, you will see examples of code that interacts with Laravel's features via "facades". Facades provide a "static" interface to classes that are available in the application's [service container](/docs/{{version}}/container). Laravel ships with many facades which provide access to almost all of Laravel's features. -Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. It's perfectly fine if you don't totally understand how facades work under the hood - just go with the flow and continue learning about Laravel. +Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. It's perfectly fine if you don't totally understand how facades work - just go with the flow and continue learning about Laravel. All of Laravel's facades are defined in the `Illuminate\Support\Facades` namespace. So, we can easily access a facade like so: - use Illuminate\Support\Facades\Cache; - use Illuminate\Support\Facades\Route; +```php +use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Route; - Route::get('/cache', function () { - return Cache::get('key'); - }); +Route::get('/cache', function () { + return Cache::get('key'); +}); +``` Throughout the Laravel documentation, many of the examples will use facades to demonstrate various features of the framework. @@ -33,94 +35,116 @@ To complement facades, Laravel offers a variety of global "helper functions" tha For example, instead of using the `Illuminate\Support\Facades\Response` facade to generate a JSON response, we may simply use the `response` function. Because helper functions are globally available, you do not need to import any classes in order to use them: - use Illuminate\Support\Facades\Response; +```php +use Illuminate\Support\Facades\Response; - Route::get('/users', function () { - return Response::json([ - // ... - ]); - }); +Route::get('/users', function () { + return Response::json([ + // ... + ]); +}); - Route::get('/users', function () { - return response()->json([ - // ... - ]); - }); +Route::get('/users', function () { + return response()->json([ + // ... + ]); +}); +``` -## When To Use Facades +## When to Utilize Facades Facades have many benefits. They provide a terse, memorable syntax that allows you to use Laravel's features without remembering long class names that must be injected or configured manually. Furthermore, because of their unique usage of PHP's dynamic methods, they are easy to test. However, some care must be taken when using facades. The primary danger of facades is class "scope creep". Since facades are so easy to use and do not require injection, it can be easy to let your classes continue to grow and use many facades in a single class. Using dependency injection, this potential is mitigated by the visual feedback a large constructor gives you that your class is growing too large. So, when using facades, pay special attention to the size of your class so that its scope of responsibility stays narrow. If your class is getting too large, consider splitting it into multiple smaller classes. -### Facades Vs. Dependency Injection +### Facades vs. Dependency Injection One of the primary benefits of dependency injection is the ability to swap implementations of the injected class. This is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub. Typically, it would not be possible to mock or stub a truly static class method. However, since facades use dynamic methods to proxy method calls to objects resolved from the service container, we actually can test facades just as we would test an injected class instance. For example, given the following route: - use Illuminate\Support\Facades\Cache; +```php +use Illuminate\Support\Facades\Cache; - Route::get('/cache', function () { - return Cache::get('key'); - }); +Route::get('/cache', function () { + return Cache::get('key'); +}); +``` Using Laravel's facade testing methods, we can write the following test to verify that the `Cache::get` method was called with the argument we expected: - use Illuminate\Support\Facades\Cache; +```php tab=Pest +use Illuminate\Support\Facades\Cache; - /** - * A basic functional test example. - * - * @return void - */ - public function testBasicExample() - { - Cache::shouldReceive('get') - ->with('key') - ->andReturn('value'); +test('basic example', function () { + Cache::shouldReceive('get') + ->with('key') + ->andReturn('value'); - $response = $this->get('/cache'); + $response = $this->get('/cache'); - $response->assertSee('value'); - } + $response->assertSee('value'); +}); +``` + +```php tab=PHPUnit +use Illuminate\Support\Facades\Cache; + +/** + * A basic functional test example. + */ +public function test_basic_example(): void +{ + Cache::shouldReceive('get') + ->with('key') + ->andReturn('value'); + + $response = $this->get('/cache'); + + $response->assertSee('value'); +} +``` -### Facades Vs. Helper Functions +### Facades vs. Helper Functions In addition to facades, Laravel includes a variety of "helper" functions which can perform common tasks like generating views, firing events, dispatching jobs, or sending HTTP responses. Many of these helper functions perform the same function as a corresponding facade. For example, this facade call and helper call are equivalent: - return Illuminate\Support\Facades\View::make('profile'); +```php +return Illuminate\Support\Facades\View::make('profile'); - return view('profile'); +return view('profile'); +``` There is absolutely no practical difference between facades and helper functions. When using helper functions, you may still test them exactly as you would the corresponding facade. For example, given the following route: - Route::get('/cache', function () { - return cache('key'); - }); +```php +Route::get('/cache', function () { + return cache('key'); +}); +``` -Under the hood, the `cache` helper is going to call the `get` method on the class underlying the `Cache` facade. So, even though we are using the helper function, we can write the following test to verify that the method was called with the argument we expected: +The `cache` helper is going to call the `get` method on the class underlying the `Cache` facade. So, even though we are using the helper function, we can write the following test to verify that the method was called with the argument we expected: - use Illuminate\Support\Facades\Cache; +```php +use Illuminate\Support\Facades\Cache; - /** - * A basic functional test example. - * - * @return void - */ - public function testBasicExample() - { - Cache::shouldReceive('get') - ->with('key') - ->andReturn('value'); +/** + * A basic functional test example. + */ +public function test_basic_example(): void +{ + Cache::shouldReceive('get') + ->with('key') + ->andReturn('value'); - $response = $this->get('/cache'); + $response = $this->get('/cache'); - $response->assertSee('value'); - } + $response->assertSee('value'); +} +``` ## How Facades Work @@ -129,42 +153,44 @@ In a Laravel application, a facade is a class that provides access to an object The `Facade` base class makes use of the `__callStatic()` magic-method to defer calls from your facade to an object resolved from the container. In the example below, a call is made to the Laravel cache system. By glancing at this code, one might assume that the static `get` method is being called on the `Cache` class: - $user]); - } + $user = Cache::get('user:'.$id); + + return view('profile', ['user' => $user]); } +} +``` Notice that near the top of the file we are "importing" the `Cache` facade. This facade serves as a proxy for accessing the underlying implementation of the `Illuminate\Contracts\Cache\Factory` interface. Any calls we make using the facade will be passed to the underlying instance of Laravel's cache service. If we look at that `Illuminate\Support\Facades\Cache` class, you'll see that there is no static method `get`: - class Cache extends Facade +```php +class Cache extends Facade +{ + /** + * Get the registered name of the component. + */ + protected static function getFacadeAccessor(): string { - /** - * Get the registered name of the component. - * - * @return string - */ - protected static function getFacadeAccessor() { return 'cache'; } + return 'cache'; } +} +``` Instead, the `Cache` facade extends the base `Facade` class and defines the method `getFacadeAccessor()`. This method's job is to return the name of a service container binding. When a user references any static method on the `Cache` facade, Laravel resolves the `cache` binding from the [service container](/docs/{{version}}/container) and runs the requested method (in this case, `get`) against that object. @@ -173,134 +199,166 @@ Instead, the `Cache` facade extends the base `Facade` class and defines the meth Using real-time facades, you may treat any class in your application as if it was a facade. To illustrate how this can be used, let's first examine some code that does not use real-time facades. For example, let's assume our `Podcast` model has a `publish` method. However, in order to publish the podcast, we need to inject a `Publisher` instance: - update(['publishing' => now()]); - - $publisher->publish($this); - } + $this->update(['publishing' => now()]); + + $publisher->publish($this); } +} +``` Injecting a publisher implementation into the method allows us to easily test the method in isolation since we can mock the injected publisher. However, it requires us to always pass a publisher instance each time we call the `publish` method. Using real-time facades, we can maintain the same testability while not being required to explicitly pass a `Publisher` instance. To generate a real-time facade, prefix the namespace of the imported class with `Facades`: - update(['publishing' => now()]); - - Publisher::publish($this); - } + $this->update(['publishing' => now()]); + + $publisher->publish($this); // [tl! remove] + Publisher::publish($this); // [tl! add] } +} +``` When the real-time facade is used, the publisher implementation will be resolved out of the service container using the portion of the interface or class name that appears after the `Facades` prefix. When testing, we can use Laravel's built-in facade testing helpers to mock this method call: - use(RefreshDatabase::class); - class PodcastTest extends TestCase - { - use RefreshDatabase; +test('podcast can be published', function () { + $podcast = Podcast::factory()->create(); + + Publisher::shouldReceive('publish')->once()->with($podcast); - /** - * A test example. - * - * @return void - */ - public function test_podcast_can_be_published() - { - $podcast = Podcast::factory()->create(); + $podcast->publish(); +}); +``` + +```php tab=PHPUnit +create(); - Publisher::shouldReceive('publish')->once()->with($podcast); + Publisher::shouldReceive('publish')->once()->with($podcast); - $podcast->publish(); - } + $podcast->publish(); } +} +``` ## Facade Class Reference Below you will find every facade and its underlying class. This is a useful tool for quickly digging into the API documentation for a given facade root. The [service container binding](/docs/{{version}}/container) key is also included where applicable. -Facade | Class | Service Container Binding -------------- | ------------- | ------------- -App | [Illuminate\Foundation\Application](https://laravel.com/api/{{version}}/Illuminate/Foundation/Application.html) | `app` -Artisan | [Illuminate\Contracts\Console\Kernel](https://laravel.com/api/{{version}}/Illuminate/Contracts/Console/Kernel.html) | `artisan` -Auth | [Illuminate\Auth\AuthManager](https://laravel.com/api/{{version}}/Illuminate/Auth/AuthManager.html) | `auth` -Auth (Instance) | [Illuminate\Contracts\Auth\Guard](https://laravel.com/api/{{version}}/Illuminate/Contracts/Auth/Guard.html) | `auth.driver` -Blade | [Illuminate\View\Compilers\BladeCompiler](https://laravel.com/api/{{version}}/Illuminate/View/Compilers/BladeCompiler.html) | `blade.compiler` -Broadcast | [Illuminate\Contracts\Broadcasting\Factory](https://laravel.com/api/{{version}}/Illuminate/Contracts/Broadcasting/Factory.html) |   -Broadcast (Instance) | [Illuminate\Contracts\Broadcasting\Broadcaster](https://laravel.com/api/{{version}}/Illuminate/Contracts/Broadcasting/Broadcaster.html) |   -Bus | [Illuminate\Contracts\Bus\Dispatcher](https://laravel.com/api/{{version}}/Illuminate/Contracts/Bus/Dispatcher.html) |   -Cache | [Illuminate\Cache\CacheManager](https://laravel.com/api/{{version}}/Illuminate/Cache/CacheManager.html) | `cache` -Cache (Instance) | [Illuminate\Cache\Repository](https://laravel.com/api/{{version}}/Illuminate/Cache/Repository.html) | `cache.store` -Config | [Illuminate\Config\Repository](https://laravel.com/api/{{version}}/Illuminate/Config/Repository.html) | `config` -Cookie | [Illuminate\Cookie\CookieJar](https://laravel.com/api/{{version}}/Illuminate/Cookie/CookieJar.html) | `cookie` -Crypt | [Illuminate\Encryption\Encrypter](https://laravel.com/api/{{version}}/Illuminate/Encryption/Encrypter.html) | `encrypter` -Date | [Illuminate\Support\DateFactory](https://laravel.com/api/{{version}}/Illuminate/Support/DateFactory.html) | `date` -DB | [Illuminate\Database\DatabaseManager](https://laravel.com/api/{{version}}/Illuminate/Database/DatabaseManager.html) | `db` -DB (Instance) | [Illuminate\Database\Connection](https://laravel.com/api/{{version}}/Illuminate/Database/Connection.html) | `db.connection` -Event | [Illuminate\Events\Dispatcher](https://laravel.com/api/{{version}}/Illuminate/Events/Dispatcher.html) | `events` -File | [Illuminate\Filesystem\Filesystem](https://laravel.com/api/{{version}}/Illuminate/Filesystem/Filesystem.html) | `files` -Gate | [Illuminate\Contracts\Auth\Access\Gate](https://laravel.com/api/{{version}}/Illuminate/Contracts/Auth/Access/Gate.html) |   -Hash | [Illuminate\Contracts\Hashing\Hasher](https://laravel.com/api/{{version}}/Illuminate/Contracts/Hashing/Hasher.html) | `hash` -Http | [Illuminate\Http\Client\Factory](https://laravel.com/api/{{version}}/Illuminate/Http/Client/Factory.html) |   -Lang | [Illuminate\Translation\Translator](https://laravel.com/api/{{version}}/Illuminate/Translation/Translator.html) | `translator` -Log | [Illuminate\Log\LogManager](https://laravel.com/api/{{version}}/Illuminate/Log/LogManager.html) | `log` -Mail | [Illuminate\Mail\Mailer](https://laravel.com/api/{{version}}/Illuminate/Mail/Mailer.html) | `mailer` -Notification | [Illuminate\Notifications\ChannelManager](https://laravel.com/api/{{version}}/Illuminate/Notifications/ChannelManager.html) |   -Password | [Illuminate\Auth\Passwords\PasswordBrokerManager](https://laravel.com/api/{{version}}/Illuminate/Auth/Passwords/PasswordBrokerManager.html) | `auth.password` -Password (Instance) | [Illuminate\Auth\Passwords\PasswordBroker](https://laravel.com/api/{{version}}/Illuminate/Auth/Passwords/PasswordBroker.html) | `auth.password.broker` -Queue | [Illuminate\Queue\QueueManager](https://laravel.com/api/{{version}}/Illuminate/Queue/QueueManager.html) | `queue` -Queue (Instance) | [Illuminate\Contracts\Queue\Queue](https://laravel.com/api/{{version}}/Illuminate/Contracts/Queue/Queue.html) | `queue.connection` -Queue (Base Class) | [Illuminate\Queue\Queue](https://laravel.com/api/{{version}}/Illuminate/Queue/Queue.html) |   -Redirect | [Illuminate\Routing\Redirector](https://laravel.com/api/{{version}}/Illuminate/Routing/Redirector.html) | `redirect` -Redis | [Illuminate\Redis\RedisManager](https://laravel.com/api/{{version}}/Illuminate/Redis/RedisManager.html) | `redis` -Redis (Instance) | [Illuminate\Redis\Connections\Connection](https://laravel.com/api/{{version}}/Illuminate/Redis/Connections/Connection.html) | `redis.connection` -Request | [Illuminate\Http\Request](https://laravel.com/api/{{version}}/Illuminate/Http/Request.html) | `request` -Response | [Illuminate\Contracts\Routing\ResponseFactory](https://laravel.com/api/{{version}}/Illuminate/Contracts/Routing/ResponseFactory.html) |   -Response (Instance) | [Illuminate\Http\Response](https://laravel.com/api/{{version}}/Illuminate/Http/Response.html) |   -Route | [Illuminate\Routing\Router](https://laravel.com/api/{{version}}/Illuminate/Routing/Router.html) | `router` -Schema | [Illuminate\Database\Schema\Builder](https://laravel.com/api/{{version}}/Illuminate/Database/Schema/Builder.html) |   -Session | [Illuminate\Session\SessionManager](https://laravel.com/api/{{version}}/Illuminate/Session/SessionManager.html) | `session` -Session (Instance) | [Illuminate\Session\Store](https://laravel.com/api/{{version}}/Illuminate/Session/Store.html) | `session.store` -Storage | [Illuminate\Filesystem\FilesystemManager](https://laravel.com/api/{{version}}/Illuminate/Filesystem/FilesystemManager.html) | `filesystem` -Storage (Instance) | [Illuminate\Contracts\Filesystem\Filesystem](https://laravel.com/api/{{version}}/Illuminate/Contracts/Filesystem/Filesystem.html) | `filesystem.disk` -URL | [Illuminate\Routing\UrlGenerator](https://laravel.com/api/{{version}}/Illuminate/Routing/UrlGenerator.html) | `url` -Validator | [Illuminate\Validation\Factory](https://laravel.com/api/{{version}}/Illuminate/Validation/Factory.html) | `validator` -Validator (Instance) | [Illuminate\Validation\Validator](https://laravel.com/api/{{version}}/Illuminate/Validation/Validator.html) |   -View | [Illuminate\View\Factory](https://laravel.com/api/{{version}}/Illuminate/View/Factory.html) | `view` -View (Instance) | [Illuminate\View\View](https://laravel.com/api/{{version}}/Illuminate/View/View.html) |   +
+ +| Facade | Class | Service Container Binding | +| --- | --- | --- | +| App | [Illuminate\Foundation\Application](https://api.laravel.com/docs/{{version}}/Illuminate/Foundation/Application.html) | `app` | +| Artisan | [Illuminate\Contracts\Console\Kernel](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Console/Kernel.html) | `artisan` | +| Auth (Instance) | [Illuminate\Contracts\Auth\Guard](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Auth/Guard.html) | `auth.driver` | +| Auth | [Illuminate\Auth\AuthManager](https://api.laravel.com/docs/{{version}}/Illuminate/Auth/AuthManager.html) | `auth` | +| Blade | [Illuminate\View\Compilers\BladeCompiler](https://api.laravel.com/docs/{{version}}/Illuminate/View/Compilers/BladeCompiler.html) | `blade.compiler` | +| Broadcast (Instance) | [Illuminate\Contracts\Broadcasting\Broadcaster](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Broadcasting/Broadcaster.html) |   | +| Broadcast | [Illuminate\Contracts\Broadcasting\Factory](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Broadcasting/Factory.html) |   | +| Bus | [Illuminate\Contracts\Bus\Dispatcher](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Bus/Dispatcher.html) |   | +| Cache (Instance) | [Illuminate\Cache\Repository](https://api.laravel.com/docs/{{version}}/Illuminate/Cache/Repository.html) | `cache.store` | +| Cache | [Illuminate\Cache\CacheManager](https://api.laravel.com/docs/{{version}}/Illuminate/Cache/CacheManager.html) | `cache` | +| Config | [Illuminate\Config\Repository](https://api.laravel.com/docs/{{version}}/Illuminate/Config/Repository.html) | `config` | +| Context | [Illuminate\Log\Context\Repository](https://api.laravel.com/docs/{{version}}/Illuminate/Log/Context/Repository.html) |   | +| Cookie | [Illuminate\Cookie\CookieJar](https://api.laravel.com/docs/{{version}}/Illuminate/Cookie/CookieJar.html) | `cookie` | +| Crypt | [Illuminate\Encryption\Encrypter](https://api.laravel.com/docs/{{version}}/Illuminate/Encryption/Encrypter.html) | `encrypter` | +| Date | [Illuminate\Support\DateFactory](https://api.laravel.com/docs/{{version}}/Illuminate/Support/DateFactory.html) | `date` | +| DB (Instance) | [Illuminate\Database\Connection](https://api.laravel.com/docs/{{version}}/Illuminate/Database/Connection.html) | `db.connection` | +| DB | [Illuminate\Database\DatabaseManager](https://api.laravel.com/docs/{{version}}/Illuminate/Database/DatabaseManager.html) | `db` | +| Event | [Illuminate\Events\Dispatcher](https://api.laravel.com/docs/{{version}}/Illuminate/Events/Dispatcher.html) | `events` | +| Exceptions (Instance) | [Illuminate\Contracts\Debug\ExceptionHandler](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Debug/ExceptionHandler.html) |   | +| Exceptions | [Illuminate\Foundation\Exceptions\Handler](https://api.laravel.com/docs/{{version}}/Illuminate/Foundation/Exceptions/Handler.html) |   | +| File | [Illuminate\Filesystem\Filesystem](https://api.laravel.com/docs/{{version}}/Illuminate/Filesystem/Filesystem.html) | `files` | +| Gate | [Illuminate\Contracts\Auth\Access\Gate](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Auth/Access/Gate.html) |   | +| Hash | [Illuminate\Contracts\Hashing\Hasher](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Hashing/Hasher.html) | `hash` | +| Http | [Illuminate\Http\Client\Factory](https://api.laravel.com/docs/{{version}}/Illuminate/Http/Client/Factory.html) |   | +| Lang | [Illuminate\Translation\Translator](https://api.laravel.com/docs/{{version}}/Illuminate/Translation/Translator.html) | `translator` | +| Log | [Illuminate\Log\LogManager](https://api.laravel.com/docs/{{version}}/Illuminate/Log/LogManager.html) | `log` | +| Mail | [Illuminate\Mail\Mailer](https://api.laravel.com/docs/{{version}}/Illuminate/Mail/Mailer.html) | `mailer` | +| Notification | [Illuminate\Notifications\ChannelManager](https://api.laravel.com/docs/{{version}}/Illuminate/Notifications/ChannelManager.html) |   | +| Password (Instance) | [Illuminate\Auth\Passwords\PasswordBroker](https://api.laravel.com/docs/{{version}}/Illuminate/Auth/Passwords/PasswordBroker.html) | `auth.password.broker` | +| Password | [Illuminate\Auth\Passwords\PasswordBrokerManager](https://api.laravel.com/docs/{{version}}/Illuminate/Auth/Passwords/PasswordBrokerManager.html) | `auth.password` | +| Pipeline (Instance) | [Illuminate\Pipeline\Pipeline](https://api.laravel.com/docs/{{version}}/Illuminate/Pipeline/Pipeline.html) |   | +| Process | [Illuminate\Process\Factory](https://api.laravel.com/docs/{{version}}/Illuminate/Process/Factory.html) |   | +| Queue (Base Class) | [Illuminate\Queue\Queue](https://api.laravel.com/docs/{{version}}/Illuminate/Queue/Queue.html) |   | +| Queue (Instance) | [Illuminate\Contracts\Queue\Queue](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Queue/Queue.html) | `queue.connection` | +| Queue | [Illuminate\Queue\QueueManager](https://api.laravel.com/docs/{{version}}/Illuminate/Queue/QueueManager.html) | `queue` | +| RateLimiter | [Illuminate\Cache\RateLimiter](https://api.laravel.com/docs/{{version}}/Illuminate/Cache/RateLimiter.html) |   | +| Redirect | [Illuminate\Routing\Redirector](https://api.laravel.com/docs/{{version}}/Illuminate/Routing/Redirector.html) | `redirect` | +| Redis (Instance) | [Illuminate\Redis\Connections\Connection](https://api.laravel.com/docs/{{version}}/Illuminate/Redis/Connections/Connection.html) | `redis.connection` | +| Redis | [Illuminate\Redis\RedisManager](https://api.laravel.com/docs/{{version}}/Illuminate/Redis/RedisManager.html) | `redis` | +| Request | [Illuminate\Http\Request](https://api.laravel.com/docs/{{version}}/Illuminate/Http/Request.html) | `request` | +| Response (Instance) | [Illuminate\Http\Response](https://api.laravel.com/docs/{{version}}/Illuminate/Http/Response.html) |   | +| Response | [Illuminate\Contracts\Routing\ResponseFactory](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Routing/ResponseFactory.html) |   | +| Route | [Illuminate\Routing\Router](https://api.laravel.com/docs/{{version}}/Illuminate/Routing/Router.html) | `router` | +| Schedule | [Illuminate\Console\Scheduling\Schedule](https://api.laravel.com/docs/{{version}}/Illuminate/Console/Scheduling/Schedule.html) |   | +| Schema | [Illuminate\Database\Schema\Builder](https://api.laravel.com/docs/{{version}}/Illuminate/Database/Schema/Builder.html) |   | +| Session (Instance) | [Illuminate\Session\Store](https://api.laravel.com/docs/{{version}}/Illuminate/Session/Store.html) | `session.store` | +| Session | [Illuminate\Session\SessionManager](https://api.laravel.com/docs/{{version}}/Illuminate/Session/SessionManager.html) | `session` | +| Storage (Instance) | [Illuminate\Contracts\Filesystem\Filesystem](https://api.laravel.com/docs/{{version}}/Illuminate/Contracts/Filesystem/Filesystem.html) | `filesystem.disk` | +| Storage | [Illuminate\Filesystem\FilesystemManager](https://api.laravel.com/docs/{{version}}/Illuminate/Filesystem/FilesystemManager.html) | `filesystem` | +| URL | [Illuminate\Routing\UrlGenerator](https://api.laravel.com/docs/{{version}}/Illuminate/Routing/UrlGenerator.html) | `url` | +| Validator (Instance) | [Illuminate\Validation\Validator](https://api.laravel.com/docs/{{version}}/Illuminate/Validation/Validator.html) |   | +| Validator | [Illuminate\Validation\Factory](https://api.laravel.com/docs/{{version}}/Illuminate/Validation/Factory.html) | `validator` | +| View (Instance) | [Illuminate\View\View](https://api.laravel.com/docs/{{version}}/Illuminate/View/View.html) |   | +| View | [Illuminate\View\Factory](https://api.laravel.com/docs/{{version}}/Illuminate/View/Factory.html) | `view` | +| Vite | [Illuminate\Foundation\Vite](https://api.laravel.com/docs/{{version}}/Illuminate/Foundation/Vite.html) |   | + +
diff --git a/filesystem.md b/filesystem.md index a4b724747aa..f6534104a72 100644 --- a/filesystem.md +++ b/filesystem.md @@ -5,18 +5,24 @@ - [The Local Driver](#the-local-driver) - [The Public Disk](#the-public-disk) - [Driver Prerequisites](#driver-prerequisites) + - [Scoped and Read-Only Filesystems](#scoped-and-read-only-filesystems) - [Amazon S3 Compatible Filesystems](#amazon-s3-compatible-filesystems) - [Obtaining Disk Instances](#obtaining-disk-instances) - [On-Demand Disks](#on-demand-disks) - [Retrieving Files](#retrieving-files) - [Downloading Files](#downloading-files) - [File URLs](#file-urls) + - [Temporary URLs](#temporary-urls) - [File Metadata](#file-metadata) - [Storing Files](#storing-files) + - [Prepending and Appending To Files](#prepending-appending-to-files) + - [Copying and Moving Files](#copying-moving-files) + - [Automatic Streaming](#automatic-streaming) - [File Uploads](#file-uploads) - [File Visibility](#file-visibility) - [Deleting Files](#deleting-files) - [Directories](#directories) +- [Testing](#testing) - [Custom Filesystems](#custom-filesystems) @@ -29,25 +35,28 @@ Laravel provides a powerful filesystem abstraction thanks to the wonderful [Flys Laravel's filesystem configuration file is located at `config/filesystems.php`. Within this file, you may configure all of your filesystem "disks". Each disk represents a particular storage driver and storage location. Example configurations for each supported driver are included in the configuration file so you can modify the configuration to reflect your storage preferences and credentials. -The `local` driver interacts with files stored locally on the server running the Laravel application while the `s3` driver is used to write to Amazon's S3 cloud storage service. +The `local` driver interacts with files stored locally on the server running the Laravel application, while the `sftp` storage driver is used for SSH key-based FTP. The `s3` driver is used to write to Amazon's S3 cloud storage service. -> {tip} You may configure as many disks as you like and may even have multiple disks that use the same driver. +> [!NOTE] +> You may configure as many disks as you like and may even have multiple disks that use the same driver. ### The Local Driver -When using the `local` driver, all file operations are relative to the `root` directory defined in your `filesystems` configuration file. By default, this value is set to the `storage/app` directory. Therefore, the following method would write to `storage/app/example.txt`: +When using the `local` driver, all file operations are relative to the `root` directory defined in your `filesystems` configuration file. By default, this value is set to the `storage/app/private` directory. Therefore, the following method would write to `storage/app/private/example.txt`: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - Storage::disk('local')->put('example.txt', 'Contents'); +Storage::disk('local')->put('example.txt', 'Contents'); +``` ### The Public Disk The `public` disk included in your application's `filesystems` configuration file is intended for files that are going to be publicly accessible. By default, the `public` disk uses the `local` driver and stores its files in `storage/app/public`. -To make these files accessible from the web, you should create a symbolic link from `public/storage` to `storage/app/public`. Utilizing this folder convention will keep your publicly accessible files in one directory that can be easily shared across deployments when using zero down-time deployment systems like [Envoyer](https://envoyer.io). +If your `public` disk uses the `local` driver and you want to make these files accessible from the web, you should create a symbolic link from source directory `storage/app/public` to target directory `public/storage`: To create the symbolic link, you may use the `storage:link` Artisan command: @@ -57,14 +66,24 @@ php artisan storage:link Once a file has been stored and the symbolic link has been created, you can create a URL to the files using the `asset` helper: - echo asset('storage/file.txt'); +```php +echo asset('storage/file.txt'); +``` You may configure additional symbolic links in your `filesystems` configuration file. Each of the configured links will be created when you run the `storage:link` command: - 'links' => [ - public_path('storage') => storage_path('app/public'), - public_path('images') => storage_path('app/images'), - ], +```php +'links' => [ + public_path('storage') => storage_path('app/public'), + public_path('images') => storage_path('app/images'), +], +``` + +The `storage:unlink` command may be used to destroy your configured symbolic links: + +```shell +php artisan storage:unlink +``` ### Driver Prerequisites @@ -75,10 +94,20 @@ You may configure additional symbolic links in your `filesystems` configuration Before using the S3 driver, you will need to install the Flysystem S3 package via the Composer package manager: ```shell -composer require -W league/flysystem-aws-s3-v3 "^3.0" +composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies +``` + +An S3 disk configuration array is located in your `config/filesystems.php` configuration file. Typically, you should configure your S3 information and credentials using the following environment variables which are referenced by the `config/filesystems.php` configuration file: + +```ini +AWS_ACCESS_KEY_ID= +AWS_SECRET_ACCESS_KEY= +AWS_DEFAULT_REGION=us-east-1 +AWS_BUCKET= +AWS_USE_PATH_STYLE_ENDPOINT=false ``` -The S3 driver configuration information is located in your `config/filesystems.php` configuration file. This file contains an example configuration array for an S3 driver. You are free to modify this array with your own S3 configuration and credentials. For convenience, these environment variables match the naming convention used by the AWS CLI. +For convenience, these environment variables match the naming convention used by the AWS CLI. #### FTP Driver Configuration @@ -89,21 +118,23 @@ Before using the FTP driver, you will need to install the Flysystem FTP package composer require league/flysystem-ftp "^3.0" ``` -Laravel's Flysystem integrations work great with FTP; however, a sample configuration is not included with the framework's default `filesystems.php` configuration file. If you need to configure an FTP filesystem, you may use the configuration example below: +Laravel's Flysystem integrations work great with FTP; however, a sample configuration is not included with the framework's default `config/filesystems.php` configuration file. If you need to configure an FTP filesystem, you may use the configuration example below: - 'ftp' => [ - 'driver' => 'ftp', - 'host' => env('FTP_HOST'), - 'username' => env('FTP_USERNAME'), - 'password' => env('FTP_PASSWORD'), - - // Optional FTP Settings... - // 'port' => env('FTP_PORT', 21), - // 'root' => env('FTP_ROOT'), - // 'passive' => true, - // 'ssl' => true, - // 'timeout' => 30, - ], +```php +'ftp' => [ + 'driver' => 'ftp', + 'host' => env('FTP_HOST'), + 'username' => env('FTP_USERNAME'), + 'password' => env('FTP_PASSWORD'), + + // Optional FTP Settings... + // 'port' => env('FTP_PORT', 21), + // 'root' => env('FTP_ROOT'), + // 'passive' => true, + // 'ssl' => true, + // 'timeout' => 30, +], +``` #### SFTP Driver Configuration @@ -114,47 +145,110 @@ Before using the SFTP driver, you will need to install the Flysystem SFTP packag composer require league/flysystem-sftp-v3 "^3.0" ``` -Laravel's Flysystem integrations work great with SFTP; however, a sample configuration is not included with the framework's default `filesystems.php` configuration file. If you need to configure an SFTP filesystem, you may use the configuration example below: +Laravel's Flysystem integrations work great with SFTP; however, a sample configuration is not included with the framework's default `config/filesystems.php` configuration file. If you need to configure an SFTP filesystem, you may use the configuration example below: - 'sftp' => [ - 'driver' => 'sftp', - 'host' => env('SFTP_HOST'), - - // Settings for basic authentication... - 'username' => env('SFTP_USERNAME'), - 'password' => env('SFTP_PASSWORD'), +```php +'sftp' => [ + 'driver' => 'sftp', + 'host' => env('SFTP_HOST'), + + // Settings for basic authentication... + 'username' => env('SFTP_USERNAME'), + 'password' => env('SFTP_PASSWORD'), + + // Settings for SSH key-based authentication with encryption password... + 'privateKey' => env('SFTP_PRIVATE_KEY'), + 'passphrase' => env('SFTP_PASSPHRASE'), + + // Settings for file / directory permissions... + 'visibility' => 'private', // `private` = 0600, `public` = 0644 + 'directory_visibility' => 'private', // `private` = 0700, `public` = 0755 + + // Optional SFTP Settings... + // 'hostFingerprint' => env('SFTP_HOST_FINGERPRINT'), + // 'maxTries' => 4, + // 'passphrase' => env('SFTP_PASSPHRASE'), + // 'port' => env('SFTP_PORT', 22), + // 'root' => env('SFTP_ROOT', ''), + // 'timeout' => 30, + // 'useAgent' => true, +], +``` - // Settings for SSH key based authentication with encryption password... - 'privateKey' => env('SFTP_PRIVATE_KEY'), - 'password' => env('SFTP_PASSWORD'), + +### Scoped and Read-Only Filesystems - // Optional SFTP Settings... - // 'port' => env('SFTP_PORT', 22), - // 'root' => env('SFTP_ROOT', ''), - // 'timeout' => 30, - ], +Scoped disks allow you to define a filesystem where all paths are automatically prefixed with a given path prefix. Before creating a scoped filesystem disk, you will need to install an additional Flysystem package via the Composer package manager: + +```shell +composer require league/flysystem-path-prefixing "^3.0" +``` + +You may create a path scoped instance of any existing filesystem disk by defining a disk that utilizes the `scoped` driver. For example, you may create a disk which scopes your existing `s3` disk to a specific path prefix, and then every file operation using your scoped disk will utilize the specified prefix: + +```php +'s3-videos' => [ + 'driver' => 'scoped', + 'disk' => 's3', + 'prefix' => 'path/to/videos', +], +``` + +"Read-only" disks allow you to create filesystem disks that do not allow write operations. Before using the `read-only` configuration option, you will need to install an additional Flysystem package via the Composer package manager: + +```shell +composer require league/flysystem-read-only "^3.0" +``` + +Next, you may include the `read-only` configuration option in one or more of your disk's configuration arrays: + +```php +'s3-videos' => [ + 'driver' => 's3', + // ... + 'read-only' => true, +], +``` ### Amazon S3 Compatible Filesystems -By default, your application's `filesystems` configuration file contains a disk configuration for the `s3` disk. In addition to using this disk to interact with Amazon S3, you may use it to interact with any S3 compatible file storage service such as [MinIO](https://github.com/minio/minio) or [DigitalOcean Spaces](https://www.digitalocean.com/products/spaces/). +By default, your application's `filesystems` configuration file contains a disk configuration for the `s3` disk. In addition to using this disk to interact with [Amazon S3](https://aws.amazon.com/s3/), you may use it to interact with any S3-compatible file storage service such as [MinIO](https://github.com/minio/minio), [DigitalOcean Spaces](https://www.digitalocean.com/products/spaces/), [Vultr Object Storage](https://www.vultr.com/products/object-storage/), [Cloudflare R2](https://www.cloudflare.com/developer-platform/products/r2/), or [Hetzner Cloud Storage](https://www.hetzner.com/storage/object-storage/). + +Typically, after updating the disk's credentials to match the credentials of the service you are planning to use, you only need to update the value of the `endpoint` configuration option. This option's value is typically defined via the `AWS_ENDPOINT` environment variable: + +```php +'endpoint' => env('AWS_ENDPOINT', 'https://minio:9000/'), +``` + + +#### MinIO + +In order for Laravel's Flysystem integration to generate proper URLs when using MinIO, you should define the `AWS_URL` environment variable so that it matches your application's local URL and includes the bucket name in the URL path: -Typically, after updating the disk's credentials to match the credentials of the service you are planning to use, you only need to update the value of the `url` configuration option. This option's value is typically defined via the `AWS_ENDPOINT` environment variable: +```ini +AWS_URL=http://localhost:9000/local +``` - 'endpoint' => env('AWS_ENDPOINT', 'https://minio:9000/'), +> [!WARNING] +> Generating temporary storage URLs via the `temporaryUrl` method may not work when using MinIO if the `endpoint` is not accessible by the client. ## Obtaining Disk Instances The `Storage` facade may be used to interact with any of your configured disks. For example, you may use the `put` method on the facade to store an avatar on the default disk. If you call methods on the `Storage` facade without first calling the `disk` method, the method will automatically be passed to the default disk: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - Storage::put('avatars/1', $content); +Storage::put('avatars/1', $content); +``` If your application interacts with multiple disks, you may use the `disk` method on the `Storage` facade to work with files on a particular disk: - Storage::disk('s3')->put('avatars/1', $content); +```php +Storage::disk('s3')->put('avatars/1', $content); +``` ### On-Demand Disks @@ -177,260 +271,381 @@ $disk->put('image.jpg', $content); The `get` method may be used to retrieve the contents of a file. The raw string contents of the file will be returned by the method. Remember, all file paths should be specified relative to the disk's "root" location: - $contents = Storage::get('file.jpg'); +```php +$contents = Storage::get('file.jpg'); +``` + +If the file you are retrieving contains JSON, you may use the `json` method to retrieve the file and decode its contents: + +```php +$orders = Storage::json('orders.json'); +``` The `exists` method may be used to determine if a file exists on the disk: - if (Storage::disk('s3')->exists('file.jpg')) { - // ... - } +```php +if (Storage::disk('s3')->exists('file.jpg')) { + // ... +} +``` The `missing` method may be used to determine if a file is missing from the disk: - if (Storage::disk('s3')->missing('file.jpg')) { - // ... - } +```php +if (Storage::disk('s3')->missing('file.jpg')) { + // ... +} +``` ### Downloading Files The `download` method may be used to generate a response that forces the user's browser to download the file at the given path. The `download` method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method: - return Storage::download('file.jpg'); +```php +return Storage::download('file.jpg'); - return Storage::download('file.jpg', $name, $headers); +return Storage::download('file.jpg', $name, $headers); +``` ### File URLs You may use the `url` method to get the URL for a given file. If you are using the `local` driver, this will typically just prepend `/storage` to the given path and return a relative URL to the file. If you are using the `s3` driver, the fully qualified remote URL will be returned: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - $url = Storage::url('https://github.com/file.jpg'); +$url = Storage::url('https://github.com/file.jpg'); +``` When using the `local` driver, all files that should be publicly accessible should be placed in the `storage/app/public` directory. Furthermore, you should [create a symbolic link](#the-public-disk) at `public/storage` which points to the `storage/app/public` directory. -> {note} When using the `local` driver, the return value of `url` is not URL encoded. For this reason, we recommend always storing your files using names that will create valid URLs. +> [!WARNING] +> When using the `local` driver, the return value of `url` is not URL encoded. For this reason, we recommend always storing your files using names that will create valid URLs. + + +#### URL Host Customization + +If you would like to modify the host for URLs generated using the `Storage` facade, you may add or change the `url` option in the disk's configuration array: + +```php +'public' => [ + 'driver' => 'local', + 'root' => storage_path('app/public'), + 'url' => env('APP_URL').'/storage', + 'visibility' => 'public', + 'throw' => false, +], +``` -#### Temporary URLs +### Temporary URLs + +Using the `temporaryUrl` method, you may create temporary URLs to files stored using the `local` and `s3` drivers. This method accepts a path and a `DateTime` instance specifying when the URL should expire: + +```php +use Illuminate\Support\Facades\Storage; + +$url = Storage::temporaryUrl( + 'file.jpg', now()->addMinutes(5) +); +``` + + +#### Enabling Local Temporary URLs -Using the `temporaryUrl` method, you may create temporary URLs to files stored using the `s3` driver. This method accepts a path and a `DateTime` instance specifying when the URL should expire: +If you started developing your application before support for temporary URLs was introduced to the `local` driver, you may need to enable local temporary URLs. To do so, add the `serve` option to your `local` disk's configuration array within the `config/filesystems.php` configuration file: - use Illuminate\Support\Facades\Storage; +```php +'local' => [ + 'driver' => 'local', + 'root' => storage_path('app/private'), + 'serve' => true, // [tl! add] + 'throw' => false, +], +``` - $url = Storage::temporaryUrl( - 'file.jpg', now()->addMinutes(5) - ); + +#### S3 Request Parameters If you need to specify additional [S3 request parameters](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html#RESTObjectGET-requests), you may pass the array of request parameters as the third argument to the `temporaryUrl` method: - $url = Storage::temporaryUrl( - 'file.jpg', - now()->addMinutes(5), - [ - 'ResponseContentType' => 'application/octet-stream', - 'ResponseContentDisposition' => 'attachment; filename=file2.jpg', - ] - ); +```php +$url = Storage::temporaryUrl( + 'file.jpg', + now()->addMinutes(5), + [ + 'ResponseContentType' => 'application/octet-stream', + 'ResponseContentDisposition' => 'attachment; filename=file2.jpg', + ] +); +``` -If you need to customize how temporary URLs are created for a specific storage disk, you can use the `buildTemporaryUrlsUsing` method. For example, this can be useful if you have a controller that allows you to download files stored via a disk that doesn't typically support temporary URLs. Usually, this method should be called from the `boot` method of a service provider: + +#### Customizing Temporary URLs - buildTemporaryUrlsUsing(function ($path, $expiration, $options) { + Storage::disk('local')->buildTemporaryUrlsUsing( + function (string $path, DateTime $expiration, array $options) { return URL::temporarySignedRoute( 'files.download', $expiration, array_merge($options, ['path' => $path]) ); - }); - } + } + ); } +} +``` - -#### URL Host Customization + +#### Temporary Upload URLs -If you would like to pre-define the host for URLs generated using the `Storage` facade, you may add a `url` option to the disk's configuration array: +> [!WARNING] +> The ability to generate temporary upload URLs is only supported by the `s3` driver. - 'public' => [ - 'driver' => 'local', - 'root' => storage_path('app/public'), - 'url' => env('APP_URL').'/storage', - 'visibility' => 'public', - ], +If you need to generate a temporary URL that can be used to upload a file directly from your client-side application, you may use the `temporaryUploadUrl` method. This method accepts a path and a `DateTime` instance specifying when the URL should expire. The `temporaryUploadUrl` method returns an associative array which may be destructured into the upload URL and the headers that should be included with the upload request: + +```php +use Illuminate\Support\Facades\Storage; + +['url' => $url, 'headers' => $headers] = Storage::temporaryUploadUrl( + 'file.jpg', now()->addMinutes(5) +); +``` + +This method is primarily useful in serverless environments that require the client-side application to directly upload files to a cloud storage system such as Amazon S3. ### File Metadata In addition to reading and writing files, Laravel can also provide information about the files themselves. For example, the `size` method may be used to get the size of a file in bytes: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - $size = Storage::size('file.jpg'); +$size = Storage::size('file.jpg'); +``` The `lastModified` method returns the UNIX timestamp of the last time the file was modified: - $time = Storage::lastModified('file.jpg'); +```php +$time = Storage::lastModified('file.jpg'); +``` + +The MIME type of a given file may be obtained via the `mimeType` method: + +```php +$mime = Storage::mimeType('file.jpg'); +``` #### File Paths You may use the `path` method to get the path for a given file. If you are using the `local` driver, this will return the absolute path to the file. If you are using the `s3` driver, this method will return the relative path to the file in the S3 bucket: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - $path = Storage::path('file.jpg'); +$path = Storage::path('file.jpg'); +``` ## Storing Files The `put` method may be used to store file contents on a disk. You may also pass a PHP `resource` to the `put` method, which will use Flysystem's underlying stream support. Remember, all file paths should be specified relative to the "root" location configured for the disk: - use Illuminate\Support\Facades\Storage; - - Storage::put('file.jpg', $contents); - - Storage::put('file.jpg', $resource); - - -#### Automatic Streaming +```php +use Illuminate\Support\Facades\Storage; -Streaming files to storage offers significantly reduced memory usage. If you would like Laravel to automatically manage streaming a given file to your storage location, you may use the `putFile` or `putFileAs` method. This method accepts either an `Illuminate\Http\File` or `Illuminate\Http\UploadedFile` instance and will automatically stream the file to your desired location: +Storage::put('file.jpg', $contents); - use Illuminate\Http\File; - use Illuminate\Support\Facades\Storage; +Storage::put('file.jpg', $resource); +``` - // Automatically generate a unique ID for filename... - $path = Storage::putFile('photos', new File('/path/to/photo')); + +#### Failed Writes - // Manually specify a filename... - $path = Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg'); +If the `put` method (or other "write" operations) is unable to write the file to disk, `false` will be returned: -There are a few important things to note about the `putFile` method. Note that we only specified a directory name and not a filename. By default, the `putFile` method will generate a unique ID to serve as the filename. The file's extension will be determined by examining the file's MIME type. The path to the file will be returned by the `putFile` method so you can store the path, including the generated filename, in your database. +```php +if (! Storage::put('file.jpg', $contents)) { + // The file could not be written to disk... +} +``` -The `putFile` and `putFileAs` methods also accept an argument to specify the "visibility" of the stored file. This is particularly useful if you are storing the file on a cloud disk such as Amazon S3 and would like the file to be publicly accessible via generated URLs: +If you wish, you may define the `throw` option within your filesystem disk's configuration array. When this option is defined as `true`, "write" methods such as `put` will throw an instance of `League\Flysystem\UnableToWriteFile` when write operations fail: - Storage::putFile('photos', new File('/path/to/photo'), 'public'); +```php +'public' => [ + 'driver' => 'local', + // ... + 'throw' => true, +], +``` -#### Prepending & Appending To Files +### Prepending and Appending To Files The `prepend` and `append` methods allow you to write to the beginning or end of a file: - Storage::prepend('file.log', 'Prepended Text'); +```php +Storage::prepend('file.log', 'Prepended Text'); - Storage::append('file.log', 'Appended Text'); +Storage::append('file.log', 'Appended Text'); +``` -#### Copying & Moving Files +### Copying and Moving Files The `copy` method may be used to copy an existing file to a new location on the disk, while the `move` method may be used to rename or move an existing file to a new location: - Storage::copy('old/file.jpg', 'new/file.jpg'); +```php +Storage::copy('old/file.jpg', 'new/file.jpg'); + +Storage::move('old/file.jpg', 'new/file.jpg'); +``` + + +### Automatic Streaming + +Streaming files to storage offers significantly reduced memory usage. If you would like Laravel to automatically manage streaming a given file to your storage location, you may use the `putFile` or `putFileAs` method. This method accepts either an `Illuminate\Http\File` or `Illuminate\Http\UploadedFile` instance and will automatically stream the file to your desired location: - Storage::move('old/file.jpg', 'new/file.jpg'); +```php +use Illuminate\Http\File; +use Illuminate\Support\Facades\Storage; + +// Automatically generate a unique ID for filename... +$path = Storage::putFile('photos', new File('/path/to/photo')); + +// Manually specify a filename... +$path = Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg'); +``` + +There are a few important things to note about the `putFile` method. Note that we only specified a directory name and not a filename. By default, the `putFile` method will generate a unique ID to serve as the filename. The file's extension will be determined by examining the file's MIME type. The path to the file will be returned by the `putFile` method so you can store the path, including the generated filename, in your database. + +The `putFile` and `putFileAs` methods also accept an argument to specify the "visibility" of the stored file. This is particularly useful if you are storing the file on a cloud disk such as Amazon S3 and would like the file to be publicly accessible via generated URLs: + +```php +Storage::putFile('photos', new File('/path/to/photo'), 'public'); +``` ### File Uploads In web applications, one of the most common use-cases for storing files is storing user uploaded files such as photos and documents. Laravel makes it very easy to store uploaded files using the `store` method on an uploaded file instance. Call the `store` method with the path at which you wish to store the uploaded file: - file('avatar')->store('avatars'); - - return $path; - } + $path = $request->file('avatar')->store('avatars'); + + return $path; } +} +``` There are a few important things to note about this example. Note that we only specified a directory name, not a filename. By default, the `store` method will generate a unique ID to serve as the filename. The file's extension will be determined by examining the file's MIME type. The path to the file will be returned by the `store` method so you can store the path, including the generated filename, in your database. You may also call the `putFile` method on the `Storage` facade to perform the same file storage operation as the example above: - $path = Storage::putFile('avatars', $request->file('avatar')); +```php +$path = Storage::putFile('avatars', $request->file('avatar')); +``` -#### Specifying A File Name +#### Specifying a File Name If you do not want a filename to be automatically assigned to your stored file, you may use the `storeAs` method, which receives the path, the filename, and the (optional) disk as its arguments: - $path = $request->file('avatar')->storeAs( - 'avatars', $request->user()->id - ); +```php +$path = $request->file('avatar')->storeAs( + 'avatars', $request->user()->id +); +``` You may also use the `putFileAs` method on the `Storage` facade, which will perform the same file storage operation as the example above: - $path = Storage::putFileAs( - 'avatars', $request->file('avatar'), $request->user()->id - ); +```php +$path = Storage::putFileAs( + 'avatars', $request->file('avatar'), $request->user()->id +); +``` -> {note} Unprintable and invalid unicode characters will automatically be removed from file paths. Therefore, you may wish to sanitize your file paths before passing them to Laravel's file storage methods. File paths are normalized using the `League\Flysystem\Util::normalizePath` method. +> [!WARNING] +> Unprintable and invalid unicode characters will automatically be removed from file paths. Therefore, you may wish to sanitize your file paths before passing them to Laravel's file storage methods. File paths are normalized using the `League\Flysystem\WhitespacePathNormalizer::normalizePath` method. -#### Specifying A Disk +#### Specifying a Disk By default, this uploaded file's `store` method will use your default disk. If you would like to specify another disk, pass the disk name as the second argument to the `store` method: - $path = $request->file('avatar')->store( - 'avatars/'.$request->user()->id, 's3' - ); +```php +$path = $request->file('avatar')->store( + 'avatars/'.$request->user()->id, 's3' +); +``` If you are using the `storeAs` method, you may pass the disk name as the third argument to the method: - $path = $request->file('avatar')->storeAs( - 'avatars', - $request->user()->id, - 's3' - ); +```php +$path = $request->file('avatar')->storeAs( + 'avatars', + $request->user()->id, + 's3' +); +``` #### Other Uploaded File Information If you would like to get the original name and extension of the uploaded file, you may do so using the `getClientOriginalName` and `getClientOriginalExtension` methods: - $file = $request->file('avatar'); +```php +$file = $request->file('avatar'); - $name = $file->getClientOriginalName(); - $extension = $file->getClientOriginalExtension(); +$name = $file->getClientOriginalName(); +$extension = $file->getClientOriginalExtension(); +``` However, keep in mind that the `getClientOriginalName` and `getClientOriginalExtension` methods are considered unsafe, as the file name and extension may be tampered with by a malicious user. For this reason, you should typically prefer the `hashName` and `extension` methods to get a name and an extension for the given file upload: - $file = $request->file('avatar'); +```php +$file = $request->file('avatar'); - $name = $file->hashName(); // Generate a unique, random name... - $extension = $file->extension(); // Determine the file's extension based on the file's MIME type... +$name = $file->hashName(); // Generate a unique, random name... +$extension = $file->extension(); // Determine the file's extension based on the file's MIME type... +``` ### File Visibility @@ -439,99 +654,197 @@ In Laravel's Flysystem integration, "visibility" is an abstraction of file permi You can set the visibility when writing the file via the `put` method: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - Storage::put('file.jpg', $contents, 'public'); +Storage::put('file.jpg', $contents, 'public'); +``` If the file has already been stored, its visibility can be retrieved and set via the `getVisibility` and `setVisibility` methods: - $visibility = Storage::getVisibility('file.jpg'); +```php +$visibility = Storage::getVisibility('file.jpg'); - Storage::setVisibility('file.jpg', 'public'); +Storage::setVisibility('file.jpg', 'public'); +``` When interacting with uploaded files, you may use the `storePublicly` and `storePubliclyAs` methods to store the uploaded file with `public` visibility: - $path = $request->file('avatar')->storePublicly('avatars', 's3'); +```php +$path = $request->file('avatar')->storePublicly('avatars', 's3'); - $path = $request->file('avatar')->storePubliclyAs( - 'avatars', - $request->user()->id, - 's3' - ); +$path = $request->file('avatar')->storePubliclyAs( + 'avatars', + $request->user()->id, + 's3' +); +``` -#### Local Files & Visibility +#### Local Files and Visibility When using the `local` driver, `public` [visibility](#file-visibility) translates to `0755` permissions for directories and `0644` permissions for files. You can modify the permissions mappings in your application's `filesystems` configuration file: - 'local' => [ - 'driver' => 'local', - 'root' => storage_path('app'), - 'permissions' => [ - 'file' => [ - 'public' => 0644, - 'private' => 0600, - ], - 'dir' => [ - 'public' => 0755, - 'private' => 0700, - ], +```php +'local' => [ + 'driver' => 'local', + 'root' => storage_path('app'), + 'permissions' => [ + 'file' => [ + 'public' => 0644, + 'private' => 0600, + ], + 'dir' => [ + 'public' => 0755, + 'private' => 0700, ], ], + 'throw' => false, +], +``` ## Deleting Files The `delete` method accepts a single filename or an array of files to delete: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - Storage::delete('file.jpg'); +Storage::delete('file.jpg'); - Storage::delete(['file.jpg', 'file2.jpg']); +Storage::delete(['file.jpg', 'file2.jpg']); +``` If necessary, you may specify the disk that the file should be deleted from: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - Storage::disk('s3')->delete('path/file.jpg'); +Storage::disk('s3')->delete('path/file.jpg'); +``` ## Directories -#### Get All Files Within A Directory +#### Get All Files Within a Directory -The `files` method returns an array of all of the files in a given directory. If you would like to retrieve a list of all files within a given directory including all subdirectories, you may use the `allFiles` method: +The `files` method returns an array of all files within a given directory. If you would like to retrieve a list of all files within a given directory including subdirectories, you may use the `allFiles` method: - use Illuminate\Support\Facades\Storage; +```php +use Illuminate\Support\Facades\Storage; - $files = Storage::files($directory); +$files = Storage::files($directory); - $files = Storage::allFiles($directory); +$files = Storage::allFiles($directory); +``` -#### Get All Directories Within A Directory +#### Get All Directories Within a Directory -The `directories` method returns an array of all the directories within a given directory. Additionally, you may use the `allDirectories` method to get a list of all directories within a given directory and all of its subdirectories: +The `directories` method returns an array of all directories within a given directory. If you would like to retrieve a list of all directories within a given directory including subdirectories, you may use the `allDirectories` method: - $directories = Storage::directories($directory); +```php +$directories = Storage::directories($directory); - $directories = Storage::allDirectories($directory); +$directories = Storage::allDirectories($directory); +``` -#### Create A Directory +#### Create a Directory The `makeDirectory` method will create the given directory, including any needed subdirectories: - Storage::makeDirectory($directory); +```php +Storage::makeDirectory($directory); +``` -#### Delete A Directory +#### Delete a Directory Finally, the `deleteDirectory` method may be used to remove a directory and all of its files: - Storage::deleteDirectory($directory); +```php +Storage::deleteDirectory($directory); +``` + + +## Testing + +The `Storage` facade's `fake` method allows you to easily generate a fake disk that, combined with the file generation utilities of the `Illuminate\Http\UploadedFile` class, greatly simplifies the testing of file uploads. For example: + +```php tab=Pest +json('POST', '/photos', [ + UploadedFile::fake()->image('photo1.jpg'), + UploadedFile::fake()->image('photo2.jpg') + ]); + + // Assert one or more files were stored... + Storage::disk('photos')->assertExists('photo1.jpg'); + Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']); + + // Assert one or more files were not stored... + Storage::disk('photos')->assertMissing('missing.jpg'); + Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']); + + // Assert that the number of files in a given directory matches the expected count... + Storage::disk('photos')->assertCount('/wallpapers', 2); + + // Assert that a given directory is empty... + Storage::disk('photos')->assertDirectoryEmpty('/wallpapers'); +}); +``` + +```php tab=PHPUnit +json('POST', '/photos', [ + UploadedFile::fake()->image('photo1.jpg'), + UploadedFile::fake()->image('photo2.jpg') + ]); + + // Assert one or more files were stored... + Storage::disk('photos')->assertExists('photo1.jpg'); + Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']); + + // Assert one or more files were not stored... + Storage::disk('photos')->assertMissing('missing.jpg'); + Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']); + + // Assert that the number of files in a given directory matches the expected count... + Storage::disk('photos')->assertCount('/wallpapers', 2); + + // Assert that a given directory is empty... + Storage::disk('photos')->assertDirectoryEmpty('/wallpapers'); + } +} +``` + +By default, the `fake` method will delete all files in its temporary directory. If you would like to keep these files, you may use the "persistentFake" method instead. For more information on testing file uploads, you may consult the [HTTP testing documentation's information on file uploads](/docs/{{version}}/http-tests#testing-file-uploads). + +> [!WARNING] +> The `image` method requires the [GD extension](https://www.php.net/manual/en/book.image.php). ## Custom Filesystems @@ -546,49 +859,48 @@ composer require spatie/flysystem-dropbox Next, you can register the driver within the `boot` method of one of your application's [service providers](/docs/{{version}}/providers). To accomplish this, you should use the `extend` method of the `Storage` facade: - +## Introduction + +[Laravel Folio](https://github.com/laravel/folio) is a powerful page based router designed to simplify routing in Laravel applications. With Laravel Folio, generating a route becomes as effortless as creating a Blade template within your application's `resources/views/pages` directory. + +For example, to create a page that is accessible at the `/greeting` URL, just create a `greeting.blade.php` file in your application's `resources/views/pages` directory: + +```php +
+ Hello World +
+``` + + +## Installation + +To get started, install Folio into your project using the Composer package manager: + +```shell +composer require laravel/folio +``` + +After installing Folio, you may execute the `folio:install` Artisan command, which will install Folio's service provider into your application. This service provider registers the directory where Folio will search for routes / pages: + +```shell +php artisan folio:install +``` + + +### Page Paths / URIs + +By default, Folio serves pages from your application's `resources/views/pages` directory, but you may customize these directories in your Folio service provider's `boot` method. + +For example, sometimes it may be convenient to specify multiple Folio paths in the same Laravel application. You may wish to have a separate directory of Folio pages for your application's "admin" area, while using another directory for the rest of your application's pages. + +You may accomplish this using the `Folio::path` and `Folio::uri` methods. The `path` method registers a directory that Folio will scan for pages when routing incoming HTTP requests, while the `uri` method specifies the "base URI" for that directory of pages: + +```php +use Laravel\Folio\Folio; + +Folio::path(resource_path('views/pages/guest'))->uri('/'); + +Folio::path(resource_path('views/pages/admin')) + ->uri('/admin') + ->middleware([ + '*' => [ + 'auth', + 'verified', + + // ... + ], + ]); +``` + + +### Subdomain Routing + +You may also route to pages based on the incoming request's subdomain. For example, you may wish to route requests from `admin.example.com` to a different page directory than the rest of your Folio pages. You may accomplish this by invoking the `domain` method after invoking the `Folio::path` method: + +```php +use Laravel\Folio\Folio; + +Folio::domain('admin.example.com') + ->path(resource_path('views/pages/admin')); +``` + +The `domain` method also allows you to capture parts of the domain or subdomain as parameters. These parameters will be injected into your page template: + +```php +use Laravel\Folio\Folio; + +Folio::domain('{account}.example.com') + ->path(resource_path('views/pages/admin')); +``` + + +## Creating Routes + +You may create a Folio route by placing a Blade template in any of your Folio mounted directories. By default, Folio mounts the `resources/views/pages` directory, but you may customize these directories in your Folio service provider's `boot` method. + +Once a Blade template has been placed in a Folio mounted directory, you may immediately access it via your browser. For example, a page placed in `pages/schedule.blade.php` may be accessed in your browser at `http://example.com/schedule`. + +To quickly view a list of all of your Folio pages / routes, you may invoke the `folio:list` Artisan command: + +```shell +php artisan folio:list +``` + + +### Nested Routes + +You may create a nested route by creating one or more directories within one of Folio's directories. For instance, to create a page that is accessible via `/user/profile`, create a `profile.blade.php` template within the `pages/user` directory: + +```shell +php artisan folio:page user/profile + +# pages/user/profile.blade.php → /user/profile +``` + + +### Index Routes + +Sometimes, you may wish to make a given page the "index" of a directory. By placing an `index.blade.php` template within a Folio directory, any requests to the root of that directory will be routed to that page: + +```shell +php artisan folio:page index +# pages/index.blade.php → / + +php artisan folio:page users/index +# pages/users/index.blade.php → /users +``` + + +## Route Parameters + +Often, you will need to have segments of the incoming request's URL injected into your page so that you can interact with them. For example, you may need to access the "ID" of the user whose profile is being displayed. To accomplish this, you may encapsulate a segment of the page's filename in square brackets: + +```shell +php artisan folio:page "users/[id]" + +# pages/users/[id].blade.php → /users/1 +``` + +Captured segments can be accessed as variables within your Blade template: + +```html +
+ User {{ $id }} +
+``` + +To capture multiple segments, you can prefix the encapsulated segment with three dots `...`: + +```shell +php artisan folio:page "users/[...ids]" + +# pages/users/[...ids].blade.php → /users/1/2/3 +``` + +When capturing multiple segments, the captured segments will be injected into the page as an array: + +```html +
    + @foreach ($ids as $id) +
  • User {{ $id }}
  • + @endforeach +
+``` + + +## Route Model Binding + +If a wildcard segment of your page template's filename corresponds one of your application's Eloquent models, Folio will automatically take advantage of Laravel's route model binding capabilities and attempt to inject the resolved model instance into your page: + +```shell +php artisan folio:page "users/[User]" + +# pages/users/[User].blade.php → /users/1 +``` + +Captured models can be accessed as variables within your Blade template. The model's variable name will be converted to "camel case": + +```html +
+ User {{ $user->id }} +
+``` + +#### Customizing the Key + +Sometimes you may wish to resolve bound Eloquent models using a column other than `id`. To do so, you may specify the column in the page's filename. For example, a page with the filename `[Post:slug].blade.php` will attempt to resolve the bound model via the `slug` column instead of the `id` column. + +On Windows, you should use `-` to separate the model name from the key: `[Post-slug].blade.php`. + +#### Model Location + +By default, Folio will search for your model within your application's `app/Models` directory. However, if needed, you may specify the fully-qualified model class name in your template's filename: + +```shell +php artisan folio:page "users/[.App.Models.User]" + +# pages/users/[.App.Models.User].blade.php → /users/1 +``` + + +### Soft Deleted Models + +By default, models that have been soft deleted are not retrieved when resolving implicit model bindings. However, if you wish, you can instruct Folio to retrieve soft deleted models by invoking the `withTrashed` function within the page's template: + +```php + + +
+ User {{ $user->id }} +
+``` + + +## Render Hooks + +By default, Folio will return the content of the page's Blade template as the response to the incoming request. However, you may customize the response by invoking the `render` function within the page's template. + +The `render` function accepts a closure which will receive the `View` instance being rendered by Folio, allowing you to add additional data to the view or customize the entire response. In addition to receiving the `View` instance, any additional route parameters or model bindings will also be provided to the `render` closure: + +```php +can('view', $post)) { + return response('Unauthorized', 403); + } + + return $view->with('photos', $post->author->photos); +}); ?> + +
+ {{ $post->content }} +
+ +
+ This author has also taken {{ count($photos) }} photos. +
+``` + + +## Named Routes + +You may specify a name for a given page's route using the `name` function: + +```php + + All Users + +``` + +If the page has parameters, you may simply pass their values to the `route` function: + +```php +route('users.show', ['user' => $user]); +``` + + +## Middleware + +You can apply middleware to a specific page by invoking the `middleware` function within the page's template: + +```php + + +
+ Dashboard +
+``` + +Or, to assign middleware to a group of pages, you may chain the `middleware` method after invoking the `Folio::path` method. + +To specify which pages the middleware should be applied to, the array of middleware may be keyed using the corresponding URL patterns of the pages they should be applied to. The `*` character may be utilized as a wildcard character: + +```php +use Laravel\Folio\Folio; + +Folio::path(resource_path('views/pages'))->middleware([ + 'admin/*' => [ + 'auth', + 'verified', + + // ... + ], +]); +``` + +You may include closures in the array of middleware to define inline, anonymous middleware: + +```php +use Closure; +use Illuminate\Http\Request; +use Laravel\Folio\Folio; + +Folio::path(resource_path('views/pages'))->middleware([ + 'admin/*' => [ + 'auth', + 'verified', + + function (Request $request, Closure $next) { + // ... + + return $next($request); + }, + ], +]); +``` + + +## Route Caching + +When using Folio, you should always take advantage of [Laravel's route caching capabilities](/docs/{{version}}/routing#route-caching). Folio listens for the `route:cache` Artisan command to ensure that Folio page definitions and route names are properly cached for maximum performance. diff --git a/fortify.md b/fortify.md index 50d9cfdb5b2..2293a45b04c 100644 --- a/fortify.md +++ b/fortify.md @@ -1,25 +1,24 @@ # Laravel Fortify - [Introduction](#introduction) - - [What Is Fortify?](#what-is-fortify) + - [What is Fortify?](#what-is-fortify) - [When Should I Use Fortify?](#when-should-i-use-fortify) - [Installation](#installation) - - [The Fortify Service Provider](#the-fortify-service-provider) - [Fortify Features](#fortify-features) - [Disabling Views](#disabling-views) - [Authentication](#authentication) - [Customizing User Authentication](#customizing-user-authentication) - - [Customizing The Authentication Pipeline](#customizing-the-authentication-pipeline) + - [Customizing the Authentication Pipeline](#customizing-the-authentication-pipeline) - [Customizing Redirects](#customizing-authentication-redirects) -- [Two Factor Authentication](#two-factor-authentication) - - [Enabling Two Factor Authentication](#enabling-two-factor-authentication) - - [Authenticating With Two Factor Authentication](#authenticating-with-two-factor-authentication) - - [Disabling Two Factor Authentication](#disabling-two-factor-authentication) +- [Two-Factor Authentication](#two-factor-authentication) + - [Enabling Two-Factor Authentication](#enabling-two-factor-authentication) + - [Authenticating With Two-Factor Authentication](#authenticating-with-two-factor-authentication) + - [Disabling Two-Factor Authentication](#disabling-two-factor-authentication) - [Registration](#registration) - [Customizing Registration](#customizing-registration) - [Password Reset](#password-reset) - - [Requesting A Password Reset Link](#requesting-a-password-reset-link) - - [Resetting The Password](#resetting-the-password) + - [Requesting a Password Reset Link](#requesting-a-password-reset-link) + - [Resetting the Password](#resetting-the-password) - [Customizing Password Resets](#customizing-password-resets) - [Email Verification](#email-verification) - [Protecting Routes](#protecting-routes) @@ -32,23 +31,24 @@ Since Fortify does not provide its own user interface, it is meant to be paired with your own user interface which makes requests to the routes it registers. We will discuss exactly how to make requests to these routes in the remainder of this documentation. -> {tip} Remember, Fortify is a package that is meant to give you a head start implementing Laravel's authentication features. **You are not required to use it.** You are always free to manually interact with Laravel's authentication services by following the documentation available in the [authentication](/docs/{{version}}/authentication), [password reset](/docs/{{version}}/passwords), and [email verification](/docs/{{version}}/verification) documentation. +> [!NOTE] +> Remember, Fortify is a package that is meant to give you a head start implementing Laravel's authentication features. **You are not required to use it.** You are always free to manually interact with Laravel's authentication services by following the documentation available in the [authentication](/docs/{{version}}/authentication), [password reset](/docs/{{version}}/passwords), and [email verification](/docs/{{version}}/verification) documentation. -### What Is Fortify? +### What is Fortify? As mentioned previously, Laravel Fortify is a frontend agnostic authentication backend implementation for Laravel. Fortify registers the routes and controllers needed to implement all of Laravel's authentication features, including login, registration, password reset, email verification, and more. **You are not required to use Fortify in order to use Laravel's authentication features.** You are always free to manually interact with Laravel's authentication services by following the documentation available in the [authentication](/docs/{{version}}/authentication), [password reset](/docs/{{version}}/passwords), and [email verification](/docs/{{version}}/verification) documentation. -If you are new to Laravel, you may wish to explore the [Laravel Breeze](/docs/{{version}}/starter-kits) application starter kit before attempting to use Laravel Fortify. Laravel Breeze provides an authentication scaffolding for your application that includes a user interface built with [Tailwind CSS](https://tailwindcss.com). Unlike Fortify, Breeze publishes its routes and controllers directly into your application. This allows you to study and get comfortable with Laravel's authentication features before allowing Laravel Fortify to implement these features for you. +If you are new to Laravel, you may wish to explore [our application starter kits](/docs/{{version}}/starter-kits). Laravel's application starter kits use Fortify internally to provide authentication scaffolding for your application that includes a user interface built with [Tailwind CSS](https://tailwindcss.com). This allows you to study and get comfortable with Laravel's authentication features. -Laravel Fortify essentially takes the routes and controllers of Laravel Breeze and offers them as a package that does not include a user interface. This allows you to still quickly scaffold the backend implementation of your application's authentication layer without being tied to any particular frontend opinions. +Laravel Fortify essentially takes the routes and controllers of our application starter kits and offers them as a package that does not include a user interface. This allows you to still quickly scaffold the backend implementation of your application's authentication layer without being tied to any particular frontend opinions. ### When Should I Use Fortify? -You may be wondering when it is appropriate to use Laravel Fortify. First, if you are using one of Laravel's [application starter kits](/docs/{{version}}/starter-kits), you do not need to install Laravel Fortify since all of Laravel's application starter kits already provide a full authentication implementation. +You may be wondering when it is appropriate to use Laravel Fortify. First, if you are using one of Laravel's [application starter kits](/docs/{{version}}/starter-kits), you do not need to install Laravel Fortify since all of Laravel's application starter kits use Fortify and already provide a full authentication implementation. If you are not using an application starter kit and your application needs authentication features, you have two options: manually implement your application's authentication features or use Laravel Fortify to provide the backend implementation of these features. @@ -57,7 +57,7 @@ If you choose to install Fortify, your user interface will make requests to Fort If you choose to manually interact with Laravel's authentication services instead of using Fortify, you may do so by following the documentation available in the [authentication](/docs/{{version}}/authentication), [password reset](/docs/{{version}}/passwords), and [email verification](/docs/{{version}}/verification) documentation. -#### Laravel Fortify & Laravel Sanctum +#### Laravel Fortify and Laravel Sanctum Some developers become confused regarding the difference between [Laravel Sanctum](/docs/{{version}}/sanctum) and Laravel Fortify. Because the two packages solve two different but related problems, Laravel Fortify and Laravel Sanctum are not mutually exclusive or competing packages. @@ -74,13 +74,13 @@ To get started, install Fortify using the Composer package manager: composer require laravel/fortify ``` -Next, publish Fortify's resources using the `vendor:publish` command: +Next, publish Fortify's resources using the `fortify:install` Artisan command: ```shell -php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider" +php artisan fortify:install ``` -This command will publish Fortify's actions to your `app/Actions` directory, which will be created if it does not exist. In addition, Fortify's configuration file and migrations will be published. +This command will publish Fortify's actions to your `app/Actions` directory, which will be created if it does not exist. In addition, the `FortifyServiceProvider`, configuration file, and all necessary database migrations will be published. Next, you should migrate your database: @@ -88,17 +88,10 @@ Next, you should migrate your database: php artisan migrate ``` - -### The Fortify Service Provider - -The `vendor:publish` command discussed above will also publish the `App\Providers\FortifyServiceProvider` class. You should ensure this class is registered within the `providers` array of your application's `config/app.php` configuration file. - -The Fortify service provider registers the actions that Fortify published and instructs Fortify to use them when their respective tasks are executed by Fortify. - ### Fortify Features -The `fortify` configuration file contains a `features` configuration array. This array defines which backend routes / features Fortify will expose by default. If you are not using Fortify in combination with [Laravel Jetstream](https://jetstream.laravel.com), we recommend that you only enable the following features, which are the basic authentication features provided by most Laravel applications: +The `fortify` configuration file contains a `features` configuration array. This array defines which backend routes / features Fortify will expose by default. We recommend that you only enable the following features, which are the basic authentication features provided by most Laravel applications: ```php 'features' => [ @@ -118,7 +111,7 @@ By default, Fortify defines routes that are intended to return views, such as a ``` -#### Disabling Views & Password Reset +#### Disabling Views and Password Reset If you choose to disable Fortify's views and you will be implementing password reset features for your application, you should still define a route named `password.reset` that is responsible for displaying your application's "reset password" view. This is necessary because Laravel's `Illuminate\Auth\Notifications\ResetPassword` notification will generate the password reset URL via the `password.reset` named route. @@ -129,21 +122,21 @@ To get started, we need to instruct Fortify how to return our "login" view. Reme All of the authentication view's rendering logic may be customized using the appropriate methods available via the `Laravel\Fortify\Fortify` class. Typically, you should call this method from the `boot` method of your application's `App\Providers\FortifyServiceProvider` class. Fortify will take care of defining the `/login` route that returns this view: - use Laravel\Fortify\Fortify; +```php +use Laravel\Fortify\Fortify; - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - Fortify::loginView(function () { - return view('auth.login'); - }); +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Fortify::loginView(function () { + return view('auth.login'); + }); - // ... - } + // ... +} +``` Your login template should include a form that makes a POST request to `/login`. The `/login` endpoint expects a string `email` / `username` and a `password`. The name of the email / username field should match the `username` value within the `config/fortify.php` configuration file. In addition, a boolean `remember` field may be provided to indicate that the user would like to use the "remember me" functionality provided by Laravel. @@ -166,10 +159,8 @@ use Laravel\Fortify\Fortify; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Fortify::authenticateUsing(function (Request $request) { $user = User::where('email', $request->email)->first(); @@ -190,7 +181,7 @@ public function boot() You may customize the authentication guard used by Fortify within your application's `fortify` configuration file. However, you should ensure that the configured guard is an implementation of `Illuminate\Contracts\Auth\StatefulGuard`. If you are attempting to use Laravel Fortify to authenticate an SPA, you should use Laravel's default `web` guard in combination with [Laravel Sanctum](https://laravel.com/docs/sanctum). -### Customizing The Authentication Pipeline +### Customizing the Authentication Pipeline Laravel Fortify authenticates login requests through a pipeline of invokable classes. If you would like, you may define a custom pipeline of classes that login requests should be piped through. Each class should have an `__invoke` method which receives the incoming `Illuminate\Http\Request` instance and, like [middleware](/docs/{{version}}/middleware), a `$next` variable that is invoked in order to pass the request to the next class in the pipeline. @@ -200,15 +191,18 @@ The example below contains the default pipeline definition that you may use as a ```php use Laravel\Fortify\Actions\AttemptToAuthenticate; +use Laravel\Fortify\Actions\CanonicalizeUsername; use Laravel\Fortify\Actions\EnsureLoginIsNotThrottled; use Laravel\Fortify\Actions\PrepareAuthenticatedSession; use Laravel\Fortify\Actions\RedirectIfTwoFactorAuthenticatable; +use Laravel\Fortify\Features; use Laravel\Fortify\Fortify; use Illuminate\Http\Request; Fortify::authenticateThrough(function (Request $request) { return array_filter([ config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class, + config('fortify.lowercase_usernames') ? CanonicalizeUsername::class : null, Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null, AttemptToAuthenticate::class, PrepareAuthenticatedSession::class, @@ -216,6 +210,15 @@ Fortify::authenticateThrough(function (Request $request) { }); ``` +#### Authentication Throttling + +By default, Fortify will throttle authentication attempts using the `EnsureLoginIsNotThrottled` middleware. This middleware throttles attempts that are unique to a username and IP address combination. + +Some applications may require a different approach to throttling authentication attempts, such as throttling by IP address alone. Therefore, Fortify allows you to specify your own [rate limiter](/docs/{{version}}/routing#rate-limiting) via the `fortify.limiters.login` configuration option. Of course, this configuration option is located in your application's `config/fortify.php` configuration file. + +> [!NOTE] +> Utilizing a mixture of throttling, [two-factor authentication](/docs/{{version}}/fortify#two-factor-authentication), and an external web application firewall (WAF) will provide the most robust defense for your legitimate application users. + ### Customizing Redirects @@ -228,10 +231,8 @@ use Laravel\Fortify\Contracts\LogoutResponse; /** * Register any application services. - * - * @return void */ -public function register() +public function register(): void { $this->app->instance(LogoutResponse::class, new class implements LogoutResponse { public function toResponse($request) @@ -243,9 +244,9 @@ public function register() ``` -## Two Factor Authentication +## Two-Factor Authentication -When Fortify's two factor authentication feature is enabled, the user is required to input a six digit numeric token during the authentication process. This token is generated using a time-based one-time password (TOTP) that can be retrieved from any TOTP compatible mobile authentication application such as Google Authenticator. +When Fortify's two-factor authentication feature is enabled, the user is required to input a six digit numeric token during the authentication process. This token is generated using a time-based one-time password (TOTP) that can be retrieved from any TOTP compatible mobile authentication application such as Google Authenticator. Before getting started, you should first ensure that your application's `App\Models\User` model uses the `Laravel\Fortify\TwoFactorAuthenticatable` trait: @@ -262,37 +263,56 @@ class User extends Authenticatable { use Notifiable, TwoFactorAuthenticatable; } - ``` +``` -Next, you should build a screen within your application where users can manage their two factor authentication settings. This screen should allow the user to enable and disable two factor authentication, as well as regenerate their two factor authentication recovery codes. +Next, you should build a screen within your application where users can manage their two-factor authentication settings. This screen should allow the user to enable and disable two-factor authentication, as well as regenerate their two-factor authentication recovery codes. -> By default, the `features` array of the `fortify` configuration file instructs Fortify's two factor authentication settings to require password confirmation before modification. Therefore, your application should implement Fortify's [password confirmation](#password-confirmation) feature before continuing. +> By default, the `features` array of the `fortify` configuration file instructs Fortify's two-factor authentication settings to require password confirmation before modification. Therefore, your application should implement Fortify's [password confirmation](#password-confirmation) feature before continuing. -### Enabling Two Factor Authentication +### Enabling Two-Factor Authentication -To enable two factor authentication, your application should make a POST request to the `/user/two-factor-authentication` endpoint defined by Fortify. If the request is successful, the user will be redirected back to the previous URL and the `status` session variable will be set to `two-factor-authentication-enabled`. You may detect this `status` session variable within your templates to display the appropriate success message. If the request was an XHR request, `200` HTTP response will be returned: +To begin enabling two-factor authentication, your application should make a POST request to the `/user/two-factor-authentication` endpoint defined by Fortify. If the request is successful, the user will be redirected back to the previous URL and the `status` session variable will be set to `two-factor-authentication-enabled`. You may detect this `status` session variable within your templates to display the appropriate success message. If the request was an XHR request, `200` HTTP response will be returned. + +After choosing to enable two-factor authentication, the user must still "confirm" their two-factor authentication configuration by providing a valid two-factor authentication code. So, your "success" message should instruct the user that two-factor authentication confirmation is still required: ```html @if (session('status') == 'two-factor-authentication-enabled') -
- Two factor authentication has been enabled. +
+ Please finish configuring two-factor authentication below.
@endif ``` -Next, you should display the two factor authentication QR code for the user to scan into their authenticator application. If you are using Blade to render your application's frontend, you may retrieve the QR code SVG using the `twoFactorQrCodeSvg` method available on the user instance: +Next, you should display the two-factor authentication QR code for the user to scan into their authenticator application. If you are using Blade to render your application's frontend, you may retrieve the QR code SVG using the `twoFactorQrCodeSvg` method available on the user instance: ```php $request->user()->twoFactorQrCodeSvg(); ``` -If you are building a JavaScript powered frontend, you may make an XHR GET request to the `/user/two-factor-qr-code` endpoint to retrieve the user's two factor authentication QR code. This endpoint will return a JSON object containing an `svg` key. +If you are building a JavaScript powered frontend, you may make an XHR GET request to the `/user/two-factor-qr-code` endpoint to retrieve the user's two-factor authentication QR code. This endpoint will return a JSON object containing an `svg` key. + + +#### Confirming Two-Factor Authentication + +In addition to displaying the user's two-factor authentication QR code, you should provide a text input where the user can supply a valid authentication code to "confirm" their two-factor authentication configuration. This code should be provided to the Laravel application via a POST request to the `/user/confirmed-two-factor-authentication` endpoint defined by Fortify. + +If the request is successful, the user will be redirected back to the previous URL and the `status` session variable will be set to `two-factor-authentication-confirmed`: + +```html +@if (session('status') == 'two-factor-authentication-confirmed') +
+ Two-factor authentication confirmed and enabled successfully. +
+@endif +``` + +If the request to the two-factor authentication confirmation endpoint was made via an XHR request, a `200` HTTP response will be returned. -#### Displaying The Recovery Codes +#### Displaying the Recovery Codes -You should also display the user's two factor recovery codes. These recovery codes allow the user to authenticate if they lose access to their mobile device. If you are using Blade to render your application's frontend, you may access the recovery codes via the authenticated user instance: +You should also display the user's two-factor recovery codes. These recovery codes allow the user to authenticate if they lose access to their mobile device. If you are using Blade to render your application's frontend, you may access the recovery codes via the authenticated user instance: ```php (array) $request->user()->recoveryCodes() @@ -303,21 +323,19 @@ If you are building a JavaScript powered frontend, you may make an XHR GET reque To regenerate the user's recovery codes, your application should make a POST request to the `/user/two-factor-recovery-codes` endpoint. -### Authenticating With Two Factor Authentication +### Authenticating With Two-Factor Authentication -During the authentication process, Fortify will automatically redirect the user to your application's two factor authentication challenge screen. However, if your application is making an XHR login request, the JSON response returned after a successful authentication attempt will contain a JSON object that has a `two_factor` boolean property. You should inspect this value to know whether you should redirect to your application's two factor authentication challenge screen. +During the authentication process, Fortify will automatically redirect the user to your application's two-factor authentication challenge screen. However, if your application is making an XHR login request, the JSON response returned after a successful authentication attempt will contain a JSON object that has a `two_factor` boolean property. You should inspect this value to know whether you should redirect to your application's two-factor authentication challenge screen. -To begin implementing two factor authentication functionality, we need to instruct Fortify how to return our two factor authentication challenge view. All of Fortify's authentication view rendering logic may be customized using the appropriate methods available via the `Laravel\Fortify\Fortify` class. Typically, you should call this method from the `boot` method of your application's `App\Providers\FortifyServiceProvider` class: +To begin implementing two-factor authentication functionality, we need to instruct Fortify how to return our two-factor authentication challenge view. All of Fortify's authentication view rendering logic may be customized using the appropriate methods available via the `Laravel\Fortify\Fortify` class. Typically, you should call this method from the `boot` method of your application's `App\Providers\FortifyServiceProvider` class: ```php use Laravel\Fortify\Fortify; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Fortify::twoFactorChallengeView(function () { return view('auth.two-factor-challenge'); @@ -331,29 +349,27 @@ Fortify will take care of defining the `/two-factor-challenge` route that return If the login attempt is successful, Fortify will redirect the user to the URI configured via the `home` configuration option within your application's `fortify` configuration file. If the login request was an XHR request, a 204 HTTP response will be returned. -If the request was not successful, the user will be redirected back to the two factor challenge screen and the validation errors will be available to you via the shared `$errors` [Blade template variable](/docs/{{version}}/validation#quick-displaying-the-validation-errors). Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response. +If the request was not successful, the user will be redirected back to the two-factor challenge screen and the validation errors will be available to you via the shared `$errors` [Blade template variable](/docs/{{version}}/validation#quick-displaying-the-validation-errors). Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response. -### Disabling Two Factor Authentication +### Disabling Two-Factor Authentication -To disable two factor authentication, your application should make a DELETE request to the `/user/two-factor-authentication` endpoint. Remember, Fortify's two factor authentication endpoints require [password confirmation](#password-confirmation) prior to being called. +To disable two-factor authentication, your application should make a DELETE request to the `/user/two-factor-authentication` endpoint. Remember, Fortify's two-factor authentication endpoints require [password confirmation](#password-confirmation) prior to being called. ## Registration To begin implementing our application's registration functionality, we need to instruct Fortify how to return our "register" view. Remember, Fortify is a headless authentication library. If you would like a frontend implementation of Laravel's authentication features that are already completed for you, you should use an [application starter kit](/docs/{{version}}/starter-kits). -All of the Fortify's view rendering logic may be customized using the appropriate methods available via the `Laravel\Fortify\Fortify` class. Typically, you should call this method from the `boot` method of your `App\Providers\FortifyServiceProvider` class: +All of Fortify's view rendering logic may be customized using the appropriate methods available via the `Laravel\Fortify\Fortify` class. Typically, you should call this method from the `boot` method of your `App\Providers\FortifyServiceProvider` class: ```php use Laravel\Fortify\Fortify; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Fortify::registerView(function () { return view('auth.register'); @@ -367,7 +383,7 @@ Fortify will take care of defining the `/register` route that returns this view. The `/register` endpoint expects a string `name`, string email address / username, `password`, and `password_confirmation` fields. The name of the email / username field should match the `username` configuration value defined within your application's `fortify` configuration file. -If the registration attempt is successful, Fortify will redirect the user to the URI configured via the `home` configuration option within your application's `fortify` configuration file. If the login request was an XHR request, a 200 HTTP response will be returned. +If the registration attempt is successful, Fortify will redirect the user to the URI configured via the `home` configuration option within your application's `fortify` configuration file. If the request was an XHR request, a 201 HTTP response will be returned. If the request was not successful, the user will be redirected back to the registration screen and the validation errors will be available to you via the shared `$errors` [Blade template variable](/docs/{{version}}/validation#quick-displaying-the-validation-errors). Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response. @@ -380,7 +396,7 @@ The user validation and creation process may be customized by modifying the `App ## Password Reset -### Requesting A Password Reset Link +### Requesting a Password Reset Link To begin implementing our application's password reset functionality, we need to instruct Fortify how to return our "forgot password" view. Remember, Fortify is a headless authentication library. If you would like a frontend implementation of Laravel's authentication features that are already completed for you, you should use an [application starter kit](/docs/{{version}}/starter-kits). @@ -391,10 +407,8 @@ use Laravel\Fortify\Fortify; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Fortify::requestPasswordResetLinkView(function () { return view('auth.forgot-password'); @@ -409,11 +423,13 @@ Fortify will take care of defining the `/forgot-password` endpoint that returns The `/forgot-password` endpoint expects a string `email` field. The name of this field / database column should match the `email` configuration value within your application's `fortify` configuration file. -#### Handling The Password Reset Link Request Response +#### Handling the Password Reset Link Request Response If the password reset link request was successful, Fortify will redirect the user back to the `/forgot-password` endpoint and send an email to the user with a secure link they can use to reset their password. If the request was an XHR request, a 200 HTTP response will be returned. -After being redirected back to the `/forgot-password` endpoint after a successful request, the `status` session variable may be used to display the status of the password reset link request attempt. The value of this session variable will match one of the translation strings defined within your application's `passwords` [language file](/docs/{{version}}/localization): +After being redirected back to the `/forgot-password` endpoint after a successful request, the `status` session variable may be used to display the status of the password reset link request attempt. + +The value of the `$status` session variable will match one of the translation strings defined within your application's `passwords` [language file](/docs/{{version}}/localization). If you would like to customize this value and have not published Laravel's language files, you may do so via the `lang:publish` Artisan command: ```html @if (session('status')) @@ -426,7 +442,7 @@ After being redirected back to the `/forgot-password` endpoint after a successfu If the request was not successful, the user will be redirected back to the request password reset link screen and the validation errors will be available to you via the shared `$errors` [Blade template variable](/docs/{{version}}/validation#quick-displaying-the-validation-errors). Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response. -### Resetting The Password +### Resetting the Password To finish implementing our application's password reset functionality, we need to instruct Fortify how to return our "reset password" view. @@ -434,15 +450,14 @@ All of Fortify's view rendering logic may be customized using the appropriate me ```php use Laravel\Fortify\Fortify; +use Illuminate\Http\Request; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { - Fortify::resetPasswordView(function ($request) { + Fortify::resetPasswordView(function (Request $request) { return view('auth.reset-password', ['request' => $request]); }); @@ -455,7 +470,7 @@ Fortify will take care of defining the route to display this view. Your `reset-p The `/reset-password` endpoint expects a string `email` field, a `password` field, a `password_confirmation` field, and a hidden field named `token` that contains the value of `request()->route('token')`. The name of the "email" field / database column should match the `email` configuration value defined within your application's `fortify` configuration file. -#### Handling The Password Reset Response +#### Handling the Password Reset Response If the password reset request was successful, Fortify will redirect back to the `/login` route so that the user can log in with their new password. In addition, a `status` session variable will be set so that you may display the successful status of the reset on your login screen: @@ -490,10 +505,8 @@ use Laravel\Fortify\Fortify; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Fortify::verifyEmailView(function () { return view('auth.verify-email'); @@ -525,7 +538,7 @@ If the request to resend the verification link email was successful, Fortify wil ### Protecting Routes -To specify that a route or group of routes requires that the user has verified their email address, you should attach Laravel's built-in `verified` middleware to the route. This middleware is registered within your application's `App\Http\Kernel` class: +To specify that a route or group of routes requires that the user has verified their email address, you should attach Laravel's built-in `verified` middleware to the route. The `verified` middleware alias is automatically registered by Laravel and serves as an alias for the `Illuminate\Auth\Middleware\EnsureEmailIsVerified` middleware: ```php Route::get('/dashboard', function () { @@ -547,10 +560,8 @@ use Laravel\Fortify\Fortify; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Fortify::confirmPasswordView(function () { return view('auth.confirm-password'); diff --git a/frontend.md b/frontend.md new file mode 100644 index 00000000000..31da734876e --- /dev/null +++ b/frontend.md @@ -0,0 +1,184 @@ +# Frontend + +- [Introduction](#introduction) +- [Using PHP](#using-php) + - [PHP and Blade](#php-and-blade) + - [Livewire](#livewire) + - [Starter Kits](#php-starter-kits) +- [Using React or Vue](#using-react-or-vue) + - [Inertia](#inertia) + - [Starter Kits](#inertia-starter-kits) +- [Bundling Assets](#bundling-assets) + + +## Introduction + +Laravel is a backend framework that provides all of the features you need to build modern web applications, such as [routing](/docs/{{version}}/routing), [validation](/docs/{{version}}/validation), [caching](/docs/{{version}}/cache), [queues](/docs/{{version}}/queues), [file storage](/docs/{{version}}/filesystem), and more. However, we believe it's important to offer developers a beautiful full-stack experience, including powerful approaches for building your application's frontend. + +There are two primary ways to tackle frontend development when building an application with Laravel, and which approach you choose is determined by whether you would like to build your frontend by leveraging PHP or by using JavaScript frameworks such as Vue and React. We'll discuss both of these options below so that you can make an informed decision regarding the best approach to frontend development for your application. + + +## Using PHP + + +### PHP and Blade + +In the past, most PHP applications rendered HTML to the browser using simple HTML templates interspersed with PHP `echo` statements which render data that was retrieved from a database during the request: + +```blade +
+ + Hello, name; ?>
+ +
+``` + +In Laravel, this approach to rendering HTML can still be achieved using [views](/docs/{{version}}/views) and [Blade](/docs/{{version}}/blade). Blade is an extremely light-weight templating language that provides convenient, short syntax for displaying data, iterating over data, and more: + +```blade +
+ @foreach ($users as $user) + Hello, {{ $user->name }}
+ @endforeach +
+``` + +When building applications in this fashion, form submissions and other page interactions typically receive an entirely new HTML document from the server and the entire page is re-rendered by the browser. Even today, many applications may be perfectly suited to having their frontends constructed in this way using simple Blade templates. + + +#### Growing Expectations + +However, as user expectations regarding web applications have matured, many developers have found the need to build more dynamic frontends with interactions that feel more polished. In light of this, some developers choose to begin building their application's frontend using JavaScript frameworks such as Vue and React. + +Others, preferring to stick with the backend language they are comfortable with, have developed solutions that allow the construction of modern web application UIs while still primarily utilizing their backend language of choice. For example, in the [Rails](https://rubyonrails.org/) ecosystem, this has spurred the creation of libraries such as [Turbo](https://turbo.hotwired.dev/) [Hotwire](https://hotwired.dev/), and [Stimulus](https://stimulus.hotwired.dev/). + +Within the Laravel ecosystem, the need to create modern, dynamic frontends by primarily using PHP has led to the creation of [Laravel Livewire](https://livewire.laravel.com) and [Alpine.js](https://alpinejs.dev/). + + +### Livewire + +[Laravel Livewire](https://livewire.laravel.com) is a framework for building Laravel powered frontends that feel dynamic, modern, and alive just like frontends built with modern JavaScript frameworks like Vue and React. + +When using Livewire, you will create Livewire "components" that render a discrete portion of your UI and expose methods and data that can be invoked and interacted with from your application's frontend. For example, a simple "Counter" component might look like the following: + +```php +count++; + } + + public function render() + { + return view('livewire.counter'); + } +} +``` + +And, the corresponding template for the counter would be written like so: + +```blade +
+ +

{{ $count }}

+
+``` + +As you can see, Livewire enables you to write new HTML attributes such as `wire:click` that connect your Laravel application's frontend and backend. In addition, you can render your component's current state using simple Blade expressions. + +For many, Livewire has revolutionized frontend development with Laravel, allowing them to stay within the comfort of Laravel while constructing modern, dynamic web applications. Typically, developers using Livewire will also utilize [Alpine.js](https://alpinejs.dev/) to "sprinkle" JavaScript onto their frontend only where it is needed, such as in order to render a dialog window. + +If you're new to Laravel, we recommend getting familiar with the basic usage of [views](/docs/{{version}}/views) and [Blade](/docs/{{version}}/blade). Then, consult the official [Laravel Livewire documentation](https://livewire.laravel.com/docs) to learn how to take your application to the next level with interactive Livewire components. + + +### Starter Kits + +If you would like to build your frontend using PHP and Livewire, you can leverage our [Livewire starter kit](/docs/{{version}}/starter-kits) to jump-start your application's development. + + +## Using React or Vue + +Although it's possible to build modern frontends using Laravel and Livewire, many developers still prefer to leverage the power of a JavaScript framework like React or Vue. This allows developers to take advantage of the rich ecosystem of JavaScript packages and tools available via NPM. + +However, without additional tooling, pairing Laravel with React or Vue would leave us needing to solve a variety of complicated problems such as client-side routing, data hydration, and authentication. Client-side routing is often simplified by using opinionated React / Vue frameworks such as [Next](https://nextjs.org/) and [Nuxt](https://nuxt.com/); however, data hydration and authentication remain complicated and cumbersome problems to solve when pairing a backend framework like Laravel with these frontend frameworks. + +In addition, developers are left maintaining two separate code repositories, often needing to coordinate maintenance, releases, and deployments across both repositories. While these problems are not insurmountable, we don't believe it's a productive or enjoyable way to develop applications. + + +### Inertia + +Thankfully, Laravel offers the best of both worlds. [Inertia](https://inertiajs.com) bridges the gap between your Laravel application and your modern React or Vue frontend, allowing you to build full-fledged, modern frontends using React or Vue while leveraging Laravel routes and controllers for routing, data hydration, and authentication — all within a single code repository. With this approach, you can enjoy the full power of both Laravel and React / Vue without crippling the capabilities of either tool. + +After installing Inertia into your Laravel application, you will write routes and controllers like normal. However, instead of returning a Blade template from your controller, you will return an Inertia page: + +```php + User::findOrFail($id) + ]); + } +} +``` + +An Inertia page corresponds to a React or Vue component, typically stored within the `resources/js/pages` directory of your application. The data given to the page via the `Inertia::render` method will be used to hydrate the "props" of the page component: + +```jsx +import Layout from '@/layouts/authenticated'; +import { Head } from '@inertiajs/react'; + +export default function Show({ user }) { + return ( + + +

Welcome

+

Hello {user.name}, welcome to Inertia.

+
+ ) +} +``` + +As you can see, Inertia allows you to leverage the full power of React or Vue when building your frontend, while providing a light-weight bridge between your Laravel powered backend and your JavaScript powered frontend. + +#### Server-Side Rendering + +If you're concerned about diving into Inertia because your application requires server-side rendering, don't worry. Inertia offers [server-side rendering support](https://inertiajs.com/server-side-rendering). And, when deploying your application via [Laravel Cloud](https://cloud.laravel.com) or [Laravel Forge](https://forge.laravel.com), it's a breeze to ensure that Inertia's server-side rendering process is always running. + + +### Starter Kits + +If you would like to build your frontend using Inertia and Vue / React, you can leverage our [React or Vue application starter kits](/docs/{{version}}/starter-kits) to jump-start your application's development. Both of these starter kits scaffold your application's backend and frontend authentication flow using Inertia, Vue / React, [Tailwind](https://tailwindcss.com), and [Vite](https://vitejs.dev) so that you can start building your next big idea. + + +## Bundling Assets + +Regardless of whether you choose to develop your frontend using Blade and Livewire or Vue / React and Inertia, you will likely need to bundle your application's CSS into production-ready assets. Of course, if you choose to build your application's frontend with Vue or React, you will also need to bundle your components into browser ready JavaScript assets. + +By default, Laravel utilizes [Vite](https://vitejs.dev) to bundle your assets. Vite provides lightning-fast build times and near instantaneous Hot Module Replacement (HMR) during local development. In all new Laravel applications, including those using our [starter kits](/docs/{{version}}/starter-kits), you will find a `vite.config.js` file that loads our light-weight Laravel Vite plugin that makes Vite a joy to use with Laravel applications. + +The fastest way to get started with Laravel and Vite is by beginning your application's development using [our application starter kits](/docs/{{version}}/starter-kits), which jump-starts your application by providing frontend and backend authentication scaffolding. + +> [!NOTE] +> For more detailed documentation on utilizing Vite with Laravel, please see our [dedicated documentation on bundling and compiling your assets](/docs/{{version}}/vite). diff --git a/hashing.md b/hashing.md index 414362496d8..2210343cae5 100644 --- a/hashing.md +++ b/hashing.md @@ -4,8 +4,9 @@ - [Configuration](#configuration) - [Basic Usage](#basic-usage) - [Hashing Passwords](#hashing-passwords) - - [Verifying That A Password Matches A Hash](#verifying-that-a-password-matches-a-hash) - - [Determining If A Password Needs To Be Rehashed](#determining-if-a-password-needs-to-be-rehashed) + - [Verifying That a Password Matches a Hash](#verifying-that-a-password-matches-a-hash) + - [Determining if a Password Needs to be Rehashed](#determining-if-a-password-needs-to-be-rehashed) +- [Hash Algorithm Verification](#hash-algorithm-verification) ## Introduction @@ -17,7 +18,13 @@ Bcrypt is a great choice for hashing passwords because its "work factor" is adju ## Configuration -The default hashing driver for your application is configured in your application's `config/hashing.php` configuration file. There are currently several supported drivers: [Bcrypt](https://en.wikipedia.org/wiki/Bcrypt) and [Argon2](https://en.wikipedia.org/wiki/Argon2) (Argon2i and Argon2id variants). +By default, Laravel uses the `bcrypt` hashing driver when hashing data. However, several other hashing drivers are supported, including [argon](https://en.wikipedia.org/wiki/Argon2) and [argon2id](https://en.wikipedia.org/wiki/Argon2). + +You may specify your application's hashing driver using the `HASH_DRIVER` environment variable. But, if you want to customize all of Laravel's hashing driver options, you should publish the complete `hashing` configuration file using the `config:publish` Artisan command: + +```shell +php artisan config:publish hashing +``` ## Basic Usage @@ -27,68 +34,89 @@ The default hashing driver for your application is configured in your applicatio You may hash a password by calling the `make` method on the `Hash` facade: - user()->fill([ - 'password' => Hash::make($request->newPassword) - ])->save(); - } + // Validate the new password length... + + $request->user()->fill([ + 'password' => Hash::make($request->newPassword) + ])->save(); + + return redirect('/profile'); } +} +``` #### Adjusting The Bcrypt Work Factor If you are using the Bcrypt algorithm, the `make` method allows you to manage the work factor of the algorithm using the `rounds` option; however, the default work factor managed by Laravel is acceptable for most applications: - $hashed = Hash::make('password', [ - 'rounds' => 12, - ]); +```php +$hashed = Hash::make('password', [ + 'rounds' => 12, +]); +``` #### Adjusting The Argon2 Work Factor If you are using the Argon2 algorithm, the `make` method allows you to manage the work factor of the algorithm using the `memory`, `time`, and `threads` options; however, the default values managed by Laravel are acceptable for most applications: - $hashed = Hash::make('password', [ - 'memory' => 1024, - 'time' => 2, - 'threads' => 2, - ]); +```php +$hashed = Hash::make('password', [ + 'memory' => 1024, + 'time' => 2, + 'threads' => 2, +]); +``` -> {tip} For more information on these options, please refer to the [official PHP documentation regarding Argon hashing](https://secure.php.net/manual/en/function.password-hash.php). +> [!NOTE] +> For more information on these options, please refer to the [official PHP documentation regarding Argon hashing](https://secure.php.net/manual/en/function.password-hash.php). -### Verifying That A Password Matches A Hash +### Verifying That a Password Matches a Hash The `check` method provided by the `Hash` facade allows you to verify that a given plain-text string corresponds to a given hash: - if (Hash::check('plain-text', $hashedPassword)) { - // The passwords match... - } +```php +if (Hash::check('plain-text', $hashedPassword)) { + // The passwords match... +} +``` -### Determining If A Password Needs To Be Rehashed +### Determining if a Password Needs to be Rehashed The `needsRehash` method provided by the `Hash` facade allows you to determine if the work factor used by the hasher has changed since the password was hashed. Some applications choose to perform this check during the application's authentication process: - if (Hash::needsRehash($hashed)) { - $hashed = Hash::make('plain-text'); - } +```php +if (Hash::needsRehash($hashed)) { + $hashed = Hash::make('plain-text'); +} +``` + + +## Hash Algorithm Verification + +To prevent hash algorithm manipulation, Laravel's `Hash::check` method will first verify the given hash was generated using the application's selected hashing algorithm. If the algorithms are different, a `RuntimeException` exception will be thrown. + +This is the expected behavior for most applications, where the hashing algorithm is not expected to change and different algorithms can be an indication of a malicious attack. However, if you need to support multiple hashing algorithms within your application, such as when migrating from one algorithm to another, you can disable hash algorithm verification by setting the `HASH_VERIFY` environment variable to `false`: + +```ini +HASH_VERIFY=false +``` diff --git a/helpers.md b/helpers.md index d26757a8f99..0011b02b641 100644 --- a/helpers.md +++ b/helpers.md @@ -2,6 +2,15 @@ - [Introduction](#introduction) - [Available Methods](#available-methods) +- [Other Utilities](#other-utilities) + - [Benchmarking](#benchmarking) + - [Dates](#dates) + - [Deferred Functions](#deferred-functions) + - [Lottery](#lottery) + - [Pipeline](#pipeline) + - [Sleep](#sleep) + - [Timebox](#timebox) + - [URI](#uri) ## Introduction @@ -13,12 +22,14 @@ Laravel includes a variety of global "helper" PHP functions. Many of these funct @@ -29,32 +40,55 @@ Laravel includes a variety of global "helper" PHP functions. Many of these funct [Arr::accessible](#method-array-accessible) [Arr::add](#method-array-add) +[Arr::array](#method-array-array) +[Arr::boolean](#method-array-boolean) [Arr::collapse](#method-array-collapse) [Arr::crossJoin](#method-array-crossjoin) [Arr::divide](#method-array-divide) [Arr::dot](#method-array-dot) +[Arr::every](#method-array-every) [Arr::except](#method-array-except) [Arr::exists](#method-array-exists) [Arr::first](#method-array-first) [Arr::flatten](#method-array-flatten) +[Arr::float](#method-array-float) [Arr::forget](#method-array-forget) +[Arr::from](#method-array-from) [Arr::get](#method-array-get) [Arr::has](#method-array-has) +[Arr::hasAll](#method-array-hasall) [Arr::hasAny](#method-array-hasany) +[Arr::integer](#method-array-integer) [Arr::isAssoc](#method-array-isassoc) [Arr::isList](#method-array-islist) +[Arr::join](#method-array-join) +[Arr::keyBy](#method-array-keyby) [Arr::last](#method-array-last) +[Arr::map](#method-array-map) +[Arr::mapSpread](#method-array-map-spread) +[Arr::mapWithKeys](#method-array-map-with-keys) [Arr::only](#method-array-only) +[Arr::partition](#method-array-partition) [Arr::pluck](#method-array-pluck) [Arr::prepend](#method-array-prepend) +[Arr::prependKeysWith](#method-array-prependkeyswith) [Arr::pull](#method-array-pull) +[Arr::push](#method-array-push) [Arr::query](#method-array-query) [Arr::random](#method-array-random) +[Arr::reject](#method-array-reject) +[Arr::select](#method-array-select) [Arr::set](#method-array-set) [Arr::shuffle](#method-array-shuffle) +[Arr::sole](#method-array-sole) +[Arr::some](#method-array-some) [Arr::sort](#method-array-sort) +[Arr::sortDesc](#method-array-sort-desc) [Arr::sortRecursive](#method-array-sort-recursive) +[Arr::string](#method-array-string) +[Arr::take](#method-array-take) [Arr::toCssClasses](#method-array-to-css-classes) +[Arr::toCssStyles](#method-array-to-css-styles) [Arr::undot](#method-array-undot) [Arr::where](#method-array-where) [Arr::whereNotNull](#method-array-where-not-null) @@ -62,10 +96,39 @@ Laravel includes a variety of global "helper" PHP functions. Many of these funct [data_fill](#method-data-fill) [data_get](#method-data-get) [data_set](#method-data-set) +[data_forget](#method-data-forget) [head](#method-head) [last](#method-last)
+ +### Numbers + +
+ +[Number::abbreviate](#method-number-abbreviate) +[Number::clamp](#method-number-clamp) +[Number::currency](#method-number-currency) +[Number::defaultCurrency](#method-default-currency) +[Number::defaultLocale](#method-default-locale) +[Number::fileSize](#method-number-file-size) +[Number::forHumans](#method-number-for-humans) +[Number::format](#method-number-format) +[Number::ordinal](#method-number-ordinal) +[Number::pairs](#method-number-pairs) +[Number::parseInt](#method-number-parse-int) +[Number::parseFloat](#method-number-parse-float) +[Number::percentage](#method-number-percentage) +[Number::spell](#method-number-spell) +[Number::spellOrdinal](#method-number-spell-ordinal) +[Number::trim](#method-number-trim) +[Number::useLocale](#method-number-use-locale) +[Number::withLocale](#method-number-with-locale) +[Number::useCurrency](#method-number-use-currency) +[Number::withCurrency](#method-number-with-currency) + +
+ ### Paths @@ -75,163 +138,13 @@ Laravel includes a variety of global "helper" PHP functions. Many of these funct [base_path](#method-base-path) [config_path](#method-config-path) [database_path](#method-database-path) -[mix](#method-mix) +[lang_path](#method-lang-path) [public_path](#method-public-path) [resource_path](#method-resource-path) [storage_path](#method-storage-path)
- -### Strings - -
- -[\__](#method-__) -[class_basename](#method-class-basename) -[e](#method-e) -[preg_replace_array](#method-preg-replace-array) -[Str::after](#method-str-after) -[Str::afterLast](#method-str-after-last) -[Str::ascii](#method-str-ascii) -[Str::before](#method-str-before) -[Str::beforeLast](#method-str-before-last) -[Str::between](#method-str-between) -[Str::camel](#method-camel-case) -[Str::contains](#method-str-contains) -[Str::containsAll](#method-str-contains-all) -[Str::endsWith](#method-ends-with) -[Str::excerpt](#method-excerpt) -[Str::finish](#method-str-finish) -[Str::headline](#method-str-headline) -[Str::is](#method-str-is) -[Str::isAscii](#method-str-is-ascii) -[Str::isUuid](#method-str-is-uuid) -[Str::kebab](#method-kebab-case) -[Str::length](#method-str-length) -[Str::limit](#method-str-limit) -[Str::lower](#method-str-lower) -[Str::markdown](#method-str-markdown) -[Str::mask](#method-str-mask) -[Str::orderedUuid](#method-str-ordered-uuid) -[Str::padBoth](#method-str-padboth) -[Str::padLeft](#method-str-padleft) -[Str::padRight](#method-str-padright) -[Str::plural](#method-str-plural) -[Str::pluralStudly](#method-str-plural-studly) -[Str::random](#method-str-random) -[Str::remove](#method-str-remove) -[Str::replace](#method-str-replace) -[Str::replaceArray](#method-str-replace-array) -[Str::replaceFirst](#method-str-replace-first) -[Str::replaceLast](#method-str-replace-last) -[Str::reverse](#method-str-reverse) -[Str::singular](#method-str-singular) -[Str::slug](#method-str-slug) -[Str::snake](#method-snake-case) -[Str::start](#method-str-start) -[Str::startsWith](#method-starts-with) -[Str::studly](#method-studly-case) -[Str::substr](#method-str-substr) -[Str::substrCount](#method-str-substrcount) -[Str::substrReplace](#method-str-substrreplace) -[Str::swap](#method-str-swap) -[Str::title](#method-title-case) -[Str::toHtmlString](#method-str-to-html-string) -[Str::ucfirst](#method-str-ucfirst) -[Str::upper](#method-str-upper) -[Str::uuid](#method-str-uuid) -[Str::wordCount](#method-str-word-count) -[Str::words](#method-str-words) -[str](#method-str) -[trans](#method-trans) -[trans_choice](#method-trans-choice) - -
- - -### Fluent Strings - -
- -[after](#method-fluent-str-after) -[afterLast](#method-fluent-str-after-last) -[append](#method-fluent-str-append) -[ascii](#method-fluent-str-ascii) -[basename](#method-fluent-str-basename) -[before](#method-fluent-str-before) -[beforeLast](#method-fluent-str-before-last) -[between](#method-fluent-str-between) -[camel](#method-fluent-str-camel) -[contains](#method-fluent-str-contains) -[containsAll](#method-fluent-str-contains-all) -[dirname](#method-fluent-str-dirname) -[endsWith](#method-fluent-str-ends-with) -[excerpt](#method-fluent-str-excerpt) -[exactly](#method-fluent-str-exactly) -[explode](#method-fluent-str-explode) -[finish](#method-fluent-str-finish) -[is](#method-fluent-str-is) -[isAscii](#method-fluent-str-is-ascii) -[isEmpty](#method-fluent-str-is-empty) -[isNotEmpty](#method-fluent-str-is-not-empty) -[isUuid](#method-fluent-str-is-uuid) -[kebab](#method-fluent-str-kebab) -[length](#method-fluent-str-length) -[limit](#method-fluent-str-limit) -[lower](#method-fluent-str-lower) -[ltrim](#method-fluent-str-ltrim) -[markdown](#method-fluent-str-markdown) -[mask](#method-fluent-str-mask) -[match](#method-fluent-str-match) -[matchAll](#method-fluent-str-match-all) -[padBoth](#method-fluent-str-padboth) -[padLeft](#method-fluent-str-padleft) -[padRight](#method-fluent-str-padright) -[pipe](#method-fluent-str-pipe) -[plural](#method-fluent-str-plural) -[prepend](#method-fluent-str-prepend) -[remove](#method-fluent-str-remove) -[replace](#method-fluent-str-replace) -[replaceArray](#method-fluent-str-replace-array) -[replaceFirst](#method-fluent-str-replace-first) -[replaceLast](#method-fluent-str-replace-last) -[replaceMatches](#method-fluent-str-replace-matches) -[rtrim](#method-fluent-str-rtrim) -[scan](#method-fluent-str-scan) -[singular](#method-fluent-str-singular) -[slug](#method-fluent-str-slug) -[snake](#method-fluent-str-snake) -[split](#method-fluent-str-split) -[start](#method-fluent-str-start) -[startsWith](#method-fluent-str-starts-with) -[studly](#method-fluent-str-studly) -[substr](#method-fluent-str-substr) -[substrReplace](#method-fluent-str-substrreplace) -[swap](#method-fluent-str-swap) -[tap](#method-fluent-str-tap) -[test](#method-fluent-str-test) -[title](#method-fluent-str-title) -[trim](#method-fluent-str-trim) -[ucfirst](#method-fluent-str-ucfirst) -[upper](#method-fluent-str-upper) -[when](#method-fluent-str-when) -[whenContains](#method-fluent-str-when-contains) -[whenContainsAll](#method-fluent-str-when-contains-all) -[whenEmpty](#method-fluent-str-when-empty) -[whenNotEmpty](#method-fluent-str-when-not-empty) -[whenStartsWith](#method-fluent-str-when-starts-with) -[whenEndsWith](#method-fluent-str-when-ends-with) -[whenExactly](#method-fluent-str-when-exactly) -[whenIs](#method-fluent-str-when-is) -[whenIsAscii](#method-fluent-str-when-is-ascii) -[whenIsUuid](#method-fluent-str-when-is-uuid) -[whenTest](#method-fluent-str-when-test) -[wordCount](#method-fluent-str-word-count) -[words](#method-fluent-str-words) - -
- ### URLs @@ -242,7 +155,9 @@ Laravel includes a variety of global "helper" PHP functions. Many of these funct [route](#method-route) [secure_asset](#method-secure-asset) [secure_url](#method-secure-url) +[to_action](#method-to-action) [to_route](#method-to-route) +[uri](#method-uri) [url](#method-url)
@@ -261,30 +176,39 @@ Laravel includes a variety of global "helper" PHP functions. Many of these funct [bcrypt](#method-bcrypt) [blank](#method-blank) [broadcast](#method-broadcast) +[broadcast_if](#method-broadcast-if) +[broadcast_unless](#method-broadcast-unless) [cache](#method-cache) [class_uses_recursive](#method-class-uses-recursive) [collect](#method-collect) [config](#method-config) +[context](#method-context) [cookie](#method-cookie) [csrf_field](#method-csrf-field) [csrf_token](#method-csrf-token) [decrypt](#method-decrypt) [dd](#method-dd) [dispatch](#method-dispatch) +[dispatch_sync](#method-dispatch-sync) [dump](#method-dump) [encrypt](#method-encrypt) [env](#method-env) [event](#method-event) +[fake](#method-fake) [filled](#method-filled) [info](#method-info) +[literal](#method-literal) [logger](#method-logger) [method_field](#method-method-field) [now](#method-now) [old](#method-old) +[once](#method-once) [optional](#method-optional) [policy](#method-policy) [redirect](#method-redirect) [report](#method-report) +[report_if](#method-report-if) +[report_unless](#method-report-unless) [request](#method-request) [rescue](#method-rescue) [resolve](#method-resolve) @@ -301,22 +225,10 @@ Laravel includes a variety of global "helper" PHP functions. Many of these funct [value](#method-value) [view](#method-view) [with](#method-with) +[when](#method-when)
- -## Method Listing - - - ## Arrays & Objects @@ -325,3293 +237,3469 @@ Laravel includes a variety of global "helper" PHP functions. Many of these funct The `Arr::accessible` method determines if the given value is array accessible: - use Illuminate\Support\Arr; - use Illuminate\Support\Collection; +```php +use Illuminate\Support\Arr; +use Illuminate\Support\Collection; - $isAccessible = Arr::accessible(['a' => 1, 'b' => 2]); +$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]); - // true +// true - $isAccessible = Arr::accessible(new Collection); +$isAccessible = Arr::accessible(new Collection); - // true +// true - $isAccessible = Arr::accessible('abc'); +$isAccessible = Arr::accessible('abc'); - // false +// false - $isAccessible = Arr::accessible(new stdClass); +$isAccessible = Arr::accessible(new stdClass); - // false +// false +``` #### `Arr::add()` {.collection-method} The `Arr::add` method adds a given key / value pair to an array if the given key doesn't already exist in the array or is set to `null`: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$array = Arr::add(['name' => 'Desk'], 'price', 100); + +// ['name' => 'Desk', 'price' => 100] + +$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100); + +// ['name' => 'Desk', 'price' => 100] +``` + + +#### `Arr::array()` {.collection-method} + +The `Arr::array` method retrieves a value from a deeply nested array using "dot" notation (just as [Arr::get()](#method-array-get) does), but throws an `InvalidArgumentException` if the requested value is not an `array`: + +``` +use Illuminate\Support\Arr; + +$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; + +$value = Arr::array($array, 'languages'); + +// ['PHP', 'Ruby'] + +$value = Arr::array($array, 'name'); + +// throws InvalidArgumentException +``` + + +#### `Arr::boolean()` {.collection-method} + +The `Arr::boolean` method retrieves a value from a deeply nested array using "dot" notation (just as [Arr::get()](#method-array-get) does), but throws an `InvalidArgumentException` if the requested value is not a `boolean`: + +``` +use Illuminate\Support\Arr; + +$array = ['name' => 'Joe', 'available' => true]; - $array = Arr::add(['name' => 'Desk'], 'price', 100); +$value = Arr::boolean($array, 'available'); - // ['name' => 'Desk', 'price' => 100] +// true - $array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100); +$value = Arr::boolean($array, 'name'); - // ['name' => 'Desk', 'price' => 100] +// throws InvalidArgumentException +``` #### `Arr::collapse()` {.collection-method} -The `Arr::collapse` method collapses an array of arrays into a single array: +The `Arr::collapse` method collapses an array of arrays or collections into a single array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); +$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); - // [1, 2, 3, 4, 5, 6, 7, 8, 9] +// [1, 2, 3, 4, 5, 6, 7, 8, 9] +``` #### `Arr::crossJoin()` {.collection-method} The `Arr::crossJoin` method cross joins the given arrays, returning a Cartesian product with all possible permutations: - use Illuminate\Support\Arr; - - $matrix = Arr::crossJoin([1, 2], ['a', 'b']); - - /* - [ - [1, 'a'], - [1, 'b'], - [2, 'a'], - [2, 'b'], - ] - */ - - $matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']); - - /* - [ - [1, 'a', 'I'], - [1, 'a', 'II'], - [1, 'b', 'I'], - [1, 'b', 'II'], - [2, 'a', 'I'], - [2, 'a', 'II'], - [2, 'b', 'I'], - [2, 'b', 'II'], - ] - */ +```php +use Illuminate\Support\Arr; + +$matrix = Arr::crossJoin([1, 2], ['a', 'b']); + +/* + [ + [1, 'a'], + [1, 'b'], + [2, 'a'], + [2, 'b'], + ] +*/ + +$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']); + +/* + [ + [1, 'a', 'I'], + [1, 'a', 'II'], + [1, 'b', 'I'], + [1, 'b', 'II'], + [2, 'a', 'I'], + [2, 'a', 'II'], + [2, 'b', 'I'], + [2, 'b', 'II'], + ] +*/ +``` #### `Arr::divide()` {.collection-method} The `Arr::divide` method returns two arrays: one containing the keys and the other containing the values of the given array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - [$keys, $values] = Arr::divide(['name' => 'Desk']); +[$keys, $values] = Arr::divide(['name' => 'Desk']); - // $keys: ['name'] +// $keys: ['name'] - // $values: ['Desk'] +// $values: ['Desk'] +``` #### `Arr::dot()` {.collection-method} The `Arr::dot` method flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$array = ['products' => ['desk' => ['price' => 100]]]; + +$flattened = Arr::dot($array); + +// ['products.desk.price' => 100] +``` + + +#### `Arr::every()` {.collection-method} + +The `Arr::every` method ensures that all values in the array pass a given truth test: + +```php +use Illuminate\Support\Arr; + +$array = [1, 2, 3]; + +Arr::every($array, fn ($i) => $i > 0); - $array = ['products' => ['desk' => ['price' => 100]]]; +// true - $flattened = Arr::dot($array); +Arr::every($array, fn ($i) => $i > 2); - // ['products.desk.price' => 100] +// false +``` #### `Arr::except()` {.collection-method} The `Arr::except` method removes the given key / value pairs from an array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = ['name' => 'Desk', 'price' => 100]; +$array = ['name' => 'Desk', 'price' => 100]; - $filtered = Arr::except($array, ['price']); +$filtered = Arr::except($array, ['price']); - // ['name' => 'Desk'] +// ['name' => 'Desk'] +``` #### `Arr::exists()` {.collection-method} The `Arr::exists` method checks that the given key exists in the provided array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = ['name' => 'John Doe', 'age' => 17]; +$array = ['name' => 'John Doe', 'age' => 17]; - $exists = Arr::exists($array, 'name'); +$exists = Arr::exists($array, 'name'); - // true +// true - $exists = Arr::exists($array, 'salary'); +$exists = Arr::exists($array, 'salary'); - // false +// false +``` #### `Arr::first()` {.collection-method} The `Arr::first` method returns the first element of an array passing a given truth test: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = [100, 200, 300]; +$array = [100, 200, 300]; - $first = Arr::first($array, function ($value, $key) { - return $value >= 150; - }); +$first = Arr::first($array, function (int $value, int $key) { + return $value >= 150; +}); - // 200 +// 200 +``` A default value may also be passed as the third parameter to the method. This value will be returned if no value passes the truth test: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $first = Arr::first($array, $callback, $default); +$first = Arr::first($array, $callback, $default); +``` #### `Arr::flatten()` {.collection-method} The `Arr::flatten` method flattens a multi-dimensional array into a single level array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; + +$flattened = Arr::flatten($array); + +// ['Joe', 'PHP', 'Ruby'] +``` + + +#### `Arr::float()` {.collection-method} + +The `Arr::float` method retrieves a value from a deeply nested array using "dot" notation (just as [Arr::get()](#method-array-get) does), but throws an `InvalidArgumentException` if the requested value is not a `float`: + +``` +use Illuminate\Support\Arr; + +$array = ['name' => 'Joe', 'balance' => 123.45]; - $array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; +$value = Arr::float($array, 'balance'); - $flattened = Arr::flatten($array); +// 123.45 - // ['Joe', 'PHP', 'Ruby'] +$value = Arr::float($array, 'name'); + +// throws InvalidArgumentException +``` #### `Arr::forget()` {.collection-method} -The `Arr::forget` method removes a given key / value pair from a deeply nested array using "dot" notation: +The `Arr::forget` method removes a given key / value pairs from a deeply nested array using "dot" notation: + +```php +use Illuminate\Support\Arr; + +$array = ['products' => ['desk' => ['price' => 100]]]; + +Arr::forget($array, 'products.desk'); + +// ['products' => []] +``` + + +#### `Arr::from()` {.collection-method} + +The `Arr::from` method converts various input types into a plain PHP array. It supports a range of input types, including arrays, objects, and several common Laravel interfaces, such as `Arrayable`, `Enumerable`, `Jsonable`, and `JsonSerializable`. Additionally, it handles `Traversable` and `WeakMap` instances: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = ['products' => ['desk' => ['price' => 100]]]; +Arr::from((object) ['foo' => 'bar']); // ['foo' => 'bar'] - Arr::forget($array, 'products.desk'); +class TestJsonableObject implements Jsonable +{ + public function toJson($options = 0) + { + return json_encode(['foo' => 'bar']); + } +} - // ['products' => []] +Arr::from(new TestJsonableObject); // ['foo' => 'bar'] +``` #### `Arr::get()` {.collection-method} The `Arr::get` method retrieves a value from a deeply nested array using "dot" notation: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = ['products' => ['desk' => ['price' => 100]]]; +$array = ['products' => ['desk' => ['price' => 100]]]; - $price = Arr::get($array, 'products.desk.price'); +$price = Arr::get($array, 'products.desk.price'); - // 100 +// 100 +``` The `Arr::get` method also accepts a default value, which will be returned if the specified key is not present in the array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $discount = Arr::get($array, 'products.desk.discount', 0); +$discount = Arr::get($array, 'products.desk.discount', 0); - // 0 +// 0 +``` #### `Arr::has()` {.collection-method} The `Arr::has` method checks whether a given item or items exists in an array using "dot" notation: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$array = ['product' => ['name' => 'Desk', 'price' => 100]]; + +$contains = Arr::has($array, 'product.name'); + +// true + +$contains = Arr::has($array, ['product.price', 'product.discount']); - $array = ['product' => ['name' => 'Desk', 'price' => 100]]; +// false +``` + + +#### `Arr::hasAll()` {.collection-method} - $contains = Arr::has($array, 'product.name'); +The `Arr::hasAll` method determines if all of the specified keys exist in the given array using "dot" notation: - // true +```php +use Illuminate\Support\Arr; - $contains = Arr::has($array, ['product.price', 'product.discount']); +$array = ['name' => 'Taylor', 'language' => 'PHP']; - // false +Arr::hasAll($array, ['name']); // true +Arr::hasAll($array, ['name', 'language']); // true +Arr::hasAll($array, ['name', 'IDE']); // false +``` #### `Arr::hasAny()` {.collection-method} The `Arr::hasAny` method checks whether any item in a given set exists in an array using "dot" notation: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$array = ['product' => ['name' => 'Desk', 'price' => 100]]; + +$contains = Arr::hasAny($array, 'product.name'); + +// true + +$contains = Arr::hasAny($array, ['product.name', 'product.discount']); + +// true + +$contains = Arr::hasAny($array, ['category', 'product.discount']); + +// false +``` + + +#### `Arr::integer()` {.collection-method} - $array = ['product' => ['name' => 'Desk', 'price' => 100]]; +The `Arr::integer` method retrieves a value from a deeply nested array using "dot" notation (just as [Arr::get()](#method-array-get) does), but throws an `InvalidArgumentException` if the requested value is not an `int`: - $contains = Arr::hasAny($array, 'product.name'); +``` +use Illuminate\Support\Arr; - // true +$array = ['name' => 'Joe', 'age' => 42]; - $contains = Arr::hasAny($array, ['product.name', 'product.discount']); +$value = Arr::integer($array, 'age'); - // true +// 42 - $contains = Arr::hasAny($array, ['category', 'product.discount']); +$value = Arr::integer($array, 'name'); - // false +// throws InvalidArgumentException +``` #### `Arr::isAssoc()` {.collection-method} The `Arr::isAssoc` method returns `true` if the given array is an associative array. An array is considered "associative" if it doesn't have sequential numerical keys beginning with zero: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]); +$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]); - // true +// true - $isAssoc = Arr::isAssoc([1, 2, 3]); +$isAssoc = Arr::isAssoc([1, 2, 3]); - // false +// false +``` #### `Arr::isList()` {.collection-method} The `Arr::isList` method returns `true` if the given array's keys are sequential integers beginning from zero: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$isList = Arr::isList(['foo', 'bar', 'baz']); - $isAssoc = Arr::isList(['foo', 'bar', 'baz']); +// true - // true +$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]); - $isAssoc = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]); +// false +``` + + +#### `Arr::join()` {.collection-method} + +The `Arr::join` method joins array elements with a string. Using this method's third argument, you may also specify the joining string for the final element of the array: + +```php +use Illuminate\Support\Arr; + +$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire']; + +$joined = Arr::join($array, ', '); + +// Tailwind, Alpine, Laravel, Livewire + +$joined = Arr::join($array, ', ', ', and '); + +// Tailwind, Alpine, Laravel, and Livewire +``` + + +#### `Arr::keyBy()` {.collection-method} + +The `Arr::keyBy` method keys the array by the given key. If multiple items have the same key, only the last one will appear in the new array: + +```php +use Illuminate\Support\Arr; + +$array = [ + ['product_id' => 'prod-100', 'name' => 'Desk'], + ['product_id' => 'prod-200', 'name' => 'Chair'], +]; - // false +$keyed = Arr::keyBy($array, 'product_id'); + +/* + [ + 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], + 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], + ] +*/ +``` #### `Arr::last()` {.collection-method} The `Arr::last` method returns the last element of an array passing a given truth test: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = [100, 200, 300, 110]; +$array = [100, 200, 300, 110]; - $last = Arr::last($array, function ($value, $key) { - return $value >= 150; - }); +$last = Arr::last($array, function (int $value, int $key) { + return $value >= 150; +}); - // 300 +// 300 +``` A default value may be passed as the third argument to the method. This value will be returned if no value passes the truth test: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$last = Arr::last($array, $callback, $default); +``` + + +#### `Arr::map()` {.collection-method} + +The `Arr::map` method iterates through the array and passes each value and key to the given callback. The array value is replaced by the value returned by the callback: + +```php +use Illuminate\Support\Arr; + +$array = ['first' => 'james', 'last' => 'kirk']; + +$mapped = Arr::map($array, function (string $value, string $key) { + return ucfirst($value); +}); + +// ['first' => 'James', 'last' => 'Kirk'] +``` + + +#### `Arr::mapSpread()` {.collection-method} + +The `Arr::mapSpread` method iterates over the array, passing each nested item value into the given closure. The closure is free to modify the item and return it, thus forming a new array of modified items: + +```php +use Illuminate\Support\Arr; + +$array = [ + [0, 1], + [2, 3], + [4, 5], + [6, 7], + [8, 9], +]; + +$mapped = Arr::mapSpread($array, function (int $even, int $odd) { + return $even + $odd; +}); + +/* + [1, 5, 9, 13, 17] +*/ +``` + + +#### `Arr::mapWithKeys()` {.collection-method} - $last = Arr::last($array, $callback, $default); +The `Arr::mapWithKeys` method iterates through the array and passes each value to the given callback. The callback should return an associative array containing a single key / value pair: + +```php +use Illuminate\Support\Arr; + +$array = [ + [ + 'name' => 'John', + 'department' => 'Sales', + 'email' => 'john@example.com', + ], + [ + 'name' => 'Jane', + 'department' => 'Marketing', + 'email' => 'jane@example.com', + ] +]; + +$mapped = Arr::mapWithKeys($array, function (array $item, int $key) { + return [$item['email'] => $item['name']]; +}); + +/* + [ + 'john@example.com' => 'John', + 'jane@example.com' => 'Jane', + ] +*/ +``` #### `Arr::only()` {.collection-method} The `Arr::only` method returns only the specified key / value pairs from the given array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10]; + +$slice = Arr::only($array, ['name', 'price']); + +// ['name' => 'Desk', 'price' => 100] +``` + + +#### `Arr::partition()` {.collection-method} + +The `Arr::partition` method may be combined with PHP array destructuring to separate elements that pass a given truth test from those that do not: - $array = ['name' => 'Desk', 'price' => 100, 'orders' => 10]; +```php + 'Desk', 'price' => 100] +// [1, 2] + +dump($equalOrAboveThree); + +// [3, 4, 5, 6] +``` #### `Arr::pluck()` {.collection-method} The `Arr::pluck` method retrieves all of the values for a given key from an array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = [ - ['developer' => ['id' => 1, 'name' => 'Taylor']], - ['developer' => ['id' => 2, 'name' => 'Abigail']], - ]; +$array = [ + ['developer' => ['id' => 1, 'name' => 'Taylor']], + ['developer' => ['id' => 2, 'name' => 'Abigail']], +]; - $names = Arr::pluck($array, 'developer.name'); +$names = Arr::pluck($array, 'developer.name'); - // ['Taylor', 'Abigail'] +// ['Taylor', 'Abigail'] +``` You may also specify how you wish the resulting list to be keyed: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $names = Arr::pluck($array, 'developer.name', 'developer.id'); +$names = Arr::pluck($array, 'developer.name', 'developer.id'); - // [1 => 'Taylor', 2 => 'Abigail'] +// [1 => 'Taylor', 2 => 'Abigail'] +``` #### `Arr::prepend()` {.collection-method} The `Arr::prepend` method will push an item onto the beginning of an array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = ['one', 'two', 'three', 'four']; +$array = ['one', 'two', 'three', 'four']; - $array = Arr::prepend($array, 'zero'); +$array = Arr::prepend($array, 'zero'); - // ['zero', 'one', 'two', 'three', 'four'] +// ['zero', 'one', 'two', 'three', 'four'] +``` If needed, you may specify the key that should be used for the value: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$array = ['price' => 100]; + +$array = Arr::prepend($array, 'Desk', 'name'); - $array = ['price' => 100]; +// ['name' => 'Desk', 'price' => 100] +``` + + +#### `Arr::prependKeysWith()` {.collection-method} + +The `Arr::prependKeysWith` prepends all key names of an associative array with the given prefix: + +```php +use Illuminate\Support\Arr; + +$array = [ + 'name' => 'Desk', + 'price' => 100, +]; - $array = Arr::prepend($array, 'Desk', 'name'); +$keyed = Arr::prependKeysWith($array, 'product.'); - // ['name' => 'Desk', 'price' => 100] +/* + [ + 'product.name' => 'Desk', + 'product.price' => 100, + ] +*/ +``` #### `Arr::pull()` {.collection-method} The `Arr::pull` method returns and removes a key / value pair from an array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = ['name' => 'Desk', 'price' => 100]; +$array = ['name' => 'Desk', 'price' => 100]; - $name = Arr::pull($array, 'name'); +$name = Arr::pull($array, 'name'); - // $name: Desk +// $name: Desk - // $array: ['price' => 100] +// $array: ['price' => 100] +``` A default value may be passed as the third argument to the method. This value will be returned if the key doesn't exist: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; + +$value = Arr::pull($array, $key, $default); +``` + + +#### `Arr::push()` {.collection-method} + +The `Arr::push` method pushes an item into an array using "dot" notation. If an array does not exist at the given key, it will be created: + +```php +use Illuminate\Support\Arr; + +$array = []; + +Arr::push($array, 'office.furniture', 'Desk'); - $value = Arr::pull($array, $key, $default); +// $array: ['office' => ['furniture' => ['Desk']]] +``` #### `Arr::query()` {.collection-method} The `Arr::query` method converts the array into a query string: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = [ - 'name' => 'Taylor', - 'order' => [ - 'column' => 'created_at', - 'direction' => 'desc' - ] - ]; +$array = [ + 'name' => 'Taylor', + 'order' => [ + 'column' => 'created_at', + 'direction' => 'desc' + ] +]; - Arr::query($array); +Arr::query($array); - // name=Taylor&order[column]=created_at&order[direction]=desc +// name=Taylor&order[column]=created_at&order[direction]=desc +``` #### `Arr::random()` {.collection-method} The `Arr::random` method returns a random value from an array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = [1, 2, 3, 4, 5]; +$array = [1, 2, 3, 4, 5]; - $random = Arr::random($array); +$random = Arr::random($array); - // 4 - (retrieved randomly) +// 4 - (retrieved randomly) +``` You may also specify the number of items to return as an optional second argument. Note that providing this argument will return an array even if only one item is desired: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $items = Arr::random($array, 2); +$items = Arr::random($array, 2); - // [2, 5] - (retrieved randomly) +// [2, 5] - (retrieved randomly) +``` - -#### `Arr::set()` {.collection-method} + +#### `Arr::reject()` {.collection-method} -The `Arr::set` method sets a value within a deeply nested array using "dot" notation: +The `Arr::reject` method removes items from an array using the given closure: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = ['products' => ['desk' => ['price' => 100]]]; +$array = [100, '200', 300, '400', 500]; - Arr::set($array, 'products.desk.price', 200); +$filtered = Arr::reject($array, function (string|int $value, int $key) { + return is_string($value); +}); - // ['products' => ['desk' => ['price' => 200]]] +// [0 => 100, 2 => 300, 4 => 500] +``` - -#### `Arr::shuffle()` {.collection-method} + +#### `Arr::select()` {.collection-method} -The `Arr::shuffle` method randomly shuffles the items in the array: +The `Arr::select` method selects an array of values from an array: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = Arr::shuffle([1, 2, 3, 4, 5]); +$array = [ + ['id' => 1, 'name' => 'Desk', 'price' => 200], + ['id' => 2, 'name' => 'Table', 'price' => 150], + ['id' => 3, 'name' => 'Chair', 'price' => 300], +]; - // [3, 2, 5, 1, 4] - (generated randomly) +Arr::select($array, ['name', 'price']); - -#### `Arr::sort()` {.collection-method} +// [['name' => 'Desk', 'price' => 200], ['name' => 'Table', 'price' => 150], ['name' => 'Chair', 'price' => 300]] +``` -The `Arr::sort` method sorts an array by its values: + +#### `Arr::set()` {.collection-method} - use Illuminate\Support\Arr; +The `Arr::set` method sets a value within a deeply nested array using "dot" notation: - $array = ['Desk', 'Table', 'Chair']; +```php +use Illuminate\Support\Arr; - $sorted = Arr::sort($array); +$array = ['products' => ['desk' => ['price' => 100]]]; - // ['Chair', 'Desk', 'Table'] +Arr::set($array, 'products.desk.price', 200); -You may also sort the array by the results of a given closure: +// ['products' => ['desk' => ['price' => 200]]] +``` - use Illuminate\Support\Arr; + +#### `Arr::shuffle()` {.collection-method} - $array = [ - ['name' => 'Desk'], - ['name' => 'Table'], - ['name' => 'Chair'], - ]; +The `Arr::shuffle` method randomly shuffles the items in the array: - $sorted = array_values(Arr::sort($array, function ($value) { - return $value['name']; - })); +```php +use Illuminate\Support\Arr; - /* - [ - ['name' => 'Chair'], - ['name' => 'Desk'], - ['name' => 'Table'], - ] - */ +$array = Arr::shuffle([1, 2, 3, 4, 5]); - -#### `Arr::sortRecursive()` {.collection-method} +// [3, 2, 5, 1, 4] - (generated randomly) +``` -The `Arr::sortRecursive` method recursively sorts an array using the `sort` function for numerically indexed sub-arrays and the `ksort` function for associative sub-arrays: + +#### `Arr::sole()` {.collection-method} - use Illuminate\Support\Arr; +The `Arr::sole` method retrieves a single value from an array using the given closure. If more than one value within the array matches the given truth test, an `Illuminate\Support\MultipleItemsFoundException` exception will be thrown. If no values match the truth test, an `Illuminate\Support\ItemNotFoundException` exception will be thrown: - $array = [ - ['Roman', 'Taylor', 'Li'], - ['PHP', 'Ruby', 'JavaScript'], - ['one' => 1, 'two' => 2, 'three' => 3], - ]; +```php +use Illuminate\Support\Arr; - $sorted = Arr::sortRecursive($array); +$array = ['Desk', 'Table', 'Chair']; - /* - [ - ['JavaScript', 'PHP', 'Ruby'], - ['one' => 1, 'three' => 3, 'two' => 2], - ['Li', 'Roman', 'Taylor'], - ] - */ +$value = Arr::sole($array, fn (string $value) => $value === 'Desk'); - -#### `Arr::toCssClasses()` {.collection-method} +// 'Desk' +``` -The `Arr::toCssClasses` conditionally compiles a CSS class string. The method accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list: + +#### `Arr::some()` {.collection-method} - use Illuminate\Support\Arr; +The `Arr::some` method ensures that at least one of the values in the array passes a given truth test: - $isActive = false; - $hasError = true; +```php +use Illuminate\Support\Arr; - $array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError]; +$array = [1, 2, 3]; - $classes = Arr::toCssClasses($array); +Arr::some($array, fn ($i) => $i > 2); - /* - 'p-4 bg-red' - */ +// true +``` -This method powers Laravel's functionality allowing [merging classes with a Blade component's attribute bag](/docs/{{version}}/blade#conditionally-merge-classes) as well as the `@class` [Blade directive](/docs/{{version}}/blade#conditional-classes). + +#### `Arr::sort()` {.collection-method} - -#### `Arr::undot()` {.collection-method} - -The `Arr::undot` method expands a single-dimensional array that uses "dot" notation into a multi-dimensional array: +The `Arr::sort` method sorts an array by its values: - use Illuminate\Support\Arr; +```php +use Illuminate\Support\Arr; - $array = [ - 'user.name' => 'Kevin Malone', - 'user.occupation' => 'Accountant', - ]; +$array = ['Desk', 'Table', 'Chair']; - $array = Arr::undot($array); +$sorted = Arr::sort($array); - // ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']] +// ['Chair', 'Desk', 'Table'] +``` - -#### `Arr::where()` {.collection-method} +You may also sort the array by the results of a given closure: -The `Arr::where` method filters an array using the given closure: +```php +use Illuminate\Support\Arr; - use Illuminate\Support\Arr; +$array = [ + ['name' => 'Desk'], + ['name' => 'Table'], + ['name' => 'Chair'], +]; - $array = [100, '200', 300, '400', 500]; +$sorted = array_values(Arr::sort($array, function (array $value) { + return $value['name']; +})); - $filtered = Arr::where($array, function ($value, $key) { - return is_string($value); - }); +/* + [ + ['name' => 'Chair'], + ['name' => 'Desk'], + ['name' => 'Table'], + ] +*/ +``` - // [1 => '200', 3 => '400'] + +#### `Arr::sortDesc()` {.collection-method} - -#### `Arr::whereNotNull()` {.collection-method} +The `Arr::sortDesc` method sorts an array in descending order by its values: -The `Arr::whereNotNull` method removes all `null` values from the given array: +```php +use Illuminate\Support\Arr; - use Illuminate\Support\Arr; +$array = ['Desk', 'Table', 'Chair']; - $array = [0, null]; +$sorted = Arr::sortDesc($array); - $filtered = Arr::whereNotNull($array); +// ['Table', 'Desk', 'Chair'] +``` - // [0 => 0] +You may also sort the array by the results of a given closure: - -#### `Arr::wrap()` {.collection-method} +```php +use Illuminate\Support\Arr; -The `Arr::wrap` method wraps the given value in an array. If the given value is already an array it will be returned without modification: +$array = [ + ['name' => 'Desk'], + ['name' => 'Table'], + ['name' => 'Chair'], +]; - use Illuminate\Support\Arr; +$sorted = array_values(Arr::sortDesc($array, function (array $value) { + return $value['name']; +})); - $string = 'Laravel'; +/* + [ + ['name' => 'Table'], + ['name' => 'Desk'], + ['name' => 'Chair'], + ] +*/ +``` - $array = Arr::wrap($string); + +#### `Arr::sortRecursive()` {.collection-method} - // ['Laravel'] +The `Arr::sortRecursive` method recursively sorts an array using the `sort` function for numerically indexed sub-arrays and the `ksort` function for associative sub-arrays: -If the given value is `null`, an empty array will be returned: +```php +use Illuminate\Support\Arr; + +$array = [ + ['Roman', 'Taylor', 'Li'], + ['PHP', 'Ruby', 'JavaScript'], + ['one' => 1, 'two' => 2, 'three' => 3], +]; + +$sorted = Arr::sortRecursive($array); + +/* + [ + ['JavaScript', 'PHP', 'Ruby'], + ['one' => 1, 'three' => 3, 'two' => 2], + ['Li', 'Roman', 'Taylor'], + ] +*/ +``` - use Illuminate\Support\Arr; +If you would like the results sorted in descending order, you may use the `Arr::sortRecursiveDesc` method. - $array = Arr::wrap(null); +```php +$sorted = Arr::sortRecursiveDesc($array); +``` - // [] + +#### `Arr::string()` {.collection-method} - -#### `data_fill()` {.collection-method} +The `Arr::string` method retrieves a value from a deeply nested array using "dot" notation (just as [Arr::get()](#method-array-get) does), but throws an `InvalidArgumentException` if the requested value is not a `string`: -The `data_fill` function sets a missing value within a nested array or object using "dot" notation: +``` +use Illuminate\Support\Arr; - $data = ['products' => ['desk' => ['price' => 100]]]; +$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; - data_fill($data, 'products.desk.price', 200); +$value = Arr::string($array, 'name'); - // ['products' => ['desk' => ['price' => 100]]] +// Joe - data_fill($data, 'products.desk.discount', 10); +$value = Arr::string($array, 'languages'); - // ['products' => ['desk' => ['price' => 100, 'discount' => 10]]] +// throws InvalidArgumentException +``` -This function also accepts asterisks as wildcards and will fill the target accordingly: + +#### `Arr::take()` {.collection-method} - $data = [ - 'products' => [ - ['name' => 'Desk 1', 'price' => 100], - ['name' => 'Desk 2'], - ], - ]; +The `Arr::take` method returns a new array with the specified number of items: - data_fill($data, 'products.*.price', 200); +```php +use Illuminate\Support\Arr; - /* - [ - 'products' => [ - ['name' => 'Desk 1', 'price' => 100], - ['name' => 'Desk 2', 'price' => 200], - ], - ] - */ +$array = [0, 1, 2, 3, 4, 5]; - -#### `data_get()` {.collection-method} +$chunk = Arr::take($array, 3); -The `data_get` function retrieves a value from a nested array or object using "dot" notation: +// [0, 1, 2] +``` - $data = ['products' => ['desk' => ['price' => 100]]]; +You may also pass a negative integer to take the specified number of items from the end of the array: - $price = data_get($data, 'products.desk.price'); +```php +$array = [0, 1, 2, 3, 4, 5]; - // 100 +$chunk = Arr::take($array, -2); -The `data_get` function also accepts a default value, which will be returned if the specified key is not found: +// [4, 5] +``` - $discount = data_get($data, 'products.desk.discount', 0); + +#### `Arr::toCssClasses()` {.collection-method} - // 0 +The `Arr::toCssClasses` method conditionally compiles a CSS class string. The method accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list: -The function also accepts wildcards using asterisks, which may target any key of the array or object: +```php +use Illuminate\Support\Arr; - $data = [ - 'product-one' => ['name' => 'Desk 1', 'price' => 100], - 'product-two' => ['name' => 'Desk 2', 'price' => 150], - ]; +$isActive = false; +$hasError = true; - data_get($data, '*.name'); +$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError]; - // ['Desk 1', 'Desk 2']; +$classes = Arr::toCssClasses($array); - -#### `data_set()` {.collection-method} +/* + 'p-4 bg-red' +*/ +``` -The `data_set` function sets a value within a nested array or object using "dot" notation: + +#### `Arr::toCssStyles()` {.collection-method} - $data = ['products' => ['desk' => ['price' => 100]]]; +The `Arr::toCssStyles` conditionally compiles a CSS style string. The method accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list: - data_set($data, 'products.desk.price', 200); +```php +use Illuminate\Support\Arr; - // ['products' => ['desk' => ['price' => 200]]] +$hasColor = true; -This function also accepts wildcards using asterisks and will set values on the target accordingly: +$array = ['background-color: blue', 'color: blue' => $hasColor]; - $data = [ - 'products' => [ - ['name' => 'Desk 1', 'price' => 100], - ['name' => 'Desk 2', 'price' => 150], - ], - ]; +$classes = Arr::toCssStyles($array); - data_set($data, 'products.*.price', 200); +/* + 'background-color: blue; color: blue;' +*/ +``` - /* - [ - 'products' => [ - ['name' => 'Desk 1', 'price' => 200], - ['name' => 'Desk 2', 'price' => 200], - ], - ] - */ +This method powers Laravel's functionality allowing [merging classes with a Blade component's attribute bag](/docs/{{version}}/blade#conditionally-merge-classes) as well as the `@class` [Blade directive](/docs/{{version}}/blade#conditional-classes). -By default, any existing values are overwritten. If you wish to only set a value if it doesn't exist, you may pass `false` as the fourth argument to the function: + +#### `Arr::undot()` {.collection-method} - $data = ['products' => ['desk' => ['price' => 100]]]; +The `Arr::undot` method expands a single-dimensional array that uses "dot" notation into a multi-dimensional array: - data_set($data, 'products.desk.price', 200, $overwrite = false); +```php +use Illuminate\Support\Arr; - // ['products' => ['desk' => ['price' => 100]]] +$array = [ + 'user.name' => 'Kevin Malone', + 'user.occupation' => 'Accountant', +]; - -#### `head()` {.collection-method} +$array = Arr::undot($array); -The `head` function returns the first element in the given array: +// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']] +``` - $array = [100, 200, 300]; + +#### `Arr::where()` {.collection-method} - $first = head($array); +The `Arr::where` method filters an array using the given closure: - // 100 +```php +use Illuminate\Support\Arr; - -#### `last()` {.collection-method} +$array = [100, '200', 300, '400', 500]; -The `last` function returns the last element in the given array: +$filtered = Arr::where($array, function (string|int $value, int $key) { + return is_string($value); +}); - $array = [100, 200, 300]; +// [1 => '200', 3 => '400'] +``` - $last = last($array); + +#### `Arr::whereNotNull()` {.collection-method} - // 300 +The `Arr::whereNotNull` method removes all `null` values from the given array: - -## Paths +```php +use Illuminate\Support\Arr; - -#### `app_path()` {.collection-method} +$array = [0, null]; -The `app_path` function returns the fully qualified path to your application's `app` directory. You may also use the `app_path` function to generate a fully qualified path to a file relative to the application directory: +$filtered = Arr::whereNotNull($array); - $path = app_path(); +// [0 => 0] +``` - $path = app_path('Http/Controllers/Controller.php'); + +#### `Arr::wrap()` {.collection-method} - -#### `base_path()` {.collection-method} +The `Arr::wrap` method wraps the given value in an array. If the given value is already an array it will be returned without modification: -The `base_path` function returns the fully qualified path to your application's root directory. You may also use the `base_path` function to generate a fully qualified path to a given file relative to the project root directory: +```php +use Illuminate\Support\Arr; - $path = base_path(); +$string = 'Laravel'; - $path = base_path('vendor/bin'); +$array = Arr::wrap($string); - -#### `config_path()` {.collection-method} +// ['Laravel'] +``` -The `config_path` function returns the fully qualified path to your application's `config` directory. You may also use the `config_path` function to generate a fully qualified path to a given file within the application's configuration directory: +If the given value is `null`, an empty array will be returned: - $path = config_path(); +```php +use Illuminate\Support\Arr; - $path = config_path('app.php'); +$array = Arr::wrap(null); - -#### `database_path()` {.collection-method} +// [] +``` -The `database_path` function returns the fully qualified path to your application's `database` directory. You may also use the `database_path` function to generate a fully qualified path to a given file within the database directory: + +#### `data_fill()` {.collection-method} - $path = database_path(); +The `data_fill` function sets a missing value within a nested array or object using "dot" notation: - $path = database_path('factories/UserFactory.php'); +```php +$data = ['products' => ['desk' => ['price' => 100]]]; - -#### `mix()` {.collection-method} +data_fill($data, 'products.desk.price', 200); -The `mix` function returns the path to a [versioned Mix file](/docs/{{version}}/mix): +// ['products' => ['desk' => ['price' => 100]]] - $path = mix('css/app.css'); +data_fill($data, 'products.desk.discount', 10); - -#### `public_path()` {.collection-method} +// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]] +``` -The `public_path` function returns the fully qualified path to your application's `public` directory. You may also use the `public_path` function to generate a fully qualified path to a given file within the public directory: +This function also accepts asterisks as wildcards and will fill the target accordingly: - $path = public_path(); +```php +$data = [ + 'products' => [ + ['name' => 'Desk 1', 'price' => 100], + ['name' => 'Desk 2'], + ], +]; - $path = public_path('css/app.css'); +data_fill($data, 'products.*.price', 200); - -#### `resource_path()` {.collection-method} +/* + [ + 'products' => [ + ['name' => 'Desk 1', 'price' => 100], + ['name' => 'Desk 2', 'price' => 200], + ], + ] +*/ +``` -The `resource_path` function returns the fully qualified path to your application's `resources` directory. You may also use the `resource_path` function to generate a fully qualified path to a given file within the resources directory: + +#### `data_get()` {.collection-method} - $path = resource_path(); +The `data_get` function retrieves a value from a nested array or object using "dot" notation: - $path = resource_path('sass/app.scss'); +```php +$data = ['products' => ['desk' => ['price' => 100]]]; - -#### `storage_path()` {.collection-method} +$price = data_get($data, 'products.desk.price'); -The `storage_path` function returns the fully qualified path to your application's `storage` directory. You may also use the `storage_path` function to generate a fully qualified path to a given file within the storage directory: +// 100 +``` - $path = storage_path(); +The `data_get` function also accepts a default value, which will be returned if the specified key is not found: - $path = storage_path('app/file.txt'); +```php +$discount = data_get($data, 'products.desk.discount', 0); - -## Strings +// 0 +``` - -#### `__()` {.collection-method} +The function also accepts wildcards using asterisks, which may target any key of the array or object: -The `__` function translates the given translation string or translation key using your [localization files](/docs/{{version}}/localization): +```php +$data = [ + 'product-one' => ['name' => 'Desk 1', 'price' => 100], + 'product-two' => ['name' => 'Desk 2', 'price' => 150], +]; - echo __('Welcome to our application'); +data_get($data, '*.name'); - echo __('messages.welcome'); +// ['Desk 1', 'Desk 2']; +``` -If the specified translation string or key does not exist, the `__` function will return the given value. So, using the example above, the `__` function would return `messages.welcome` if that translation key does not exist. +The `{first}` and `{last}` placeholders may be used to retrieve the first or last items in an array: - -#### `class_basename()` {.collection-method} +```php +$flight = [ + 'segments' => [ + ['from' => 'LHR', 'departure' => '9:00', 'to' => 'IST', 'arrival' => '15:00'], + ['from' => 'IST', 'departure' => '16:00', 'to' => 'PKX', 'arrival' => '20:00'], + ], +]; -The `class_basename` function returns the class name of the given class with the class's namespace removed: +data_get($flight, 'segments.{first}.arrival'); - $class = class_basename('Foo\Bar\Baz'); +// 15:00 +``` - // Baz + +#### `data_set()` {.collection-method} - -#### `e()` {.collection-method} +The `data_set` function sets a value within a nested array or object using "dot" notation: -The `e` function runs PHP's `htmlspecialchars` function with the `double_encode` option set to `true` by default: +```php +$data = ['products' => ['desk' => ['price' => 100]]]; - echo e('foo'); +data_set($data, 'products.desk.price', 200); - // <html>foo</html> +// ['products' => ['desk' => ['price' => 200]]] +``` - -#### `preg_replace_array()` {.collection-method} +This function also accepts wildcards using asterisks and will set values on the target accordingly: -The `preg_replace_array` function replaces a given pattern in the string sequentially using an array: +```php +$data = [ + 'products' => [ + ['name' => 'Desk 1', 'price' => 100], + ['name' => 'Desk 2', 'price' => 150], + ], +]; - $string = 'The event will take place between :start and :end'; +data_set($data, 'products.*.price', 200); - $replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string); +/* + [ + 'products' => [ + ['name' => 'Desk 1', 'price' => 200], + ['name' => 'Desk 2', 'price' => 200], + ], + ] +*/ +``` - // The event will take place between 8:30 and 9:00 +By default, any existing values are overwritten. If you wish to only set a value if it doesn't exist, you may pass `false` as the fourth argument to the function: - -#### `Str::after()` {.collection-method} +```php +$data = ['products' => ['desk' => ['price' => 100]]]; -The `Str::after` method returns everything after the given value in a string. The entire string will be returned if the value does not exist within the string: +data_set($data, 'products.desk.price', 200, overwrite: false); - use Illuminate\Support\Str; +// ['products' => ['desk' => ['price' => 100]]] +``` - $slice = Str::after('This is my name', 'This is'); + +#### `data_forget()` {.collection-method} - // ' my name' +The `data_forget` function removes a value within a nested array or object using "dot" notation: - -#### `Str::afterLast()` {.collection-method} +```php +$data = ['products' => ['desk' => ['price' => 100]]]; -The `Str::afterLast` method returns everything after the last occurrence of the given value in a string. The entire string will be returned if the value does not exist within the string: +data_forget($data, 'products.desk.price'); - use Illuminate\Support\Str; +// ['products' => ['desk' => []]] +``` - $slice = Str::afterLast('App\Http\Controllers\Controller', '\\'); +This function also accepts wildcards using asterisks and will remove values on the target accordingly: - // 'Controller' +```php +$data = [ + 'products' => [ + ['name' => 'Desk 1', 'price' => 100], + ['name' => 'Desk 2', 'price' => 150], + ], +]; - -#### `Str::ascii()` {.collection-method} +data_forget($data, 'products.*.price'); -The `Str::ascii` method will attempt to transliterate the string into an ASCII value: +/* + [ + 'products' => [ + ['name' => 'Desk 1'], + ['name' => 'Desk 2'], + ], + ] +*/ +``` - use Illuminate\Support\Str; + +#### `head()` {.collection-method} - $slice = Str::ascii('û'); +The `head` function returns the first element in the given array. If the array is empty, `false` will be returned: - // 'u' +```php +$array = [100, 200, 300]; - -#### `Str::before()` {.collection-method} +$first = head($array); -The `Str::before` method returns everything before the given value in a string: +// 100 +``` - use Illuminate\Support\Str; + +#### `last()` {.collection-method} - $slice = Str::before('This is my name', 'my name'); +The `last` function returns the last element in the given array. If the array is empty, `false` will be returned: - // 'This is ' +```php +$array = [100, 200, 300]; - -#### `Str::beforeLast()` {.collection-method} +$last = last($array); -The `Str::beforeLast` method returns everything before the last occurrence of the given value in a string: +// 300 +``` - use Illuminate\Support\Str; + +## Numbers - $slice = Str::beforeLast('This is my name', 'is'); + +#### `Number::abbreviate()` {.collection-method} - // 'This ' +The `Number::abbreviate` method returns the human-readable format of the provided numerical value, with an abbreviation for the units: - -#### `Str::between()` {.collection-method} +```php +use Illuminate\Support\Number; -The `Str::between` method returns the portion of a string between two values: +$number = Number::abbreviate(1000); - use Illuminate\Support\Str; +// 1K - $slice = Str::between('This is my name', 'This', 'name'); +$number = Number::abbreviate(489939); - // ' is my ' +// 490K - -#### `Str::camel()` {.collection-method} +$number = Number::abbreviate(1230000, precision: 2); -The `Str::camel` method converts the given string to `camelCase`: +// 1.23M +``` - use Illuminate\Support\Str; + +#### `Number::clamp()` {.collection-method} - $converted = Str::camel('foo_bar'); +The `Number::clamp` method ensures a given number stays within a specified range. If the number is lower than the minimum, the minimum value is returned. If the number is higher than the maximum, the maximum value is returned: - // fooBar +```php +use Illuminate\Support\Number; - -#### `Str::contains()` {.collection-method} +$number = Number::clamp(105, min: 10, max: 100); -The `Str::contains` method determines if the given string contains the given value. This method is case sensitive: +// 100 - use Illuminate\Support\Str; +$number = Number::clamp(5, min: 10, max: 100); - $contains = Str::contains('This is my name', 'my'); +// 10 - // true +$number = Number::clamp(10, min: 10, max: 100); -You may also pass an array of values to determine if the given string contains any of the values in the array: +// 10 - use Illuminate\Support\Str; +$number = Number::clamp(20, min: 10, max: 100); - $contains = Str::contains('This is my name', ['my', 'foo']); +// 20 +``` - // true + +#### `Number::currency()` {.collection-method} - -#### `Str::containsAll()` {.collection-method} +The `Number::currency` method returns the currency representation of the given value as a string: -The `Str::containsAll` method determines if the given string contains all of the values in a given array: +```php +use Illuminate\Support\Number; - use Illuminate\Support\Str; +$currency = Number::currency(1000); - $containsAll = Str::containsAll('This is my name', ['my', 'name']); +// $1,000.00 - // true +$currency = Number::currency(1000, in: 'EUR'); - -#### `Str::endsWith()` {.collection-method} +// €1,000.00 -The `Str::endsWith` method determines if the given string ends with the given value: +$currency = Number::currency(1000, in: 'EUR', locale: 'de'); - use Illuminate\Support\Str; +// 1.000,00 € - $result = Str::endsWith('This is my name', 'name'); +$currency = Number::currency(1000, in: 'EUR', locale: 'de', precision: 0); - // true +// 1.000 € +``` + +#### `Number::defaultCurrency()` {.collection-method} -You may also pass an array of values to determine if the given string ends with any of the values in the array: +The `Number::defaultCurrency` method returns the default currency being used by the `Number` class: - use Illuminate\Support\Str; +```php +use Illuminate\Support\Number; - $result = Str::endsWith('This is my name', ['name', 'foo']); +$currency = Number::defaultCurrency(); - // true +// USD +``` - $result = Str::endsWith('This is my name', ['this', 'foo']); + +#### `Number::defaultLocale()` {.collection-method} - // false +The `Number::defaultLocale` method returns the default locale being used by the `Number` class: - -#### `Str::excerpt()` {.collection-method} +```php +use Illuminate\Support\Number; -The `Str::excerpt` method extracts an excerpt from a given string that matches the first instance of a phrase within that string: +$locale = Number::defaultLocale(); - use Illuminate\Support\Str; +// en +``` - $excerpt = Str::excerpt('This is my name', 'my', [ - 'radius' => 3 - ]); + +#### `Number::fileSize()` {.collection-method} - // '...is my na...' +The `Number::fileSize` method returns the file size representation of the given byte value as a string: -The `radius` option, which defaults to `100`, allows you to define the number of characters that should appear on each side of the truncated string. +```php +use Illuminate\Support\Number; -In addition, you may use the `omission` option to define the string that will be prepended and appended to the truncated string: +$size = Number::fileSize(1024); - use Illuminate\Support\Str; +// 1 KB - $excerpt = Str::excerpt('This is my name', 'name', [ - 'radius' => 3, - 'omission' => '(...) ' - ]); +$size = Number::fileSize(1024 * 1024); - // '(...) my name' +// 1 MB - -#### `Str::finish()` {.collection-method} +$size = Number::fileSize(1024, precision: 2); -The `Str::finish` method adds a single instance of the given value to a string if it does not already end with that value: +// 1.00 KB +``` - use Illuminate\Support\Str; + +#### `Number::forHumans()` {.collection-method} - $adjusted = Str::finish('this/string', '/'); +The `Number::forHumans` method returns the human-readable format of the provided numerical value: - // this/string/ +```php +use Illuminate\Support\Number; - $adjusted = Str::finish('this/string/', '/'); +$number = Number::forHumans(1000); - // this/string/ +// 1 thousand - -#### `Str::headline()` {.collection-method} +$number = Number::forHumans(489939); -The `Str::headline` method will convert strings delimited by casing, hyphens, or underscores into a space delimited string with each word's first letter capitalized: +// 490 thousand - use Illuminate\Support\Str; +$number = Number::forHumans(1230000, precision: 2); - $headline = Str::headline('steve_jobs'); +// 1.23 million +``` - // Steve Jobs + +#### `Number::format()` {.collection-method} - $headline = Str::headline('EmailNotificationSent'); +The `Number::format` method formats the given number into a locale specific string: - // Email Notification Sent +```php +use Illuminate\Support\Number; - -#### `Str::is()` {.collection-method} +$number = Number::format(100000); -The `Str::is` method determines if a given string matches a given pattern. Asterisks may be used as wildcard values: +// 100,000 - use Illuminate\Support\Str; +$number = Number::format(100000, precision: 2); - $matches = Str::is('foo*', 'foobar'); +// 100,000.00 - // true +$number = Number::format(100000.123, maxPrecision: 2); - $matches = Str::is('baz*', 'foobar'); +// 100,000.12 - // false +$number = Number::format(100000, locale: 'de'); - -#### `Str::isAscii()` {.collection-method} +// 100.000 +``` -The `Str::isAscii` method determines if a given string is 7 bit ASCII: + +#### `Number::ordinal()` {.collection-method} - use Illuminate\Support\Str; +The `Number::ordinal` method returns a number's ordinal representation: - $isAscii = Str::isAscii('Taylor'); +```php +use Illuminate\Support\Number; - // true +$number = Number::ordinal(1); - $isAscii = Str::isAscii('ü'); +// 1st - // false +$number = Number::ordinal(2); - -#### `Str::isUuid()` {.collection-method} +// 2nd -The `Str::isUuid` method determines if the given string is a valid UUID: +$number = Number::ordinal(21); - use Illuminate\Support\Str; +// 21st +``` - $isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de'); + +#### `Number::pairs()` {.collection-method} - // true +The `Number::pairs` method generates an array of number pairs (sub-ranges) based on a specified range and step value. This method can be useful for dividing a larger range of numbers into smaller, manageable sub-ranges for things like pagination or batching tasks. The `pairs` method returns an array of arrays, where each inner array represents a pair (sub-range) of numbers: - $isUuid = Str::isUuid('laravel'); +```php +use Illuminate\Support\Number; - // false +$result = Number::pairs(25, 10); - -#### `Str::kebab()` {.collection-method} +// [[0, 9], [10, 19], [20, 25]] -The `Str::kebab` method converts the given string to `kebab-case`: +$result = Number::pairs(25, 10, offset: 0); - use Illuminate\Support\Str; +// [[0, 10], [10, 20], [20, 25]] +``` - $converted = Str::kebab('fooBar'); + +#### `Number::parseInt()` {.collection-method} - // foo-bar +The `Number::parseInt` method parse a string into an integer according to the specified locale: - -#### `Str::length()` {.collection-method} +```php +use Illuminate\Support\Number; -The `Str::length` method returns the length of the given string: +$result = Number::parseInt('10.123'); - use Illuminate\Support\Str; +// (int) 10 - $length = Str::length('Laravel'); +$result = Number::parseInt('10,123', locale: 'fr'); - // 7 +// (int) 10 +``` - -#### `Str::limit()` {.collection-method} + +#### `Number::parseFloat()` {.collection-method} -The `Str::limit` method truncates the given string to the specified length: +The `Number::parseFloat` method parse a string into a float according to the specified locale: - use Illuminate\Support\Str; +```php +use Illuminate\Support\Number; - $truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20); +$result = Number::parseFloat('10'); - // The quick brown fox... +// (float) 10.0 -You may pass a third argument to the method to change the string that will be appended to the end of the truncated string: +$result = Number::parseFloat('10', locale: 'fr'); - use Illuminate\Support\Str; +// (float) 10.0 +``` - $truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)'); + +#### `Number::percentage()` {.collection-method} - // The quick brown fox (...) +The `Number::percentage` method returns the percentage representation of the given value as a string: - -#### `Str::lower()` {.collection-method} +```php +use Illuminate\Support\Number; -The `Str::lower` method converts the given string to lowercase: +$percentage = Number::percentage(10); - use Illuminate\Support\Str; +// 10% - $converted = Str::lower('LARAVEL'); +$percentage = Number::percentage(10, precision: 2); - // laravel +// 10.00% - -#### `Str::markdown()` {.collection-method} +$percentage = Number::percentage(10.123, maxPrecision: 2); -The `Str::markdown` method converts GitHub flavored Markdown into HTML: +// 10.12% - use Illuminate\Support\Str; +$percentage = Number::percentage(10, precision: 2, locale: 'de'); - $html = Str::markdown('# Laravel'); +// 10,00% +``` - //

Laravel

+ +#### `Number::spell()` {.collection-method} - $html = Str::markdown('# Taylor Otwell', [ - 'html_input' => 'strip', - ]); +The `Number::spell` method transforms the given number into a string of words: - //

Taylor Otwell

+```php +use Illuminate\Support\Number; - -#### `Str::mask()` {.collection-method} +$number = Number::spell(102); -The `Str::mask` method masks a portion of a string with a repeated character, and may be used to obfuscate segments of strings such as email addresses and phone numbers: +// one hundred and two - use Illuminate\Support\Str; +$number = Number::spell(88, locale: 'fr'); - $string = Str::mask('taylor@example.com', '*', 3); +// quatre-vingt-huit +``` - // tay*************** +The `after` argument allows you to specify a value after which all numbers should be spelled out: -If needed, you provide a negative number as the third argument to the `mask` method, which will instruct the method to begin masking at the given distance from the end of the string: +```php +$number = Number::spell(10, after: 10); - $string = Str::mask('taylor@example.com', '*', -15, 3); +// 10 - // tay***@example.com +$number = Number::spell(11, after: 10); - -#### `Str::orderedUuid()` {.collection-method} +// eleven +``` -The `Str::orderedUuid` method generates a "timestamp first" UUID that may be efficiently stored in an indexed database column. Each UUID that is generated using this method will be sorted after UUIDs previously generated using the method: +The `until` argument allows you to specify a value before which all numbers should be spelled out: - use Illuminate\Support\Str; +```php +$number = Number::spell(5, until: 10); - return (string) Str::orderedUuid(); +// five - -#### `Str::padBoth()` {.collection-method} +$number = Number::spell(10, until: 10); -The `Str::padBoth` method wraps PHP's `str_pad` function, padding both sides of a string with another string until the final string reaches a desired length: +// 10 +``` - use Illuminate\Support\Str; + +#### `Number::spellOrdinal()` {.collection-method} - $padded = Str::padBoth('James', 10, '_'); +The `Number::spellOrdinal` method returns the number's ordinal representation as a string of words: - // '__James___' +```php +use Illuminate\Support\Number; - $padded = Str::padBoth('James', 10); +$number = Number::spellOrdinal(1); - // ' James ' +// first - -#### `Str::padLeft()` {.collection-method} +$number = Number::spellOrdinal(2); -The `Str::padLeft` method wraps PHP's `str_pad` function, padding the left side of a string with another string until the final string reaches a desired length: +// second - use Illuminate\Support\Str; +$number = Number::spellOrdinal(21); - $padded = Str::padLeft('James', 10, '-='); +// twenty-first +``` - // '-=-=-James' + +#### `Number::trim()` {.collection-method} - $padded = Str::padLeft('James', 10); +The `Number::trim` method removes any trailing zero digits after the decimal point of the given number: - // ' James' +```php +use Illuminate\Support\Number; - -#### `Str::padRight()` {.collection-method} +$number = Number::trim(12.0); -The `Str::padRight` method wraps PHP's `str_pad` function, padding the right side of a string with another string until the final string reaches a desired length: +// 12 - use Illuminate\Support\Str; +$number = Number::trim(12.30); - $padded = Str::padRight('James', 10, '-'); +// 12.3 +``` - // 'James-----' + +#### `Number::useLocale()` {.collection-method} - $padded = Str::padRight('James', 10); +The `Number::useLocale` method sets the default number locale globally, which affects how numbers and currency are formatted by subsequent invocations to the `Number` class's methods: - // 'James ' +```php +use Illuminate\Support\Number; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Number::useLocale('de'); +} +``` - -#### `Str::plural()` {.collection-method} + +#### `Number::withLocale()` {.collection-method} -The `Str::plural` method converts a singular word string to its plural form. This function currently only supports the English language: +The `Number::withLocale` method executes the given closure using the specified locale and then restores the original locale after the callback has executed: - use Illuminate\Support\Str; +```php +use Illuminate\Support\Number; - $plural = Str::plural('car'); +$number = Number::withLocale('de', function () { + return Number::format(1500); +}); +``` - // cars + +#### `Number::useCurrency()` {.collection-method} - $plural = Str::plural('child'); +The `Number::useCurrency` method sets the default number currency globally, which affects how the currency is formatted by subsequent invocations to the `Number` class's methods: - // children +```php +use Illuminate\Support\Number; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Number::useCurrency('GBP'); +} +``` -You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string: + +#### `Number::withCurrency()` {.collection-method} - use Illuminate\Support\Str; +The `Number::withCurrency` method executes the given closure using the specified currency and then restores the original currency after the callback has executed: - $plural = Str::plural('child', 2); +```php +use Illuminate\Support\Number; - // children +$number = Number::withCurrency('GBP', function () { + // ... +}); +``` - $singular = Str::plural('child', 1); + +## Paths - // child + +#### `app_path()` {.collection-method} - -#### `Str::pluralStudly()` {.collection-method} +The `app_path` function returns the fully qualified path to your application's `app` directory. You may also use the `app_path` function to generate a fully qualified path to a file relative to the application directory: -The `Str::pluralStudly` method converts a singular word string formatted in studly caps case to its plural form. This function currently only supports the English language: +```php +$path = app_path(); - use Illuminate\Support\Str; +$path = app_path('Http/Controllers/Controller.php'); +``` - $plural = Str::pluralStudly('VerifiedHuman'); + +#### `base_path()` {.collection-method} - // VerifiedHumans +The `base_path` function returns the fully qualified path to your application's root directory. You may also use the `base_path` function to generate a fully qualified path to a given file relative to the project root directory: - $plural = Str::pluralStudly('UserFeedback'); +```php +$path = base_path(); - // UserFeedback +$path = base_path('vendor/bin'); +``` -You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string: + +#### `config_path()` {.collection-method} - use Illuminate\Support\Str; +The `config_path` function returns the fully qualified path to your application's `config` directory. You may also use the `config_path` function to generate a fully qualified path to a given file within the application's configuration directory: - $plural = Str::pluralStudly('VerifiedHuman', 2); +```php +$path = config_path(); - // VerifiedHumans +$path = config_path('app.php'); +``` - $singular = Str::pluralStudly('VerifiedHuman', 1); + +#### `database_path()` {.collection-method} - // VerifiedHuman +The `database_path` function returns the fully qualified path to your application's `database` directory. You may also use the `database_path` function to generate a fully qualified path to a given file within the database directory: - -#### `Str::random()` {.collection-method} +```php +$path = database_path(); -The `Str::random` method generates a random string of the specified length. This function uses PHP's `random_bytes` function: +$path = database_path('factories/UserFactory.php'); +``` - use Illuminate\Support\Str; + +#### `lang_path()` {.collection-method} - $random = Str::random(40); +The `lang_path` function returns the fully qualified path to your application's `lang` directory. You may also use the `lang_path` function to generate a fully qualified path to a given file within the directory: - -#### `Str::remove()` {.collection-method} +```php +$path = lang_path(); -The `Str::remove` method removes the given value or array of values from the string: +$path = lang_path('en/messages.php'); +``` - use Illuminate\Support\Str; +> [!NOTE] +> By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. - $string = 'Peter Piper picked a peck of pickled peppers.'; + +#### `public_path()` {.collection-method} - $removed = Str::remove('e', $string); +The `public_path` function returns the fully qualified path to your application's `public` directory. You may also use the `public_path` function to generate a fully qualified path to a given file within the public directory: - // Ptr Pipr pickd a pck of pickld ppprs. +```php +$path = public_path(); -You may also pass `false` as a third argument to the `remove` method to ignore case when removing strings. +$path = public_path('css/app.css'); +``` - -#### `Str::replace()` {.collection-method} + +#### `resource_path()` {.collection-method} -The `Str::replace` method replaces a given string within the string: +The `resource_path` function returns the fully qualified path to your application's `resources` directory. You may also use the `resource_path` function to generate a fully qualified path to a given file within the resources directory: - use Illuminate\Support\Str; +```php +$path = resource_path(); - $string = 'Laravel 8.x'; +$path = resource_path('sass/app.scss'); +``` - $replaced = Str::replace('8.x', '9.x', $string); - - // Laravel 9.x + +#### `storage_path()` {.collection-method} - -#### `Str::replaceArray()` {.collection-method} +The `storage_path` function returns the fully qualified path to your application's `storage` directory. You may also use the `storage_path` function to generate a fully qualified path to a given file within the storage directory: -The `Str::replaceArray` method replaces a given value in the string sequentially using an array: +```php +$path = storage_path(); - use Illuminate\Support\Str; +$path = storage_path('app/file.txt'); +``` - $string = 'The event will take place between ? and ?'; + +## URLs - $replaced = Str::replaceArray('?', ['8:30', '9:00'], $string); + +#### `action()` {.collection-method} - // The event will take place between 8:30 and 9:00 +The `action` function generates a URL for the given controller action: - -#### `Str::replaceFirst()` {.collection-method} +```php +use App\Http\Controllers\HomeController; -The `Str::replaceFirst` method replaces the first occurrence of a given value in a string: +$url = action([HomeController::class, 'index']); +``` - use Illuminate\Support\Str; +If the method accepts route parameters, you may pass them as the second argument to the method: - $replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog'); +```php +$url = action([UserController::class, 'profile'], ['id' => 1]); +``` - // a quick brown fox jumps over the lazy dog + +#### `asset()` {.collection-method} - -#### `Str::replaceLast()` {.collection-method} +The `asset` function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS): -The `Str::replaceLast` method replaces the last occurrence of a given value in a string: +```php +$url = asset('img/photo.jpg'); +``` - use Illuminate\Support\Str; +You can configure the asset URL host by setting the `ASSET_URL` variable in your `.env` file. This can be useful if you host your assets on an external service like Amazon S3 or another CDN: - $replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog'); +```php +// ASSET_URL=http://example.com/assets - // the quick brown fox jumps over a lazy dog +$url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg +``` + +#### `route()` {.collection-method} - -#### `Str::reverse()` {.collection-method} +The `route` function generates a URL for a given [named route](/docs/{{version}}/routing#named-routes): -The `Str::reverse` method reverses the given string: +```php +$url = route('route.name'); +``` - use Illuminate\Support\Str; +If the route accepts parameters, you may pass them as the second argument to the function: - $reversed = Str::reverse('Hello World'); +```php +$url = route('route.name', ['id' => 1]); +``` - // dlroW olleH +By default, the `route` function generates an absolute URL. If you wish to generate a relative URL, you may pass `false` as the third argument to the function: - -#### `Str::singular()` {.collection-method} +```php +$url = route('route.name', ['id' => 1], false); +``` -The `Str::singular` method converts a string to its singular form. This function currently only supports the English language: + +#### `secure_asset()` {.collection-method} - use Illuminate\Support\Str; +The `secure_asset` function generates a URL for an asset using HTTPS: - $singular = Str::singular('cars'); +```php +$url = secure_asset('img/photo.jpg'); +``` - // car + +#### `secure_url()` {.collection-method} - $singular = Str::singular('children'); +The `secure_url` function generates a fully qualified HTTPS URL to the given path. Additional URL segments may be passed in the function's second argument: - // child +```php +$url = secure_url('https://github.com/user/profile'); - -#### `Str::slug()` {.collection-method} +$url = secure_url('https://github.com/user/profile',%20[1]); +``` -The `Str::slug` method generates a URL friendly "slug" from the given string: + +#### `to_action()` {.collection-method} - use Illuminate\Support\Str; +The `to_action` function generates a [redirect HTTP response](/docs/{{version}}/responses#redirects) for a given controller action: - $slug = Str::slug('Laravel 5 Framework', '-'); +```php +use App\Http\Controllers\UserController; - // laravel-5-framework +return to_action([UserController::class, 'show'], ['user' => 1]); +``` - -#### `Str::snake()` {.collection-method} +If necessary, you may pass the HTTP status code that should be assigned to the redirect and any additional response headers as the third and fourth arguments to the `to_action` method: -The `Str::snake` method converts the given string to `snake_case`: +```php +return to_action( + [UserController::class, 'show'], + ['user' => 1], + 302, + ['X-Framework' => 'Laravel'] +); +``` - use Illuminate\Support\Str; + +#### `to_route()` {.collection-method} - $converted = Str::snake('fooBar'); +The `to_route` function generates a [redirect HTTP response](/docs/{{version}}/responses#redirects) for a given [named route](/docs/{{version}}/routing#named-routes): - // foo_bar +```php +return to_route('users.show', ['user' => 1]); +``` - $converted = Str::snake('fooBar', '-'); +If necessary, you may pass the HTTP status code that should be assigned to the redirect and any additional response headers as the third and fourth arguments to the `to_route` method: - // foo-bar +```php +return to_route('users.show', ['user' => 1], 302, ['X-Framework' => 'Laravel']); +``` - -#### `Str::start()` {.collection-method} + +#### `uri()` {.collection-method} -The `Str::start` method adds a single instance of the given value to a string if it does not already start with that value: +The `uri` function generates a [fluent URI instance](#uri) for the given URI: - use Illuminate\Support\Str; +```php +$uri = uri('https://example.com/') + ->withPath('/users') + ->withQuery(['page' => 1]); +``` - $adjusted = Str::start('this/string', '/'); +If the `uri` function is given an array containing a callable controller and method pair, the function will create a `Uri` instance for the controller method's route path: - // /this/string +```php +use App\Http\Controllers\UserController; - $adjusted = Str::start('/this/string', '/'); +$uri = uri([UserController::class, 'show'], ['user' => $user]); +``` - // /this/string +If the controller is invokable, you may simply provide the controller class name: - -#### `Str::startsWith()` {.collection-method} +```php +use App\Http\Controllers\UserIndexController; -The `Str::startsWith` method determines if the given string begins with the given value: +$uri = uri(UserIndexController::class); +``` - use Illuminate\Support\Str; +If the value given to the `uri` function matches the name of a [named route](/docs/{{version}}/routing#named-routes), a `Uri` instance will be generated for that route's path: - $result = Str::startsWith('This is my name', 'This'); +```php +$uri = uri('users.show', ['user' => $user]); +``` - // true + +#### `url()` {.collection-method} -If an array of possible values is passed, the `startsWith` method will return `true` if the string begins with any of the given values: +The `url` function generates a fully qualified URL to the given path: - $result = Str::startsWith('This is my name', ['This', 'That', 'There']); +```php +$url = url('https://github.com/user/profile'); - // true +$url = url('https://github.com/user/profile',%20[1]); +``` - -#### `Str::studly()` {.collection-method} +If no path is provided, an `Illuminate\Routing\UrlGenerator` instance is returned: -The `Str::studly` method converts the given string to `StudlyCase`: +```php +$current = url()->current(); - use Illuminate\Support\Str; +$full = url()->full(); - $converted = Str::studly('foo_bar'); +$previous = url()->previous(); +``` - // FooBar +For more information on working with the `url` function, consult the [URL generation documentation](/docs/{{version}}/urls#generating-urls). - -#### `Str::substr()` {.collection-method} + +## Miscellaneous -The `Str::substr` method returns the portion of string specified by the start and length parameters: + +#### `abort()` {.collection-method} - use Illuminate\Support\Str; +The `abort` function throws [an HTTP exception](/docs/{{version}}/errors#http-exceptions) which will be rendered by the [exception handler](/docs/{{version}}/errors#handling-exceptions): - $converted = Str::substr('The Laravel Framework', 4, 7); +```php +abort(403); +``` - // Laravel +You may also provide the exception's message and custom HTTP response headers that should be sent to the browser: - -#### `Str::substrCount()` {.collection-method} +```php +abort(403, 'Unauthorized.', $headers); +``` -The `Str::substrCount` method returns the number of occurrences of a given value in the given string: + +#### `abort_if()` {.collection-method} - use Illuminate\Support\Str; +The `abort_if` function throws an HTTP exception if a given boolean expression evaluates to `true`: - $count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like'); +```php +abort_if(! Auth::user()->isAdmin(), 403); +``` - // 2 +Like the `abort` method, you may also provide the exception's response text as the third argument and an array of custom response headers as the fourth argument to the function. - -#### `Str::substrReplace()` {.collection-method} + +#### `abort_unless()` {.collection-method} -The `Str::substrReplace` method replaces text within a portion of a string, starting at the position specified by the third argument and replacing the number of characters specified by the fourth argument. Passing `0` to the method's fourth argument will insert the string at the specified position without replacing any of the existing characters in the string: +The `abort_unless` function throws an HTTP exception if a given boolean expression evaluates to `false`: - use Illuminate\Support\Str; +```php +abort_unless(Auth::user()->isAdmin(), 403); +``` - $result = Str::substrReplace('1300', ':', 2); - // 13: - - $result = Str::substrReplace('1300', ':', 2, 0); - // 13:00 +Like the `abort` method, you may also provide the exception's response text as the third argument and an array of custom response headers as the fourth argument to the function. - -#### `Str::swap()` {.collection-method} + +#### `app()` {.collection-method} -The `Str::swap` method replaces multiple values in the given string using PHP's `strtr` function: +The `app` function returns the [service container](/docs/{{version}}/container) instance: - use Illuminate\Support\Str; +```php +$container = app(); +``` - $string = Str::swap([ - 'Tacos' => 'Burritos', - 'great' => 'fantastic', - ], 'Tacos are great!'); +You may pass a class or interface name to resolve it from the container: - // Burritos are fantastic! +```php +$api = app('HelpSpot\API'); +``` - -#### `Str::title()` {.collection-method} + +#### `auth()` {.collection-method} -The `Str::title` method converts the given string to `Title Case`: +The `auth` function returns an [authenticator](/docs/{{version}}/authentication) instance. You may use it as an alternative to the `Auth` facade: - use Illuminate\Support\Str; +```php +$user = auth()->user(); +``` - $converted = Str::title('a nice title uses the correct case'); +If needed, you may specify which guard instance you would like to access: - // A Nice Title Uses The Correct Case +```php +$user = auth('admin')->user(); +``` - -#### `Str::toHtmlString()` {.collection-method} + +#### `back()` {.collection-method} -The `Str::toHtmlString` method converts the string instance to an instance of `Illuminate\Support\HtmlString`, which may be displayed in Blade templates: +The `back` function generates a [redirect HTTP response](/docs/{{version}}/responses#redirects) to the user's previous location: - use Illuminate\Support\Str; +```php +return back($status = 302, $headers = [], $fallback = '/'); - $htmlString = Str::of('Nuno Maduro')->toHtmlString(); +return back(); +``` - -#### `Str::ucfirst()` {.collection-method} + +#### `bcrypt()` {.collection-method} -The `Str::ucfirst` method returns the given string with the first character capitalized: +The `bcrypt` function [hashes](/docs/{{version}}/hashing) the given value using Bcrypt. You may use this function as an alternative to the `Hash` facade: - use Illuminate\Support\Str; +```php +$password = bcrypt('my-secret-password'); +``` - $string = Str::ucfirst('foo bar'); + +#### `blank()` {.collection-method} - // Foo bar +The `blank` function determines whether the given value is "blank": - -#### `Str::upper()` {.collection-method} +```php +blank(''); +blank(' '); +blank(null); +blank(collect()); -The `Str::upper` method converts the given string to uppercase: +// true - use Illuminate\Support\Str; +blank(0); +blank(true); +blank(false); - $string = Str::upper('laravel'); +// false +``` - // LARAVEL +For the inverse of `blank`, see the [filled](#method-filled) function. - -#### `Str::uuid()` {.collection-method} + +#### `broadcast()` {.collection-method} -The `Str::uuid` method generates a UUID (version 4): +The `broadcast` function [broadcasts](/docs/{{version}}/broadcasting) the given [event](/docs/{{version}}/events) to its listeners: - use Illuminate\Support\Str; +```php +broadcast(new UserRegistered($user)); - return (string) Str::uuid(); +broadcast(new UserRegistered($user))->toOthers(); +``` - -#### `Str::wordCount()` {.collection-method} + +#### `broadcast_if()` {.collection-method} -The `Str::wordCount` method returns the number of words that a string contains: +The `broadcast_if` function [broadcasts](/docs/{{version}}/broadcasting) the given [event](/docs/{{version}}/events) to its listeners if a given boolean expression evaluates to `true`: ```php -use Illuminate\Support\Str; +broadcast_if($user->isActive(), new UserRegistered($user)); -Str::wordCount('Hello, world!'); // 2 +broadcast_if($user->isActive(), new UserRegistered($user))->toOthers(); ``` - -#### `Str::words()` {.collection-method} + +#### `broadcast_unless()` {.collection-method} -The `Str::words` method limits the number of words in a string. An additional string may be passed to this method via its third argument to specify which string should be appended to the end of the truncated string: +The `broadcast_unless` function [broadcasts](/docs/{{version}}/broadcasting) the given [event](/docs/{{version}}/events) to its listeners if a given boolean expression evaluates to `false`: - use Illuminate\Support\Str; +```php +broadcast_unless($user->isBanned(), new UserRegistered($user)); - return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>'); +broadcast_unless($user->isBanned(), new UserRegistered($user))->toOthers(); +``` - // Perfectly balanced, as >>> + +#### `cache()` {.collection-method} - -#### `str()` {.collection-method} +The `cache` function may be used to get values from the [cache](/docs/{{version}}/cache). If the given key does not exist in the cache, an optional default value will be returned: -The `str` function returns a new `Illuminate\Support\Stringable` instance of the given string. This function is equivalent to the `Str::of` method: +```php +$value = cache('key'); - $string = str('Taylor')->append(' Otwell'); +$value = cache('key', 'default'); +``` - // 'Taylor Otwell' +You may add items to the cache by passing an array of key / value pairs to the function. You should also pass the number of seconds or duration the cached value should be considered valid: -If no argument is provided to the `str` function, the function returns an instance of `Illuminate\Support\Str`: +```php +cache(['key' => 'value'], 300); - $snake = str()->snake('FooBar'); +cache(['key' => 'value'], now()->addSeconds(10)); +``` - // 'foo_bar' + +#### `class_uses_recursive()` {.collection-method} - -#### `trans()` {.collection-method} +The `class_uses_recursive` function returns all traits used by a class, including traits used by all of its parent classes: -The `trans` function translates the given translation key using your [localization files](/docs/{{version}}/localization): +```php +$traits = class_uses_recursive(App\Models\User::class); +``` - echo trans('messages.welcome'); + +#### `collect()` {.collection-method} -If the specified translation key does not exist, the `trans` function will return the given key. So, using the example above, the `trans` function would return `messages.welcome` if the translation key does not exist. +The `collect` function creates a [collection](/docs/{{version}}/collections) instance from the given value: - -#### `trans_choice()` {.collection-method} +```php +$collection = collect(['Taylor', 'Abigail']); +``` -The `trans_choice` function translates the given translation key with inflection: + +#### `config()` {.collection-method} - echo trans_choice('messages.notifications', $unreadCount); +The `config` function gets the value of a [configuration](/docs/{{version}}/configuration) variable. The configuration values may be accessed using "dot" syntax, which includes the name of the file and the option you wish to access. You may also provide a default value that will be returned if the configuration option does not exist: -If the specified translation key does not exist, the `trans_choice` function will return the given key. So, using the example above, the `trans_choice` function would return `messages.notifications` if the translation key does not exist. +```php +$value = config('app.timezone'); - -## Fluent Strings +$value = config('app.timezone', $default); +``` -Fluent strings provide a more fluent, object-oriented interface for working with string values, allowing you to chain multiple string operations together using a more readable syntax compared to traditional string operations. +You may set configuration variables at runtime by passing an array of key / value pairs. However, note that this function only affects the configuration value for the current request and does not update your actual configuration values: - -#### `after` {.collection-method} +```php +config(['app.debug' => true]); +``` -The `after` method returns everything after the given value in a string. The entire string will be returned if the value does not exist within the string: + +#### `context()` {.collection-method} - use Illuminate\Support\Str; +The `context` function gets the value from the current [context](/docs/{{version}}/context). You may also provide a default value that will be returned if the context key does not exist: - $slice = Str::of('This is my name')->after('This is'); +```php +$value = context('trace_id'); - // ' my name' +$value = context('trace_id', $default); +``` - -#### `afterLast` {.collection-method} +You may set context values by passing an array of key / value pairs: -The `afterLast` method returns everything after the last occurrence of the given value in a string. The entire string will be returned if the value does not exist within the string: +```php +use Illuminate\Support\Str; - use Illuminate\Support\Str; +context(['trace_id' => Str::uuid()->toString()]); +``` - $slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\'); + +#### `cookie()` {.collection-method} - // 'Controller' +The `cookie` function creates a new [cookie](/docs/{{version}}/requests#cookies) instance: - -#### `append` {.collection-method} +```php +$cookie = cookie('name', 'value', $minutes); +``` -The `append` method appends the given values to the string: + +#### `csrf_field()` {.collection-method} - use Illuminate\Support\Str; +The `csrf_field` function generates an HTML `hidden` input field containing the value of the CSRF token. For example, using [Blade syntax](/docs/{{version}}/blade): - $string = Str::of('Taylor')->append(' Otwell'); +```blade +{{ csrf_field() }} +``` - // 'Taylor Otwell' + +#### `csrf_token()` {.collection-method} - -#### `ascii` {.collection-method} +The `csrf_token` function retrieves the value of the current CSRF token: -The `ascii` method will attempt to transliterate the string into an ASCII value: +```php +$token = csrf_token(); +``` - use Illuminate\Support\Str; + +#### `decrypt()` {.collection-method} - $string = Str::of('ü')->ascii(); +The `decrypt` function [decrypts](/docs/{{version}}/encryption) the given value. You may use this function as an alternative to the `Crypt` facade: - // 'u' +```php +$password = decrypt($value); +``` - -#### `basename` {.collection-method} +For the inverse of `decrypt`, see the [encrypt](#method-encrypt) function. -The `basename` method will return the trailing name component of the given string: + +#### `dd()` {.collection-method} - use Illuminate\Support\Str; +The `dd` function dumps the given variables and ends the execution of the script: - $string = Str::of('/foo/bar/baz')->basename(); +```php +dd($value); - // 'baz' +dd($value1, $value2, $value3, ...); +``` -If needed, you may provide an "extension" that will be removed from the trailing component: +If you do not want to halt the execution of your script, use the [dump](#method-dump) function instead. - use Illuminate\Support\Str; + +#### `dispatch()` {.collection-method} - $string = Str::of('/foo/bar/baz.jpg')->basename('.jpg'); +The `dispatch` function pushes the given [job](/docs/{{version}}/queues#creating-jobs) onto the Laravel [job queue](/docs/{{version}}/queues): - // 'baz' +```php +dispatch(new App\Jobs\SendEmails); +``` - -#### `before` {.collection-method} + +#### `dispatch_sync()` {.collection-method} -The `before` method returns everything before the given value in a string: +The `dispatch_sync` function pushes the given job to the [sync](/docs/{{version}}/queues#synchronous-dispatching) queue so that it is processed immediately: - use Illuminate\Support\Str; +```php +dispatch_sync(new App\Jobs\SendEmails); +``` - $slice = Str::of('This is my name')->before('my name'); + +#### `dump()` {.collection-method} - // 'This is ' +The `dump` function dumps the given variables: - -#### `beforeLast` {.collection-method} +```php +dump($value); -The `beforeLast` method returns everything before the last occurrence of the given value in a string: +dump($value1, $value2, $value3, ...); +``` - use Illuminate\Support\Str; +If you want to stop executing the script after dumping the variables, use the [dd](#method-dd) function instead. - $slice = Str::of('This is my name')->beforeLast('is'); + +#### `encrypt()` {.collection-method} - // 'This ' +The `encrypt` function [encrypts](/docs/{{version}}/encryption) the given value. You may use this function as an alternative to the `Crypt` facade: - -#### `between` {.collection-method} +```php +$secret = encrypt('my-secret-value'); +``` -The `between` method returns the portion of a string between two values: +For the inverse of `encrypt`, see the [decrypt](#method-decrypt) function. - use Illuminate\Support\Str; + +#### `env()` {.collection-method} - $converted = Str::of('This is my name')->between('This', 'name'); +The `env` function retrieves the value of an [environment variable](/docs/{{version}}/configuration#environment-configuration) or returns a default value: - // ' is my ' +```php +$env = env('APP_ENV'); - -#### `camel` {.collection-method} +$env = env('APP_ENV', 'production'); +``` -The `camel` method converts the given string to `camelCase`: +> [!WARNING] +> If you execute the `config:cache` command during your deployment process, you should be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded and all calls to the `env` function will return external environment variables such as server-level or system-level environment variables or `null`. - use Illuminate\Support\Str; + +#### `event()` {.collection-method} - $converted = Str::of('foo_bar')->camel(); +The `event` function dispatches the given [event](/docs/{{version}}/events) to its listeners: - // fooBar +```php +event(new UserRegistered($user)); +``` - -#### `contains` {.collection-method} + +#### `fake()` {.collection-method} -The `contains` method determines if the given string contains the given value. This method is case sensitive: +The `fake` function resolves a [Faker](https://github.com/FakerPHP/Faker) singleton from the container, which can be useful when creating fake data in model factories, database seeding, tests, and prototyping views: - use Illuminate\Support\Str; +```blade +@for ($i = 0; $i < 10; $i++) +
+
Name
+
{{ fake()->name() }}
- $contains = Str::of('This is my name')->contains('my'); +
Email
+
{{ fake()->unique()->safeEmail() }}
+
+@endfor +``` - // true +By default, the `fake` function will utilize the `app.faker_locale` configuration option in your `config/app.php` configuration. Typically, this configuration option is set via the `APP_FAKER_LOCALE` environment variable. You may also specify the locale by passing it to the `fake` function. Each locale will resolve an individual singleton: -You may also pass an array of values to determine if the given string contains any of the values in the array: +```php +fake('nl_NL')->name() +``` - use Illuminate\Support\Str; + +#### `filled()` {.collection-method} - $contains = Str::of('This is my name')->contains(['my', 'foo']); +The `filled` function determines whether the given value is not "blank": - // true +```php +filled(0); +filled(true); +filled(false); - -#### `containsAll` {.collection-method} +// true -The `containsAll` method determines if the given string contains all of the values in the given array: +filled(''); +filled(' '); +filled(null); +filled(collect()); - use Illuminate\Support\Str; +// false +``` - $containsAll = Str::of('This is my name')->containsAll(['my', 'name']); +For the inverse of `filled`, see the [blank](#method-blank) function. - // true + +#### `info()` {.collection-method} - -#### `dirname` {.collection-method} +The `info` function will write information to your application's [log](/docs/{{version}}/logging): -The `dirname` method returns the parent directory portion of the given string: +```php +info('Some helpful information!'); +``` - use Illuminate\Support\Str; +An array of contextual data may also be passed to the function: - $string = Str::of('/foo/bar/baz')->dirname(); +```php +info('User login attempt failed.', ['id' => $user->id]); +``` - // '/foo/bar' + +#### `literal()` {.collection-method} -If necessary, you may specify how many directory levels you wish to trim from the string: +The `literal` function creates a new [stdClass](https://www.php.net/manual/en/class.stdclass.php) instance with the given named arguments as properties: - use Illuminate\Support\Str; +```php +$obj = literal( + name: 'Joe', + languages: ['PHP', 'Ruby'], +); - $string = Str::of('/foo/bar/baz')->dirname(2); +$obj->name; // 'Joe' +$obj->languages; // ['PHP', 'Ruby'] +``` - // '/foo' + +#### `logger()` {.collection-method} - -#### `excerpt` {.collection-method} +The `logger` function can be used to write a `debug` level message to the [log](/docs/{{version}}/logging): -The `excerpt` method extracts an excerpt from the string that matches the first instance of a phrase within that string: +```php +logger('Debug message'); +``` - use Illuminate\Support\Str; +An array of contextual data may also be passed to the function: - $excerpt = Str::of('This is my name')->excerpt('my', [ - 'radius' => 3 - ]); +```php +logger('User has logged in.', ['id' => $user->id]); +``` - // '...is my na...' +A [logger](/docs/{{version}}/logging) instance will be returned if no value is passed to the function: -The `radius` option, which defaults to `100`, allows you to define the number of characters that should appear on each side of the truncated string. +```php +logger()->error('You are not allowed here.'); +``` -In addition, you may use the `omission` option to change the string that will be prepended and appended to the truncated string: + +#### `method_field()` {.collection-method} - use Illuminate\Support\Str; +The `method_field` function generates an HTML `hidden` input field containing the spoofed value of the form's HTTP verb. For example, using [Blade syntax](/docs/{{version}}/blade): - $excerpt = Str::of('This is my name')->excerpt('name', [ - 'radius' => 3, - 'omission' => '(...) ' - ]); +```blade +
+ {{ method_field('DELETE') }} +
+``` - // '(...) my name' + +#### `now()` {.collection-method} - -#### `endsWith` {.collection-method} +The `now` function creates a new `Illuminate\Support\Carbon` instance for the current time: -The `endsWith` method determines if the given string ends with the given value: +```php +$now = now(); +``` - use Illuminate\Support\Str; + +#### `old()` {.collection-method} - $result = Str::of('This is my name')->endsWith('name'); +The `old` function [retrieves](/docs/{{version}}/requests#retrieving-input) an [old input](/docs/{{version}}/requests#old-input) value flashed into the session: - // true +```php +$value = old('value'); -You may also pass an array of values to determine if the given string ends with any of the values in the array: - - use Illuminate\Support\Str; - - $result = Str::of('This is my name')->endsWith(['name', 'foo']); - - // true - - $result = Str::of('This is my name')->endsWith(['this', 'foo']); - - // false - - -#### `exactly` {.collection-method} - -The `exactly` method determines if the given string is an exact match with another string: - - use Illuminate\Support\Str; - - $result = Str::of('Laravel')->exactly('Laravel'); - - // true - - -#### `explode` {.collection-method} - -The `explode` method splits the string by the given delimiter and returns a collection containing each section of the split string: - - use Illuminate\Support\Str; - - $collection = Str::of('foo bar baz')->explode(' '); - - // collect(['foo', 'bar', 'baz']) - - -#### `finish` {.collection-method} - -The `finish` method adds a single instance of the given value to a string if it does not already end with that value: - - use Illuminate\Support\Str; - - $adjusted = Str::of('this/string')->finish('/'); - - // this/string/ - - $adjusted = Str::of('this/string/')->finish('/'); - - // this/string/ - - -#### `is` {.collection-method} - -The `is` method determines if a given string matches a given pattern. Asterisks may be used as wildcard values - - use Illuminate\Support\Str; - - $matches = Str::of('foobar')->is('foo*'); - - // true +$value = old('value', 'default'); +``` - $matches = Str::of('foobar')->is('baz*'); +Since the "default value" provided as the second argument to the `old` function is often an attribute of an Eloquent model, Laravel allows you to simply pass the entire Eloquent model as the second argument to the `old` function. When doing so, Laravel will assume the first argument provided to the `old` function is the name of the Eloquent attribute that should be considered the "default value": - // false +```blade +{{ old('name', $user->name) }} - -#### `isAscii` {.collection-method} +// Is equivalent to... -The `isAscii` method determines if a given string is an ASCII string: +{{ old('name', $user) }} +``` - use Illuminate\Support\Str; + +#### `once()` {.collection-method} - $result = Str::of('Taylor')->isAscii(); +The `once` function executes the given callback and caches the result in memory for the duration of the request. Any subsequent calls to the `once` function with the same callback will return the previously cached result: - // true +```php +function random(): int +{ + return once(function () { + return random_int(1, 1000); + }); +} - $result = Str::of('ü')->isAscii(); +random(); // 123 +random(); // 123 (cached result) +random(); // 123 (cached result) +``` - // false +When the `once` function is executed from within an object instance, the cached result will be unique to that object instance: - -#### `isEmpty` {.collection-method} +```php + [1, 2, 3]); + } +} - use Illuminate\Support\Str; +$service = new NumberService; - $result = Str::of(' ')->trim()->isEmpty(); +$service->all(); +$service->all(); // (cached result) - // true +$secondService = new NumberService; - $result = Str::of('Laravel')->trim()->isEmpty(); +$secondService->all(); +$secondService->all(); // (cached result) +``` + +#### `optional()` {.collection-method} - // false +The `optional` function accepts any argument and allows you to access properties or call methods on that object. If the given object is `null`, properties and methods will return `null` instead of causing an error: - -#### `isNotEmpty` {.collection-method} +```php +return optional($user->address)->street; -The `isNotEmpty` method determines if the given string is not empty: +{!! old('name', optional($user)->name) !!} +``` +The `optional` function also accepts a closure as its second argument. The closure will be invoked if the value provided as the first argument is not null: - use Illuminate\Support\Str; +```php +return optional(User::find($id), function (User $user) { + return $user->name; +}); +``` - $result = Str::of(' ')->trim()->isNotEmpty(); + +#### `policy()` {.collection-method} - // false +The `policy` method retrieves a [policy](/docs/{{version}}/authorization#creating-policies) instance for a given class: - $result = Str::of('Laravel')->trim()->isNotEmpty(); +```php +$policy = policy(App\Models\User::class); +``` - // true + +#### `redirect()` {.collection-method} - -#### `isUuid` {.collection-method} +The `redirect` function returns a [redirect HTTP response](/docs/{{version}}/responses#redirects), or returns the redirector instance if called with no arguments: -The `isUuid` method determines if a given string is a UUID: +```php +return redirect($to = null, $status = 302, $headers = [], $secure = null); - use Illuminate\Support\Str; +return redirect('/home'); - $result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid(); +return redirect()->route('route.name'); +``` - // true + +#### `report()` {.collection-method} - $result = Str::of('Taylor')->isUuid(); +The `report` function will report an exception using your [exception handler](/docs/{{version}}/errors#handling-exceptions): - // false +```php +report($e); +``` - -#### `kebab` {.collection-method} +The `report` function also accepts a string as an argument. When a string is given to the function, the function will create an exception with the given string as its message: -The `kebab` method converts the given string to `kebab-case`: +```php +report('Something went wrong.'); +``` - use Illuminate\Support\Str; + +#### `report_if()` {.collection-method} - $converted = Str::of('fooBar')->kebab(); +The `report_if` function will report an exception using your [exception handler](/docs/{{version}}/errors#handling-exceptions) if a given boolean expression evaluates to `true`: - // foo-bar +```php +report_if($shouldReport, $e); - -#### `length` {.collection-method} +report_if($shouldReport, 'Something went wrong.'); +``` -The `length` method returns the length of the given string: + +#### `report_unless()` {.collection-method} - use Illuminate\Support\Str; +The `report_unless` function will report an exception using your [exception handler](/docs/{{version}}/errors#handling-exceptions) if a given boolean expression evaluates to `false`: - $length = Str::of('Laravel')->length(); +```php +report_unless($reportingDisabled, $e); - // 7 +report_unless($reportingDisabled, 'Something went wrong.'); +``` - -#### `limit` {.collection-method} + +#### `request()` {.collection-method} -The `limit` method truncates the given string to the specified length: +The `request` function returns the current [request](/docs/{{version}}/requests) instance or obtains an input field's value from the current request: - use Illuminate\Support\Str; +```php +$request = request(); - $truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20); +$value = request('key', $default); +``` - // The quick brown fox... + +#### `rescue()` {.collection-method} -You may also pass a second argument to change the string that will be appended to the end of the truncated string: +The `rescue` function executes the given closure and catches any exceptions that occur during its execution. All exceptions that are caught will be sent to your [exception handler](/docs/{{version}}/errors#handling-exceptions); however, the request will continue processing: - use Illuminate\Support\Str; +```php +return rescue(function () { + return $this->method(); +}); +``` - $truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)'); +You may also pass a second argument to the `rescue` function. This argument will be the "default" value that should be returned if an exception occurs while executing the closure: - // The quick brown fox (...) +```php +return rescue(function () { + return $this->method(); +}, false); + +return rescue(function () { + return $this->method(); +}, function () { + return $this->failure(); +}); +``` - -#### `lower` {.collection-method} +A `report` argument may be provided to the `rescue` function to determine if the exception should be reported via the `report` function: -The `lower` method converts the given string to lowercase: +```php +return rescue(function () { + return $this->method(); +}, report: function (Throwable $throwable) { + return $throwable instanceof InvalidArgumentException; +}); +``` - use Illuminate\Support\Str; + +#### `resolve()` {.collection-method} - $result = Str::of('LARAVEL')->lower(); +The `resolve` function resolves a given class or interface name to an instance using the [service container](/docs/{{version}}/container): - // 'laravel' +```php +$api = resolve('HelpSpot\API'); +``` - -#### `ltrim` {.collection-method} + +#### `response()` {.collection-method} -The `ltrim` method trims the left side of the string: +The `response` function creates a [response](/docs/{{version}}/responses) instance or obtains an instance of the response factory: - use Illuminate\Support\Str; +```php +return response('Hello World', 200, $headers); - $string = Str::of(' Laravel ')->ltrim(); +return response()->json(['foo' => 'bar'], 200, $headers); +``` - // 'Laravel ' + +#### `retry()` {.collection-method} - $string = Str::of('/Laravel/')->ltrim('/'); +The `retry` function attempts to execute the given callback until the given maximum attempt threshold is met. If the callback does not throw an exception, its return value will be returned. If the callback throws an exception, it will automatically be retried. If the maximum attempt count is exceeded, the exception will be thrown: - // 'Laravel/' +```php +return retry(5, function () { + // Attempt 5 times while resting 100ms between attempts... +}, 100); +``` - -#### `markdown` {.collection-method} +If you would like to manually calculate the number of milliseconds to sleep between attempts, you may pass a closure as the third argument to the `retry` function: -The `markdown` method converts GitHub flavored Markdown into HTML: +```php +use Exception; - use Illuminate\Support\Str; +return retry(5, function () { + // ... +}, function (int $attempt, Exception $exception) { + return $attempt * 100; +}); +``` - $html = Str::of('# Laravel')->markdown(); +For convenience, you may provide an array as the first argument to the `retry` function. This array will be used to determine how many milliseconds to sleep between subsequent attempts: - //

Laravel

+```php +return retry([100, 200], function () { + // Sleep for 100ms on first retry, 200ms on second retry... +}); +``` - $html = Str::of('# Taylor Otwell')->markdown([ - 'html_input' => 'strip', - ]); +To only retry under specific conditions, you may pass a closure as the fourth argument to the `retry` function: - //

Taylor Otwell

+```php +use App\Exceptions\TemporaryException; +use Exception; + +return retry(5, function () { + // ... +}, 100, function (Exception $exception) { + return $exception instanceof TemporaryException; +}); +``` - -#### `mask` {.collection-method} + +#### `session()` {.collection-method} -The `mask` method masks a portion of a string with a repeated character, and may be used to obfuscate segments of strings such as email addresses and phone numbers: +The `session` function may be used to get or set [session](/docs/{{version}}/session) values: - use Illuminate\Support\Str; +```php +$value = session('key'); +``` - $string = Str::of('taylor@example.com')->mask('*', 3); +You may set values by passing an array of key / value pairs to the function: - // tay*************** +```php +session(['chairs' => 7, 'instruments' => 3]); +``` -If needed, you provide a negative number as the third argument to the `mask` method, which will instruct the method to begin masking at the given distance from the end of the string: +The session store will be returned if no value is passed to the function: - $string = Str::of('taylor@example.com')->mask('*', -15, 3); +```php +$value = session()->get('key'); - // tay***@example.com +session()->put('key', $value); +``` - -#### `match` {.collection-method} + +#### `tap()` {.collection-method} -The `match` method will return the portion of a string that matches a given regular expression pattern: +The `tap` function accepts two arguments: an arbitrary `$value` and a closure. The `$value` will be passed to the closure and then be returned by the `tap` function. The return value of the closure is irrelevant: - use Illuminate\Support\Str; +```php +$user = tap(User::first(), function (User $user) { + $user->name = 'Taylor'; - $result = Str::of('foo bar')->match('/bar/'); + $user->save(); +}); +``` - // 'bar' +If no closure is passed to the `tap` function, you may call any method on the given `$value`. The return value of the method you call will always be `$value`, regardless of what the method actually returns in its definition. For example, the Eloquent `update` method typically returns an integer. However, we can force the method to return the model itself by chaining the `update` method call through the `tap` function: - $result = Str::of('foo bar')->match('/foo (.*)/'); +```php +$user = tap($user)->update([ + 'name' => $name, + 'email' => $email, +]); +``` - // 'bar' +To add a `tap` method to a class, you may add the `Illuminate\Support\Traits\Tappable` trait to the class. The `tap` method of this trait accepts a Closure as its only argument. The object instance itself will be passed to the Closure and then be returned by the `tap` method: - -#### `matchAll` {.collection-method} +```php +return $user->tap(function (User $user) { + // ... +}); +``` -The `matchAll` method will return a collection containing the portions of a string that match a given regular expression pattern: + +#### `throw_if()` {.collection-method} - use Illuminate\Support\Str; +The `throw_if` function throws the given exception if a given boolean expression evaluates to `true`: - $result = Str::of('bar foo bar')->matchAll('/bar/'); +```php +throw_if(! Auth::user()->isAdmin(), AuthorizationException::class); - // collect(['bar', 'bar']) +throw_if( + ! Auth::user()->isAdmin(), + AuthorizationException::class, + 'You are not allowed to access this page.' +); +``` -If you specify a matching group within the expression, Laravel will return a collection of that group's matches: + +#### `throw_unless()` {.collection-method} - use Illuminate\Support\Str; +The `throw_unless` function throws the given exception if a given boolean expression evaluates to `false`: - $result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/'); +```php +throw_unless(Auth::user()->isAdmin(), AuthorizationException::class); - // collect(['un', 'ly']); +throw_unless( + Auth::user()->isAdmin(), + AuthorizationException::class, + 'You are not allowed to access this page.' +); +``` -If no matches are found, an empty collection will be returned. + +#### `today()` {.collection-method} - -#### `padBoth` {.collection-method} +The `today` function creates a new `Illuminate\Support\Carbon` instance for the current date: -The `padBoth` method wraps PHP's `str_pad` function, padding both sides of a string with another string until the final string reaches the desired length: +```php +$today = today(); +``` - use Illuminate\Support\Str; + +#### `trait_uses_recursive()` {.collection-method} - $padded = Str::of('James')->padBoth(10, '_'); +The `trait_uses_recursive` function returns all traits used by a trait: - // '__James___' +```php +$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class); +``` - $padded = Str::of('James')->padBoth(10); + +#### `transform()` {.collection-method} - // ' James ' +The `transform` function executes a closure on a given value if the value is not [blank](#method-blank) and then returns the return value of the closure: - -#### `padLeft` {.collection-method} +```php +$callback = function (int $value) { + return $value * 2; +}; -The `padLeft` method wraps PHP's `str_pad` function, padding the left side of a string with another string until the final string reaches the desired length: +$result = transform(5, $callback); - use Illuminate\Support\Str; +// 10 +``` - $padded = Str::of('James')->padLeft(10, '-='); +A default value or closure may be passed as the third argument to the function. This value will be returned if the given value is blank: - // '-=-=-James' +```php +$result = transform(null, $callback, 'The value is blank'); - $padded = Str::of('James')->padLeft(10); +// The value is blank +``` - // ' James' + +#### `validator()` {.collection-method} - -#### `padRight` {.collection-method} +The `validator` function creates a new [validator](/docs/{{version}}/validation) instance with the given arguments. You may use it as an alternative to the `Validator` facade: -The `padRight` method wraps PHP's `str_pad` function, padding the right side of a string with another string until the final string reaches the desired length: +```php +$validator = validator($data, $rules, $messages); +``` - use Illuminate\Support\Str; + +#### `value()` {.collection-method} - $padded = Str::of('James')->padRight(10, '-'); +The `value` function returns the value it is given. However, if you pass a closure to the function, the closure will be executed and its returned value will be returned: - // 'James-----' +```php +$result = value(true); - $padded = Str::of('James')->padRight(10); +// true - // 'James ' +$result = value(function () { + return false; +}); - -#### `pipe` {.collection-method} +// false +``` -The `pipe` method allows you to transform the string by passing its current value to the given callable: +Additional arguments may be passed to the `value` function. If the first argument is a closure then the additional parameters will be passed to the closure as arguments, otherwise they will be ignored: - use Illuminate\Support\Str; +```php +$result = value(function (string $name) { + return $name; +}, 'Taylor'); - $hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: '); +// 'Taylor' +``` - // 'Checksum: a5c95b86291ea299fcbe64458ed12702' + +#### `view()` {.collection-method} - $closure = Str::of('foo')->pipe(function ($str) { - return 'bar'; - }); +The `view` function retrieves a [view](/docs/{{version}}/views) instance: - // 'bar' +```php +return view('auth.login'); +``` - -#### `plural` {.collection-method} + +#### `with()` {.collection-method} -The `plural` method converts a singular word string to its plural form. This function currently only supports the English language: +The `with` function returns the value it is given. If a closure is passed as the second argument to the function, the closure will be executed and its returned value will be returned: - use Illuminate\Support\Str; +```php +$callback = function (mixed $value) { + return is_numeric($value) ? $value * 2 : 0; +}; - $plural = Str::of('car')->plural(); +$result = with(5, $callback); - // cars +// 10 - $plural = Str::of('child')->plural(); +$result = with(null, $callback); - // children +// 0 -You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string: +$result = with(5, null); - use Illuminate\Support\Str; +// 5 +``` - $plural = Str::of('child')->plural(2); + +#### `when()` {.collection-method} - // children +The `when` function returns the value it is given if a given condition evaluates to `true`. Otherwise, `null` is returned. If a closure is passed as the second argument to the function, the closure will be executed and its returned value will be returned: - $plural = Str::of('child')->plural(1); +```php +$value = when(true, 'Hello World'); - // child +$value = when(true, fn () => 'Hello World'); +``` - -#### `prepend` {.collection-method} +The `when` function is primarily useful for conditionally rendering HTML attributes: -The `prepend` method prepends the given values onto the string: +```blade +
+ ... +
+``` - use Illuminate\Support\Str; + +## Other Utilities - $string = Str::of('Framework')->prepend('Laravel '); + +### Benchmarking - // Laravel Framework +Sometimes you may wish to quickly test the performance of certain parts of your application. On those occasions, you may utilize the `Benchmark` support class to measure the number of milliseconds it takes for the given callbacks to complete: - -#### `remove` {.collection-method} +```php + User::find(1)); // 0.1 ms - $string = Str::of('Arkansas is quite beautiful!')->remove('quite'); +Benchmark::dd([ + 'Scenario 1' => fn () => User::count(), // 0.5 ms + 'Scenario 2' => fn () => User::all()->count(), // 20.0 ms +]); +``` - // Arkansas is beautiful! +By default, the given callbacks will be executed once (one iteration), and their duration will be displayed in the browser / console. -You may also pass `false` as a second parameter to ignore case when removing strings. +To invoke a callback more than once, you may specify the number of iterations that the callback should be invoked as the second argument to the method. When executing a callback more than once, the `Benchmark` class will return the average number of milliseconds it took to execute the callback across all iterations: - -#### `replace` {.collection-method} +```php +Benchmark::dd(fn () => User::count(), iterations: 10); // 0.5 ms +``` -The `replace` method replaces a given string within the string: +Sometimes, you may want to benchmark the execution of a callback while still obtaining the value returned by the callback. The `value` method will return a tuple containing the value returned by the callback and the number of milliseconds it took to execute the callback: - use Illuminate\Support\Str; +```php +[$count, $duration] = Benchmark::value(fn () => User::count()); +``` - $replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x'); + +### Dates - // Laravel 7.x +Laravel includes [Carbon](https://carbon.nesbot.com/docs/), a powerful date and time manipulation library. To create a new `Carbon` instance, you may invoke the `now` function. This function is globally available within your Laravel application: - -#### `replaceArray` {.collection-method} +```php +$now = now(); +``` -The `replaceArray` method replaces a given value in the string sequentially using an array: +Or, you may create a new `Carbon` instance using the `Illuminate\Support\Carbon` class: - use Illuminate\Support\Str; +```php +use Illuminate\Support\Carbon; - $string = 'The event will take place between ? and ?'; +$now = Carbon::now(); +``` - $replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']); +For a thorough discussion of Carbon and its features, please consult the [official Carbon documentation](https://carbon.nesbot.com/docs/). - // The event will take place between 8:30 and 9:00 + +### Deferred Functions - -#### `replaceFirst` {.collection-method} +While Laravel's [queued jobs](/docs/{{version}}/queues) allow you to queue tasks for background processing, sometimes you may have simple tasks you would like to defer without configuring or maintaining a long-running queue worker. -The `replaceFirst` method replaces the first occurrence of a given value in a string: +Deferred functions allow you to defer the execution of a closure until after the HTTP response has been sent to the user, keeping your application feeling fast and responsive. To defer the execution of a closure, simply pass the closure to the `Illuminate\Support\defer` function: - use Illuminate\Support\Str; +```php +use App\Services\Metrics; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Route; +use function Illuminate\Support\defer; - $replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a'); +Route::post('/orders', function (Request $request) { + // Create order... - // a quick brown fox jumps over the lazy dog + defer(fn () => Metrics::reportOrder($order)); - -#### `replaceLast` {.collection-method} + return $order; +}); +``` -The `replaceLast` method replaces the last occurrence of a given value in a string: +By default, deferred functions will only be executed if the HTTP response, Artisan command, or queued job from which `Illuminate\Support\defer` is invoked completes successfully. This means that deferred functions will not be executed if a request results in a `4xx` or `5xx` HTTP response. If you would like a deferred function to always execute, you may chain the `always` method onto your deferred function: - use Illuminate\Support\Str; +```php +defer(fn () => Metrics::reportOrder($order))->always(); +``` - $replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a'); +> [!WARNING] +> If you have the [Swoole PHP extension](https://www.php.net/manual/en/book.swoole.php) installed, Laravel's `defer` function may conflict with Swoole's own global `defer` function, leading to web server errors. Make sure you call Laravel's `defer` helper by explicitly namespacing it: `use function Illuminate\Support\defer;` - // the quick brown fox jumps over a lazy dog + +#### Cancelling Deferred Functions - -#### `replaceMatches` {.collection-method} +If you need to cancel a deferred function before it is executed, you can use the `forget` method to cancel the function by its name. To name a deferred function, provide a second argument to the `Illuminate\Support\defer` function: -The `replaceMatches` method replaces all portions of a string matching a pattern with the given replacement string: +```php +defer(fn () => Metrics::report(), 'reportMetrics'); - use Illuminate\Support\Str; +defer()->forget('reportMetrics'); +``` - $replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '') + +#### Disabling Deferred Functions in Tests - // '15015551000' +When writing tests, it may be useful to disable deferred functions. You may call `withoutDefer` in your test to instruct Laravel to invoke all deferred functions immediately: -The `replaceMatches` method also accepts a closure that will be invoked with each portion of the string matching the given pattern, allowing you to perform the replacement logic within the closure and return the replaced value: +```php tab=Pest +test('without defer', function () { + $this->withoutDefer(); - use Illuminate\Support\Str; + // ... +}); +``` - $replaced = Str::of('123')->replaceMatches('/\d/', function ($match) { - return '['.$match[0].']'; - }); +```php tab=PHPUnit +use Tests\TestCase; - // '[1][2][3]' +class ExampleTest extends TestCase +{ + public function test_without_defer(): void + { + $this->withoutDefer(); - -#### `rtrim` {.collection-method} + // ... + } +} +``` -The `rtrim` method trims the right side of the given string: +If you would like to disable deferred functions for all tests within a test case, you may call the `withoutDefer` method from the `setUp` method on your base `TestCase` class: - use Illuminate\Support\Str; +```php +rtrim(); +namespace Tests; - // ' Laravel' +use Illuminate\Foundation\Testing\TestCase as BaseTestCase; - $string = Str::of('/Laravel/')->rtrim('/'); +abstract class TestCase extends BaseTestCase +{ + protected function setUp(): void// [tl! add:start] + { + parent::setUp(); - // '/Laravel' + $this->withoutDefer(); + }// [tl! add:end] +} +``` - -#### `scan` {.collection-method} + +### Lottery -The `scan` method parses input from a string into a collection according to a format supported by the [`sscanf` PHP function](https://www.php.net/manual/en/function.sscanf.php): +Laravel's lottery class may be used to execute callbacks based on a set of given odds. This can be particularly useful when you only want to execute code for a percentage of your incoming requests: - use Illuminate\Support\Str; +```php +use Illuminate\Support\Lottery; - $collection = Str::of('filename.jpg')->scan('%[^.].%s'); +Lottery::odds(1, 20) + ->winner(fn () => $user->won()) + ->loser(fn () => $user->lost()) + ->choose(); +``` - // collect(['filename', 'jpg']) +You may combine Laravel's lottery class with other Laravel features. For example, you may wish to only report a small percentage of slow queries to your exception handler. And, since the lottery class is callable, we may pass an instance of the class into any method that accepts callables: - -#### `singular` {.collection-method} +```php +use Carbon\CarbonInterval; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Lottery; + +DB::whenQueryingForLongerThan( + CarbonInterval::seconds(2), + Lottery::odds(1, 100)->winner(fn () => report('Querying > 2 seconds.')), +); +``` -The `singular` method converts a string to its singular form. This function currently only supports the English language: + +#### Testing Lotteries - use Illuminate\Support\Str; +Laravel provides some simple methods to allow you to easily test your application's lottery invocations: - $singular = Str::of('cars')->singular(); +```php +// Lottery will always win... +Lottery::alwaysWin(); - // car +// Lottery will always lose... +Lottery::alwaysLose(); - $singular = Str::of('children')->singular(); +// Lottery will win then lose, and finally return to normal behavior... +Lottery::fix([true, false]); - // child +// Lottery will return to normal behavior... +Lottery::determineResultsNormally(); +``` - -#### `slug` {.collection-method} + +### Pipeline -The `slug` method generates a URL friendly "slug" from the given string: +Laravel's `Pipeline` facade provides a convenient way to "pipe" a given input through a series of invokable classes, closures, or callables, giving each class the opportunity to inspect or modify the input and invoke the next callable in the pipeline: - use Illuminate\Support\Str; +```php +use Closure; +use App\Models\User; +use Illuminate\Support\Facades\Pipeline; + +$user = Pipeline::send($user) + ->through([ + function (User $user, Closure $next) { + // ... + + return $next($user); + }, + function (User $user, Closure $next) { + // ... + + return $next($user); + }, + ]) + ->then(fn (User $user) => $user); +``` - $slug = Str::of('Laravel Framework')->slug('-'); +As you can see, each invokable class or closure in the pipeline is provided the input and a `$next` closure. Invoking the `$next` closure will invoke the next callable in the pipeline. As you may have noticed, this is very similar to [middleware](/docs/{{version}}/middleware). - // laravel-framework +When the last callable in the pipeline invokes the `$next` closure, the callable provided to the `then` method will be invoked. Typically, this callable will simply return the given input. For convenience, if you simply want to return the input after it has been processed, you may use the `thenReturn` method. - -#### `snake` {.collection-method} +Of course, as discussed previously, you are not limited to providing closures to your pipeline. You may also provide invokable classes. If a class name is provided, the class will be instantiated via Laravel's [service container](/docs/{{version}}/container), allowing dependencies to be injected into the invokable class: -The `snake` method converts the given string to `snake_case`: +```php +$user = Pipeline::send($user) + ->through([ + GenerateProfilePhoto::class, + ActivateSubscription::class, + SendWelcomeEmail::class, + ]) + ->thenReturn(); +``` - use Illuminate\Support\Str; +The `withinTransaction` method may be invoked on the pipeline to automatically wrap all steps of the pipeline within a single database transaction: - $converted = Str::of('fooBar')->snake(); +```php +$user = Pipeline::send($user) + ->withinTransaction() + ->through([ + ProcessOrder::class, + TransferFunds::class, + UpdateInventory::class, + ]) + ->thenReturn(); +``` - // foo_bar + +### Sleep - -#### `split` {.collection-method} +Laravel's `Sleep` class is a light-weight wrapper around PHP's native `sleep` and `usleep` functions, offering greater testability while also exposing a developer friendly API for working with time: -The `split` method splits a string into a collection using a regular expression: +```php +use Illuminate\Support\Sleep; - use Illuminate\Support\Str; +$waiting = true; - $segments = Str::of('one, two, three')->split('/[\s,]+/'); +while ($waiting) { + Sleep::for(1)->second(); - // collect(["one", "two", "three"]) + $waiting = /* ... */; +} +``` - -#### `start` {.collection-method} +The `Sleep` class offers a variety of methods that allow you to work with different units of time: -The `start` method adds a single instance of the given value to a string if it does not already start with that value: +```php +// Return a value after sleeping... +$result = Sleep::for(1)->second()->then(fn () => 1 + 1); - use Illuminate\Support\Str; +// Sleep while a given value is true... +Sleep::for(1)->second()->while(fn () => shouldKeepSleeping()); - $adjusted = Str::of('this/string')->start('/'); +// Pause execution for 90 seconds... +Sleep::for(1.5)->minutes(); - // /this/string +// Pause execution for 2 seconds... +Sleep::for(2)->seconds(); - $adjusted = Str::of('/this/string')->start('/'); +// Pause execution for 500 milliseconds... +Sleep::for(500)->milliseconds(); - // /this/string +// Pause execution for 5,000 microseconds... +Sleep::for(5000)->microseconds(); - -#### `startsWith` {.collection-method} +// Pause execution until a given time... +Sleep::until(now()->addMinute()); -The `startsWith` method determines if the given string begins with the given value: +// Alias of PHP's native "sleep" function... +Sleep::sleep(2); - use Illuminate\Support\Str; +// Alias of PHP's native "usleep" function... +Sleep::usleep(5000); +``` - $result = Str::of('This is my name')->startsWith('This'); +To easily combine units of time, you may use the `and` method: - // true +```php +Sleep::for(1)->second()->and(10)->milliseconds(); +``` - -#### `studly` {.collection-method} + +#### Testing Sleep -The `studly` method converts the given string to `StudlyCase`: +When testing code that utilizes the `Sleep` class or PHP's native sleep functions, your test will pause execution. As you might expect, this makes your test suite significantly slower. For example, imagine you are testing the following code: - use Illuminate\Support\Str; +```php +$waiting = /* ... */; - $converted = Str::of('foo_bar')->studly(); +$seconds = 1; - // FooBar +while ($waiting) { + Sleep::for($seconds++)->seconds(); - -#### `substr` {.collection-method} + $waiting = /* ... */; +} +``` -The `substr` method returns the portion of the string specified by the given start and length parameters: +Typically, testing this code would take _at least_ one second. Luckily, the `Sleep` class allows us to "fake" sleeping so that our test suite stays fast: - use Illuminate\Support\Str; +```php tab=Pest +it('waits until ready', function () { + Sleep::fake(); - $string = Str::of('Laravel Framework')->substr(8); + // ... +}); +``` - // Framework +```php tab=PHPUnit +public function test_it_waits_until_ready() +{ + Sleep::fake(); - $string = Str::of('Laravel Framework')->substr(8, 5); + // ... +} +``` - // Frame +When faking the `Sleep` class, the actual execution pause is bypassed, leading to a substantially faster test. - -#### `substrReplace` {.collection-method} +Once the `Sleep` class has been faked, it is possible to make assertions against the expected "sleeps" that should have occurred. To illustrate this, let's imagine we are testing code that pauses execution three times, with each pause increasing by a single second. Using the `assertSequence` method, we can assert that our code "slept" for the proper amount of time while keeping our test fast: -The `substrReplace` method replaces text within a portion of a string, starting at the position specified by the second argument and replacing the number of characters specified by the third argument. Passing `0` to the method's third argument will insert the string at the specified position without replacing any of the existing characters in the string: +```php tab=Pest +it('checks if ready three times', function () { + Sleep::fake(); - use Illuminate\Support\Str; + // ... - $string = Str::of('1300')->substrReplace(':', 2); + Sleep::assertSequence([ + Sleep::for(1)->second(), + Sleep::for(2)->seconds(), + Sleep::for(3)->seconds(), + ]); +} +``` - // 13: +```php tab=PHPUnit +public function test_it_checks_if_ready_three_times() +{ + Sleep::fake(); - $string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0); + // ... - // The Laravel Framework + Sleep::assertSequence([ + Sleep::for(1)->second(), + Sleep::for(2)->seconds(), + Sleep::for(3)->seconds(), + ]); +} +``` - -#### `swap` {.collection-method} +Of course, the `Sleep` class offers a variety of other assertions you may use when testing: -The `swap` method replaces multiple values in the string using PHP's `strtr` function: +```php +use Carbon\CarbonInterval as Duration; +use Illuminate\Support\Sleep; - use Illuminate\Support\Str; +// Assert that sleep was called 3 times... +Sleep::assertSleptTimes(3); - $string = Str::of('Tacos are great!') - ->swap([ - 'Tacos' => 'Burritos', - 'great' => 'fantastic', - ]); +// Assert against the duration of sleep... +Sleep::assertSlept(function (Duration $duration): bool { + return /* ... */; +}, times: 1); - // Burritos are fantastic! +// Assert that the Sleep class was never invoked... +Sleep::assertNeverSlept(); - -#### `tap` {.collection-method} +// Assert that, even if Sleep was called, no execution paused occurred... +Sleep::assertInsomniac(); +``` -The `tap` method passes the string to the given closure, allowing you to examine and interact with the string while not affecting the string itself. The original string is returned by the `tap` method regardless of what is returned by the closure: +Sometimes it may be useful to perform an action whenever a fake sleep occurs. To achieve this, you may provide a callback to the `whenFakingSleep` method. In the following example, we use Laravel's [time manipulation helpers](/docs/{{version}}/mocking#interacting-with-time) to instantly progress time by the duration of each sleep: - use Illuminate\Support\Str; +```php +use Carbon\CarbonInterval as Duration; - $string = Str::of('Laravel') - ->append(' Framework') - ->tap(function ($string) { - dump('String after append: ' . $string); - }) - ->upper(); +$this->freezeTime(); - // LARAVEL FRAMEWORK +Sleep::fake(); - -#### `test` {.collection-method} +Sleep::whenFakingSleep(function (Duration $duration) { + // Progress time when faking sleep... + $this->travel($duration->totalMilliseconds)->milliseconds(); +}); +``` -The `test` method determines if a string matches the given regular expression pattern: +As progressing time is a common requirement, the `fake` method accepts a `syncWithCarbon` argument to keep Carbon in sync when sleeping within a test: - use Illuminate\Support\Str; +```php +Sleep::fake(syncWithCarbon: true); - $result = Str::of('Laravel Framework')->test('/Laravel/'); +$start = now(); - // true +Sleep::for(1)->second(); - -#### `title` {.collection-method} +$start->diffForHumans(); // 1 second ago +``` -The `title` method converts the given string to `Title Case`: +Laravel uses the `Sleep` class internally whenever it is pausing execution. For example, the [retry](#method-retry) helper uses the `Sleep` class when sleeping, allowing for improved testability when using that helper. - use Illuminate\Support\Str; + +### Timebox - $converted = Str::of('a nice title uses the correct case')->title(); +Laravel's `Timebox` class ensures that the given callback always takes a fixed amount of time to execute, even if its actual execution completes sooner. This is particularly useful for cryptographic operations and user authentication checks, where attackers might exploit variations in execution time to infer sensitive information. - // A Nice Title Uses The Correct Case +If the execution exceeds the fixed duration, `Timebox` has no effect. It is up to the developer to choose a sufficiently long time as the fixed duration to account for worst-case scenarios. - -#### `trim` {.collection-method} +The call method accepts a closure and a time limit in microseconds, and then executes the closure and waits until the time limit is reached: -The `trim` method trims the given string: +```php +use Illuminate\Support\Timebox; - use Illuminate\Support\Str; +(new Timebox)->call(function ($timebox) { + // ... +}, microseconds: 10000); +``` - $string = Str::of(' Laravel ')->trim(); +If an exception is thrown within the closure, this class will respect the defined delay and re-throw the exception after the delay. - // 'Laravel' + +### URI - $string = Str::of('/Laravel/')->trim('/'); +Laravel's `Uri` class provides a convenient and fluent interface for creating and manipulating URIs. This class wraps the functionality provided by the underlying League URI package and integrates seamlessly with Laravel's routing system. - // 'Laravel' +You can create a `Uri` instance easily using static methods: - -#### `ucfirst` {.collection-method} +```php +use App\Http\Controllers\UserController; +use App\Http\Controllers\InvokableController; +use Illuminate\Support\Uri; + +// Generate a URI instance from the given string... +$uri = Uri::of('https://example.com/path'); + +// Generate URI instances to paths, named routes, or controller actions... +$uri = Uri::to('/dashboard'); +$uri = Uri::route('users.show', ['user' => 1]); +$uri = Uri::signedRoute('users.show', ['user' => 1]); +$uri = Uri::temporarySignedRoute('user.index', now()->addMinutes(5)); +$uri = Uri::action([UserController::class, 'index']); +$uri = Uri::action(InvokableController::class); + +// Generate a URI instance from the current request URL... +$uri = $request->uri(); +``` -The `ucfirst` method returns the given string with the first character capitalized: +Once you have a URI instance, you can fluently modify it: - use Illuminate\Support\Str; +```php +$uri = Uri::of('https://example.com/') + ->withScheme('http') + ->withHost('test.com') + ->withPort(8000) + ->withPath('/users') + ->withQuery(['page' => 2]) + ->withFragment('section-1'); +``` - $string = Str::of('foo bar')->ucfirst(); + +#### Inspecting URIs - // Foo bar +The `Uri` class also allows you to easily inspect the various components of the underlying URI: - -#### `upper` {.collection-method} +```php +$scheme = $uri->scheme(); +$host = $uri->host(); +$port = $uri->port(); +$path = $uri->path(); +$segments = $uri->pathSegments(); +$query = $uri->query(); +$fragment = $uri->fragment(); +``` -The `upper` method converts the given string to uppercase: + +#### Manipulating Query Strings - use Illuminate\Support\Str; +The `Uri` class offers several methods that may be used to manipulate a URI's query string. The `withQuery` method may be used to merge additional query string parameters into the existing query string: - $adjusted = Str::of('laravel')->upper(); +```php +$uri = $uri->withQuery(['sort' => 'name']); +``` - // LARAVEL +The `withQueryIfMissing` method may be used to merge additional query string parameters into the existing query string if the given keys do not already exist in the query string: - -#### `when` {.collection-method} +```php +$uri = $uri->withQueryIfMissing(['page' => 1]); +``` -The `when` method invokes the given closure if a given condition is `true`. The closure will receive the fluent string instance: +The `replaceQuery` method may be used to complete replace the existing query string with a new one: - use Illuminate\Support\Str; +```php +$uri = $uri->replaceQuery(['page' => 1]); +``` - $string = Str::of('Taylor') - ->when(true, function ($string) { - return $string->append(' Otwell'); - }); +The `pushOntoQuery` method may be used to push additional parameters onto a query string parameter that has an array value: - // 'Taylor Otwell' +```php +$uri = $uri->pushOntoQuery('filter', ['active', 'pending']); +``` -If necessary, you may pass another closure as the third parameter to the `when` method. This closure will execute if the condition parameter evaluates to `false`. +The `withoutQuery` method may be used to remove parameters from the query string: - -#### `whenContains` {.collection-method} +```php +$uri = $uri->withoutQuery(['page']); +``` -The `whenContains` method invokes the given closure if the string contains the given value. The closure will receive the fluent string instance: + +#### Generating Responses From URIs - use Illuminate\Support\Str; +The `redirect` method may be used to generate a `RedirectResponse` instance to the given URI: - $string = Str::of('tony stark') - ->whenContains('tony', function ($string) { - return $string->title(); - }); +```php +$uri = Uri::of('https://example.com/'); - // 'Tony Stark' +return $uri->redirect(); +``` -If necessary, you may pass another closure as the third parameter to the `when` method. This closure will execute if the string does not contain the given value. +Or, you may simply return the `Uri` instance from a route or controller action, which will automatically generate a redirect response to the returned URI: -You may also pass an array of values to determine if the given string contains any of the values in the array: +```php +use Illuminate\Support\Facades\Route; +use Illuminate\Support\Uri; - use Illuminate\Support\Str; - - $string = Str::of('tony stark') - ->whenContains(['tony', 'hulk'], function ($string) { - return $string->title(); - }); - - // Tony Stark - - -#### `whenContainsAll` {.collection-method} - -The `whenContainsAll` method invokes the given closure if the string contains all of the given sub-strings. The closure will receive the fluent string instance: - - use Illuminate\Support\Str; - - $string = Str::of('tony stark') - ->whenContainsAll(['tony', 'stark'], function ($string) { - return $string->title(); - }); - - // 'Tony Stark' - -If necessary, you may pass another closure as the third parameter to the `when` method. This closure will execute if the condition parameter evaluates to `false`. - - -#### `whenEmpty` {.collection-method} - -The `whenEmpty` method invokes the given closure if the string is empty. If the closure returns a value, that value will also be returned by the `whenEmpty` method. If the closure does not return a value, the fluent string instance will be returned: - - use Illuminate\Support\Str; - - $string = Str::of(' ')->whenEmpty(function ($string) { - return $string->trim()->prepend('Laravel'); - }); - - // 'Laravel' - - -#### `whenNotEmpty` {.collection-method} - -The `whenNotEmpty` method invokes the given closure if the string is not empty. If the closure returns a value, that value will also be returned by the `whenNotEmpty` method. If the closure does not return a value, the fluent string instance will be returned: - - use Illuminate\Support\Str; - - $string = Str::of('Framework')->whenNotEmpty(function ($string) { - return $string->prepend('Laravel '); - }); - - // 'Laravel Framework' - - -#### `whenStartsWith` {.collection-method} - -The `whenStartsWith` method invokes the given closure if the string starts with the given sub-string. The closure will receive the fluent string instance: - - use Illuminate\Support\Str; - - $string = Str::of('disney world')->whenStartsWith('disney', function ($string) { - return $string->title(); - }); - - // 'Disney World' - - -#### `whenEndsWith` {.collection-method} - -The `whenEndsWith` method invokes the given closure if the string ends with the given sub-string. The closure will receive the fluent string instance: - - use Illuminate\Support\Str; - - $string = Str::of('disney world')->whenEndsWith('world', function ($string) { - return $string->title(); - }); - - // 'Disney World' - - -#### `whenExactly` {.collection-method} - -The `whenExactly` method invokes the given closure if the string exactly matches the given string. The closure will receive the fluent string instance: - - use Illuminate\Support\Str; - - $string = Str::of('laravel')->whenExactly('laravel', function ($string) { - return $string->title(); - }); - - // 'Laravel' - - -#### `whenIs` {.collection-method} - -The `whenIs` method invokes the given closure if the string matches a given pattern. Asterisks may be used as wildcard values. The closure will receive the fluent string instance: - - use Illuminate\Support\Str; - - $string = Str::of('foo/bar')->whenIs('foo/*', function ($string) { - return $string->append('/baz'); - }); - - // 'foo/bar/baz' - - -#### `whenIsAscii` {.collection-method} - -The `whenIsAscii` method invokes the given closure if the string is 7 bit ASCII. The closure will receive the fluent string instance: - - use Illuminate\Support\Str; - - $string = Str::of('foo/bar')->whenIsAscii('laravel', function ($string) { - return $string->title(); - }); - - // 'Laravel' - - -#### `whenIsUuid` {.collection-method} - -The `whenIsUuid` method invokes the given closure if the string is a valid UUID. The closure will receive the fluent string instance: - - use Illuminate\Support\Str; - - $string = Str::of('foo/bar')->whenIsUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', function ($string) { - return $string->substr(0, 8); - }); - - // 'a0a2a2d2' - - -#### `whenTest` {.collection-method} - -The `whenTest` method invokes the given closure if the string matches the given regular expression. The closure will receive the fluent string instance: - - use Illuminate\Support\Str; - - $string = Str::of('laravel framework')->whenTest('/laravel/', function ($string) { - return $string->title(); - }); - - // 'Laravel Framework' - - -#### `wordCount` {.collection-method} - -The `wordCount` method returns the number of words that a string contains: - -```php -use Illuminate\Support\Str; - -Str::of('Hello, world!')->wordCount(); // 2 +Route::get('/redirect', function () { + return Uri::to('/index') + ->withQuery(['sort' => 'name']); +}); ``` - - -#### `words` {.collection-method} - -The `words` method limits the number of words in a string. If necessary, you may specify an additional string that will be appended to the truncated string: - - use Illuminate\Support\Str; - - $string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>'); - - // Perfectly balanced, as >>> - - -## URLs - - -#### `action()` {.collection-method} - -The `action` function generates a URL for the given controller action: - - use App\Http\Controllers\HomeController; - - $url = action([HomeController::class, 'index']); - -If the method accepts route parameters, you may pass them as the second argument to the method: - - $url = action([UserController::class, 'profile'], ['id' => 1]); - - -#### `asset()` {.collection-method} - -The `asset` function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS): - - $url = asset('img/photo.jpg'); - -You can configure the asset URL host by setting the `ASSET_URL` variable in your `.env` file. This can be useful if you host your assets on an external service like Amazon S3 or another CDN: - - // ASSET_URL=http://example.com/assets - - $url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg - - -#### `route()` {.collection-method} - -The `route` function generates a URL for a given [named route](/docs/{{version}}/routing#named-routes): - - $url = route('route.name'); - -If the route accepts parameters, you may pass them as the second argument to the function: - - $url = route('route.name', ['id' => 1]); - -By default, the `route` function generates an absolute URL. If you wish to generate a relative URL, you may pass `false` as the third argument to the function: - - $url = route('route.name', ['id' => 1], false); - - -#### `secure_asset()` {.collection-method} - -The `secure_asset` function generates a URL for an asset using HTTPS: - - $url = secure_asset('img/photo.jpg'); - - -#### `secure_url()` {.collection-method} - -The `secure_url` function generates a fully qualified HTTPS URL to the given path. Additional URL segments may be passed in the function's second argument: - - $url = secure_url('https://github.com/user/profile'); - - $url = secure_url('https://github.com/user/profile',%20[1]); - - -#### `to_route()` {.collection-method} - -The `to_route` function generates a [redirect HTTP response](/docs/{{version}}/responses#redirects) for a given [named route](/docs/{{version}}/routing#named-routes): - - return to_route('users.show', ['user' => 1]); - -If necessary, you may pass the HTTP status code that should be assigned to the redirect and any additional response headers as the third and fourth arguments to the `to_route` method: - - return to_route('users.show', ['user' => 1], 302, ['X-Framework' => 'Laravel']); - - -#### `url()` {.collection-method} - -The `url` function generates a fully qualified URL to the given path: - - $url = url('https://github.com/user/profile'); - - $url = url('https://github.com/user/profile',%20[1]); - -If no path is provided, an `Illuminate\Routing\UrlGenerator` instance is returned: - - $current = url()->current(); - - $full = url()->full(); - - $previous = url()->previous(); - - -## Miscellaneous - - -#### `abort()` {.collection-method} - -The `abort` function throws [an HTTP exception](/docs/{{version}}/errors#http-exceptions) which will be rendered by the [exception handler](/docs/{{version}}/errors#the-exception-handler): - - abort(403); - -You may also provide the exception's message and custom HTTP response headers that should be sent to the browser: - - abort(403, 'Unauthorized.', $headers); - - -#### `abort_if()` {.collection-method} - -The `abort_if` function throws an HTTP exception if a given boolean expression evaluates to `true`: - - abort_if(! Auth::user()->isAdmin(), 403); - -Like the `abort` method, you may also provide the exception's response text as the third argument and an array of custom response headers as the fourth argument to the function. - - -#### `abort_unless()` {.collection-method} - -The `abort_unless` function throws an HTTP exception if a given boolean expression evaluates to `false`: - - abort_unless(Auth::user()->isAdmin(), 403); - -Like the `abort` method, you may also provide the exception's response text as the third argument and an array of custom response headers as the fourth argument to the function. - - -#### `app()` {.collection-method} - -The `app` function returns the [service container](/docs/{{version}}/container) instance: - - $container = app(); - -You may pass a class or interface name to resolve it from the container: - - $api = app('HelpSpot\API'); - - -#### `auth()` {.collection-method} - -The `auth` function returns an [authenticator](/docs/{{version}}/authentication) instance. You may use it as an alternative to the `Auth` facade: - - $user = auth()->user(); - -If needed, you may specify which guard instance you would like to access: - - $user = auth('admin')->user(); - - -#### `back()` {.collection-method} - -The `back` function generates a [redirect HTTP response](/docs/{{version}}/responses#redirects) to the user's previous location: - - return back($status = 302, $headers = [], $fallback = '/'); - - return back(); - - -#### `bcrypt()` {.collection-method} - -The `bcrypt` function [hashes](/docs/{{version}}/hashing) the given value using Bcrypt. You may use this function as an alternative to the `Hash` facade: - - $password = bcrypt('my-secret-password'); - - -#### `blank()` {.collection-method} - -The `blank` function determines whether the given value is "blank": - - blank(''); - blank(' '); - blank(null); - blank(collect()); - - // true - - blank(0); - blank(true); - blank(false); - - // false - -For the inverse of `blank`, see the [`filled`](#method-filled) method. - - -#### `broadcast()` {.collection-method} - -The `broadcast` function [broadcasts](/docs/{{version}}/broadcasting) the given [event](/docs/{{version}}/events) to its listeners: - - broadcast(new UserRegistered($user)); - - broadcast(new UserRegistered($user))->toOthers(); - - -#### `cache()` {.collection-method} - -The `cache` function may be used to get values from the [cache](/docs/{{version}}/cache). If the given key does not exist in the cache, an optional default value will be returned: - - $value = cache('key'); - - $value = cache('key', 'default'); - -You may add items to the cache by passing an array of key / value pairs to the function. You should also pass the number of seconds or duration the cached value should be considered valid: - - cache(['key' => 'value'], 300); - - cache(['key' => 'value'], now()->addSeconds(10)); - - -#### `class_uses_recursive()` {.collection-method} - -The `class_uses_recursive` function returns all traits used by a class, including traits used by all of its parent classes: - - $traits = class_uses_recursive(App\Models\User::class); - - -#### `collect()` {.collection-method} - -The `collect` function creates a [collection](/docs/{{version}}/collections) instance from the given value: - - $collection = collect(['taylor', 'abigail']); - - -#### `config()` {.collection-method} - -The `config` function gets the value of a [configuration](/docs/{{version}}/configuration) variable. The configuration values may be accessed using "dot" syntax, which includes the name of the file and the option you wish to access. A default value may be specified and is returned if the configuration option does not exist: - - $value = config('app.timezone'); - - $value = config('app.timezone', $default); - -You may set configuration variables at runtime by passing an array of key / value pairs. However, note that this function only affects the configuration value for the current request and does not update your actual configuration values: - - config(['app.debug' => true]); - - -#### `cookie()` {.collection-method} - -The `cookie` function creates a new [cookie](/docs/{{version}}/requests#cookies) instance: - - $cookie = cookie('name', 'value', $minutes); - - -#### `csrf_field()` {.collection-method} - -The `csrf_field` function generates an HTML `hidden` input field containing the value of the CSRF token. For example, using [Blade syntax](/docs/{{version}}/blade): - - {{ csrf_field() }} - - -#### `csrf_token()` {.collection-method} - -The `csrf_token` function retrieves the value of the current CSRF token: - - $token = csrf_token(); - - -#### `decrypt()` {.collection-method} - -The `decrypt` function [decrypts](/docs/{{version}}/encryption) the given value. You may use this function as an alternative to the `Crypt` facade: - - $password = decrypt($value); - - -#### `dd()` {.collection-method} - -The `dd` function dumps the given variables and ends execution of the script: - - dd($value); - - dd($value1, $value2, $value3, ...); - -If you do not want to halt the execution of your script, use the [`dump`](#method-dump) function instead. - - -#### `dispatch()` {.collection-method} - -The `dispatch` function pushes the given [job](/docs/{{version}}/queues#creating-jobs) onto the Laravel [job queue](/docs/{{version}}/queues): - - dispatch(new App\Jobs\SendEmails); - - -#### `dump()` {.collection-method} - -The `dump` function dumps the given variables: - - dump($value); - - dump($value1, $value2, $value3, ...); - -If you want to stop executing the script after dumping the variables, use the [`dd`](#method-dd) function instead. - - -#### `encrypt()` {.collection-method} - -The `encrypt` function [encrypts](/docs/{{version}}/encryption) the given value. You may use this function as an alternative to the `Crypt` facade: - - $secret = encrypt('my-secret-value'); - - -#### `env()` {.collection-method} - -The `env` function retrieves the value of an [environment variable](/docs/{{version}}/configuration#environment-configuration) or returns a default value: - - $env = env('APP_ENV'); - - $env = env('APP_ENV', 'production'); - -> {note} If you execute the `config:cache` command during your deployment process, you should be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded and all calls to the `env` function will return `null`. - - -#### `event()` {.collection-method} - -The `event` function dispatches the given [event](/docs/{{version}}/events) to its listeners: - - event(new UserRegistered($user)); - - -#### `filled()` {.collection-method} - -The `filled` function determines whether the given value is not "blank": - - filled(0); - filled(true); - filled(false); - - // true - - filled(''); - filled(' '); - filled(null); - filled(collect()); - - // false - -For the inverse of `filled`, see the [`blank`](#method-blank) method. - - -#### `info()` {.collection-method} - -The `info` function will write information to your application's [log](/docs/{{version}}/logging): - - info('Some helpful information!'); - -An array of contextual data may also be passed to the function: - - info('User login attempt failed.', ['id' => $user->id]); - - -#### `logger()` {.collection-method} - -The `logger` function can be used to write a `debug` level message to the [log](/docs/{{version}}/logging): - - logger('Debug message'); - -An array of contextual data may also be passed to the function: - - logger('User has logged in.', ['id' => $user->id]); - -A [logger](/docs/{{version}}/errors#logging) instance will be returned if no value is passed to the function: - - logger()->error('You are not allowed here.'); - - -#### `method_field()` {.collection-method} - -The `method_field` function generates an HTML `hidden` input field containing the spoofed value of the form's HTTP verb. For example, using [Blade syntax](/docs/{{version}}/blade): - -
- {{ method_field('DELETE') }} -
- - -#### `now()` {.collection-method} - -The `now` function creates a new `Illuminate\Support\Carbon` instance for the current time: - - $now = now(); - - -#### `old()` {.collection-method} - -The `old` function [retrieves](/docs/{{version}}/requests#retrieving-input) an [old input](/docs/{{version}}/requests#old-input) value flashed into the session: - - $value = old('value'); - - $value = old('value', 'default'); - - -#### `optional()` {.collection-method} - -The `optional` function accepts any argument and allows you to access properties or call methods on that object. If the given object is `null`, properties and methods will return `null` instead of causing an error: - - return optional($user->address)->street; - - {!! old('name', optional($user)->name) !!} - -The `optional` function also accepts a closure as its second argument. The closure will be invoked if the value provided as the first argument is not null: - - return optional(User::find($id), function ($user) { - return $user->name; - }); - - -#### `policy()` {.collection-method} - -The `policy` method retrieves a [policy](/docs/{{version}}/authorization#creating-policies) instance for a given class: - - $policy = policy(App\Models\User::class); - - -#### `redirect()` {.collection-method} - -The `redirect` function returns a [redirect HTTP response](/docs/{{version}}/responses#redirects), or returns the redirector instance if called with no arguments: - - return redirect($to = null, $status = 302, $headers = [], $https = null); - - return redirect('/home'); - - return redirect()->route('route.name'); - - -#### `report()` {.collection-method} - -The `report` function will report an exception using your [exception handler](/docs/{{version}}/errors#the-exception-handler): - - report($e); - -The `report` function also accepts a string as an argument. When a string is given to the function, the function will create an exception with the given string as its message: - - report('Something went wrong.'); - - -#### `request()` {.collection-method} - -The `request` function returns the current [request](/docs/{{version}}/requests) instance or obtains an input field's value from the current request: - - $request = request(); - - $value = request('key', $default); - - -#### `rescue()` {.collection-method} - -The `rescue` function executes the given closure and catches any exceptions that occur during its execution. All exceptions that are caught will be sent to your [exception handler](/docs/{{version}}/errors#the-exception-handler); however, the request will continue processing: - - return rescue(function () { - return $this->method(); - }); - -You may also pass a second argument to the `rescue` function. This argument will be the "default" value that should be returned if an exception occurs while executing the closure: - - return rescue(function () { - return $this->method(); - }, false); - - return rescue(function () { - return $this->method(); - }, function () { - return $this->failure(); - }); - - -#### `resolve()` {.collection-method} - -The `resolve` function resolves a given class or interface name to an instance using the [service container](/docs/{{version}}/container): - - $api = resolve('HelpSpot\API'); - - -#### `response()` {.collection-method} - -The `response` function creates a [response](/docs/{{version}}/responses) instance or obtains an instance of the response factory: - - return response('Hello World', 200, $headers); - - return response()->json(['foo' => 'bar'], 200, $headers); - - -#### `retry()` {.collection-method} - -The `retry` function attempts to execute the given callback until the given maximum attempt threshold is met. If the callback does not throw an exception, its return value will be returned. If the callback throws an exception, it will automatically be retried. If the maximum attempt count is exceeded, the exception will be thrown: - - return retry(5, function () { - // Attempt 5 times while resting 100ms between attempts... - }, 100); - -If you would like to manually calculate the number of milliseconds to sleep between attempts, you may pass a closure as the third argument to the `retry` function: - - return retry(5, function () { - // ... - }, function ($attempt) { - return $attempt * 100; - }); - -For convenience, you may provide an array as the first argument to the `retry` function. This array will be used to determine how many milliseconds to sleep between subsequent attempts: - - return retry([100, 200] function () { - // Sleep for 100ms on first retry, 200ms on second retry... - }); - -To only retry under specific conditions, you may pass a closure as the fourth argument to the `retry` function: - - return retry(5, function () { - // ... - }, 100, function ($exception) { - return $exception instanceof RetryException; - }); - - -#### `session()` {.collection-method} - -The `session` function may be used to get or set [session](/docs/{{version}}/session) values: - - $value = session('key'); - -You may set values by passing an array of key / value pairs to the function: - - session(['chairs' => 7, 'instruments' => 3]); - -The session store will be returned if no value is passed to the function: - - $value = session()->get('key'); - - session()->put('key', $value); - - -#### `tap()` {.collection-method} - -The `tap` function accepts two arguments: an arbitrary `$value` and a closure. The `$value` will be passed to the closure and then be returned by the `tap` function. The return value of the closure is irrelevant: - - $user = tap(User::first(), function ($user) { - $user->name = 'taylor'; - - $user->save(); - }); - -If no closure is passed to the `tap` function, you may call any method on the given `$value`. The return value of the method you call will always be `$value`, regardless of what the method actually returns in its definition. For example, the Eloquent `update` method typically returns an integer. However, we can force the method to return the model itself by chaining the `update` method call through the `tap` function: - - $user = tap($user)->update([ - 'name' => $name, - 'email' => $email, - ]); - -To add a `tap` method to a class, you may add the `Illuminate\Support\Traits\Tappable` trait to the class. The `tap` method of this trait accepts a Closure as its only argument. The object instance itself will be passed to the Closure and then be returned by the `tap` method: - - return $user->tap(function ($user) { - // - }); - - -#### `throw_if()` {.collection-method} - -The `throw_if` function throws the given exception if a given boolean expression evaluates to `true`: - - throw_if(! Auth::user()->isAdmin(), AuthorizationException::class); - - throw_if( - ! Auth::user()->isAdmin(), - AuthorizationException::class, - 'You are not allowed to access this page.' - ); - - -#### `throw_unless()` {.collection-method} - -The `throw_unless` function throws the given exception if a given boolean expression evaluates to `false`: - - throw_unless(Auth::user()->isAdmin(), AuthorizationException::class); - - throw_unless( - Auth::user()->isAdmin(), - AuthorizationException::class, - 'You are not allowed to access this page.' - ); - - -#### `today()` {.collection-method} - -The `today` function creates a new `Illuminate\Support\Carbon` instance for the current date: - - $today = today(); - - -#### `trait_uses_recursive()` {.collection-method} - -The `trait_uses_recursive` function returns all traits used by a trait: - - $traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class); - - -#### `transform()` {.collection-method} - -The `transform` function executes a closure on a given value if the value is not [blank](#method-blank) and then returns the return value of the closure: - - $callback = function ($value) { - return $value * 2; - }; - - $result = transform(5, $callback); - - // 10 - -A default value or closure may be passed as the third argument to the function. This value will be returned if the given value is blank: - - $result = transform(null, $callback, 'The value is blank'); - - // The value is blank - - -#### `validator()` {.collection-method} - -The `validator` function creates a new [validator](/docs/{{version}}/validation) instance with the given arguments. You may use it as an alternative to the `Validator` facade: - - $validator = validator($data, $rules, $messages); - - -#### `value()` {.collection-method} - -The `value` function returns the value it is given. However, if you pass a closure to the function, the closure will be executed and its returned value will be returned: - - $result = value(true); - - // true - - $result = value(function () { - return false; - }); - - // false - - -#### `view()` {.collection-method} - -The `view` function retrieves a [view](/docs/{{version}}/views) instance: - - return view('auth.login'); - - -#### `with()` {.collection-method} - -The `with` function returns the value it is given. If a closure is passed as the second argument to the function, the closure will be executed and its returned value will be returned: - - $callback = function ($value) { - return is_numeric($value) ? $value * 2 : 0; - }; - - $result = with(5, $callback); - - // 10 - - $result = with(null, $callback); - - // 0 - - $result = with(5, null); - - // 5 diff --git a/homestead.md b/homestead.md index 25c43197487..74172ccd9bc 100644 --- a/homestead.md +++ b/homestead.md @@ -1,33 +1,33 @@ # Laravel Homestead - [Introduction](#introduction) -- [Installation & Setup](#installation-and-setup) +- [Installation and Setup](#installation-and-setup) - [First Steps](#first-steps) - [Configuring Homestead](#configuring-homestead) - [Configuring Nginx Sites](#configuring-nginx-sites) - [Configuring Services](#configuring-services) - - [Launching The Vagrant Box](#launching-the-vagrant-box) + - [Launching the Vagrant Box](#launching-the-vagrant-box) - [Per Project Installation](#per-project-installation) - [Installing Optional Features](#installing-optional-features) - [Aliases](#aliases) - [Updating Homestead](#updating-homestead) - [Daily Usage](#daily-usage) - - [Connecting Via SSH](#connecting-via-ssh) + - [Connecting via SSH](#connecting-via-ssh) - [Adding Additional Sites](#adding-additional-sites) - [Environment Variables](#environment-variables) - [Ports](#ports) - [PHP Versions](#php-versions) - - [Connecting To Databases](#connecting-to-databases) + - [Connecting to Databases](#connecting-to-databases) - [Database Backups](#database-backups) - [Configuring Cron Schedules](#configuring-cron-schedules) - - [Configuring MailHog](#configuring-mailhog) + - [Configuring Mailpit](#configuring-mailpit) - [Configuring Minio](#configuring-minio) - [Laravel Dusk](#laravel-dusk) - [Sharing Your Environment](#sharing-your-environment) -- [Debugging & Profiling](#debugging-and-profiling) +- [Debugging and Profiling](#debugging-and-profiling) - [Debugging Web Requests With Xdebug](#debugging-web-requests) - [Debugging CLI Applications](#debugging-cli-applications) - - [Profiling Applications with Blackfire](#profiling-applications-with-blackfire) + - [Profiling Applications With Blackfire](#profiling-applications-with-blackfire) - [Network Interfaces](#network-interfaces) - [Extending Homestead](#extending-homestead) - [Provider Specific Settings](#provider-specific-settings) @@ -36,13 +36,17 @@ ## Introduction -Laravel strives to make the entire PHP development experience delightful, including your local development environment. [Laravel Homestead](https://github.com/laravel/homestead) is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine. +> [!WARNING] +> Laravel Homestead is a legacy package that is no longer actively maintained. [Laravel Sail](/docs/{{version}}/sail) may be used as a modern alternative. + +Laravel strives to make the entire PHP development experience delightful, including your local development environment. [Laravel Homestead](https://github.com/laravel/homestead) is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, or any other server software on your local machine. [Vagrant](https://www.vagrantup.com) provides a simple, elegant way to manage and provision Virtual Machines. Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes! Homestead runs on any Windows, macOS, or Linux system and includes Nginx, PHP, MySQL, PostgreSQL, Redis, Memcached, Node, and all of the other software you need to develop amazing Laravel applications. -> {note} If you are using Windows, you may need to enable hardware virtualization (VT-x). It can usually be enabled via your BIOS. If you are using Hyper-V on a UEFI system you may additionally need to disable Hyper-V in order to access VT-x. +> [!WARNING] +> If you are using Windows, you may need to enable hardware virtualization (VT-x). It can usually be enabled via your BIOS. If you are using Hyper-V on a UEFI system you may additionally need to disable Hyper-V in order to access VT-x. ### Included Software @@ -56,8 +60,11 @@ Homestead runs on any Windows, macOS, or Linux system and includes Nginx, PHP, M
-- Ubuntu 20.04 + +- Ubuntu 22.04 - Git +- PHP 8.3 +- PHP 8.2 - PHP 8.1 - PHP 8.0 - PHP 7.4 @@ -70,18 +77,20 @@ Homestead runs on any Windows, macOS, or Linux system and includes Nginx, PHP, M - MySQL 8.0 - lmm - Sqlite3 -- PostgreSQL 13 +- PostgreSQL 15 - Composer +- Docker - Node (With Yarn, Bower, Grunt, and Gulp) - Redis - Memcached - Beanstalkd -- Mailhog +- Mailpit - avahi - ngrok - Xdebug - XHProf / Tideways / XHGui - wp-cli +
@@ -96,19 +105,21 @@ Homestead runs on any Windows, macOS, or Linux system and includes Nginx, PHP, M
+ - Apache - Blackfire - Cassandra - Chronograf - CouchDB - Crystal & Lucky Framework -- Docker - Elasticsearch - EventStoreDB +- Flyway - Gearman - Go - Grafana - InfluxDB +- Logstash - MariaDB - Meilisearch - MinIO @@ -120,22 +131,24 @@ Homestead runs on any Windows, macOS, or Linux system and includes Nginx, PHP, M - Python - R - RabbitMQ +- Rust - RVM (Ruby Version Manager) - Solr - TimescaleDB - Trader (PHP extension) - Webdriver & Laravel Dusk Utilities +
-## Installation & Setup +## Installation and Setup ### First Steps -Before launching your Homestead environment, you must install [Vagrant](https://www.vagrantup.com/downloads.html) as well as one of the following supported providers: +Before launching your Homestead environment, you must install [Vagrant](https://developer.hashicorp.com/vagrant/downloads) as well as one of the following supported providers: -- [VirtualBox 6.1.x](https://www.virtualbox.org/wiki/Downloads) +- [VirtualBox 6.1.x](https://www.virtualbox.org/wiki/Download_Old_Builds_6_1) - [Parallels](https://www.parallels.com/products/desktop/) All of these software packages provide easy-to-use visual installers for all popular operating systems. @@ -179,7 +192,8 @@ The `provider` key in your `Homestead.yaml` file indicates which Vagrant provide provider: virtualbox -> {note} If you are using Apple Silicon, you should add `box: laravel/homestead-arm` to your `Homestead.yaml` file. Apple Silicon requires the Parallels provider. +> [!WARNING] +> If you are using Apple Silicon the Parallels provider is required. #### Configuring Shared Folders @@ -192,7 +206,8 @@ folders: to: /home/vagrant/project1 ``` -> {note} Windows users should not use the `~/` path syntax and instead should use the full path to their project, such as `C:\Users\user\Code\project1`. +> [!WARNING] +> Windows users should not use the `~/` path syntax and instead should use the full path to their project, such as `C:\Users\user\Code\project1`. You should always map individual applications to their own folder mapping instead of mapping a single large directory that contains all of your applications. When you map a folder, the virtual machine must keep track of all disk IO for *every* file in the folder. You may experience reduced performance if you have a large number of files in a folder: @@ -204,9 +219,10 @@ folders: to: /home/vagrant/project2 ``` -> {note} You should never mount `.` (the current directory) when using Homestead. This causes Vagrant to not map the current folder to `/vagrant` and will break optional features and cause unexpected results while provisioning. +> [!WARNING] +> You should never mount `.` (the current directory) when using Homestead. This causes Vagrant to not map the current folder to `/vagrant` and will break optional features and cause unexpected results while provisioning. -To enable [NFS](https://www.vagrantup.com/docs/synced-folders/nfs.html), you may add a `type` option to your folder mapping: +To enable [NFS](https://developer.hashicorp.com/vagrant/docs/synced-folders/nfs), you may add a `type` option to your folder mapping: ```yaml folders: @@ -215,9 +231,10 @@ folders: type: "nfs" ``` -> {note} When using NFS on Windows, you should consider installing the [vagrant-winnfsd](https://github.com/winnfsd/vagrant-winnfsd) plug-in. This plug-in will maintain the correct user / group permissions for files and directories within the Homestead virtual machine. +> [!WARNING] +> When using NFS on Windows, you should consider installing the [vagrant-winnfsd](https://github.com/winnfsd/vagrant-winnfsd) plug-in. This plug-in will maintain the correct user / group permissions for files and directories within the Homestead virtual machine. -You may also pass any options supported by Vagrant's [Synced Folders](https://www.vagrantup.com/docs/synced-folders/basic_usage.html) by listing them under the `options` key: +You may also pass any options supported by Vagrant's [Synced Folders](https://developer.hashicorp.com/vagrant/docs/synced-folders/basic_usage) by listing them under the `options` key: ```yaml folders: @@ -242,7 +259,8 @@ sites: If you change the `sites` property after provisioning the Homestead virtual machine, you should execute the `vagrant reload --provision` command in your terminal to update the Nginx configuration on the virtual machine. -> {note} Homestead scripts are built to be as idempotent as possible. However, if you are experiencing issues while provisioning you should destroy and rebuild the machine by executing the `vagrant destroy && vagrant up` command. +> [!WARNING] +> Homestead scripts are built to be as idempotent as possible. However, if you are experiencing issues while provisioning you should destroy and rebuild the machine by executing the `vagrant destroy && vagrant up` command. #### Hostname Resolution @@ -251,7 +269,9 @@ Homestead publishes hostnames using `mDNS` for automatic host resolution. If you Using automatic hostnames works best for [per project installations](#per-project-installation) of Homestead. If you host multiple sites on a single Homestead instance, you may add the "domains" for your web sites to the `hosts` file on your machine. The `hosts` file will redirect requests for your Homestead sites into your Homestead virtual machine. On macOS and Linux, this file is located at `/etc/hosts`. On Windows, it is located at `C:\Windows\System32\drivers\etc\hosts`. The lines you add to this file will look like the following: - 192.168.56.56 homestead.test +```text +192.168.56.56 homestead.test +``` Make sure the IP address listed is the one set in your `Homestead.yaml` file. Once you have added the domain to your `hosts` file and launched the Vagrant box you will be able to access the site via your web browser: @@ -275,7 +295,7 @@ services: The specified services will be started or stopped based on their order in the `enabled` and `disabled` directives. -### Launching The Vagrant Box +### Launching the Vagrant Box Once you have edited the `Homestead.yaml` to your liking, run the `vagrant up` command from your Homestead directory. Vagrant will boot the virtual machine and automatically configure your shared folders and Nginx sites. @@ -320,15 +340,17 @@ features: - chronograf: true - couchdb: true - crystal: true - - docker: true + - dragonflydb: true - elasticsearch: version: 7.9.0 - eventstore: true version: 21.2.0 + - flyway: true - gearman: true - golang: true - grafana: true - influxdb: true + - logstash: true - mariadb: true - meilisearch: true - minio: true @@ -340,6 +362,7 @@ features: - python: true - r-base: true - rabbitmq: true + - rustc: true - rvm: true - solr: true - timescaledb: true @@ -352,7 +375,8 @@ features: You may specify a supported version of Elasticsearch, which must be an exact version number (major.minor.patch). The default installation will create a cluster named 'homestead'. You should never give Elasticsearch more than half of the operating system's memory, so make sure your Homestead virtual machine has at least twice the Elasticsearch allocation. -> {tip} Check out the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current) to learn how to customize your configuration. +> [!NOTE] +> Check out the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current) to learn how to customize your configuration. #### MariaDB @@ -432,7 +456,7 @@ vagrant up ## Daily Usage -### Connecting Via SSH +### Connecting via SSH You can SSH into your virtual machine by executing the `vagrant ssh` terminal command from your Homestead directory. @@ -449,12 +473,15 @@ sites: to: /home/vagrant/project2/public ``` -> {note} You should ensure that you have configured a [folder mapping](#configuring-shared-folders) for the project's directory before adding the site. +> [!WARNING] +> You should ensure that you have configured a [folder mapping](#configuring-shared-folders) for the project's directory before adding the site. If Vagrant is not automatically managing your "hosts" file, you may need to add the new site to that file as well. On macOS and Linux, this file is located at `/etc/hosts`. On Windows, it is located at `C:\Windows\System32\drivers\etc\hosts`: - 192.168.56.56 homestead.test - 192.168.56.56 another.test +```text +192.168.56.56 homestead.test +192.168.56.56 another.test +``` Once the site has been added, execute the `vagrant reload --provision` terminal command from your Homestead directory. @@ -470,7 +497,7 @@ sites: type: "statamic" ``` -The available site types are: `apache`, `apigility`, `expressive`, `laravel` (the default), `proxy`, `silverstripe`, `statamic`, `symfony2`, `symfony4`, and `zf`. +The available site types are: `apache`, `apache-proxy`, `apigility`, `expressive`, `laravel` (the default), `proxy` (for nginx), `silverstripe`, `statamic`, `symfony2`, `symfony4`, and `zf`. #### Site Parameters @@ -536,7 +563,7 @@ Below is a list of additional Homestead service ports that you may wish to map f - **MySQL:** 33060 → To 3306 - **PostgreSQL:** 54320 → To 5432 - **MongoDB:** 27017 → To 27017 -- **Mailhog:** 8025 → To 8025 +- **Mailpit:** 8025 → To 8025 - **Minio:** 9600 → To 9600
@@ -544,7 +571,7 @@ Below is a list of additional Homestead service ports that you may wish to map f ### PHP Versions -Homestead 6 introduced support for running multiple versions of PHP on the same virtual machine. You may specify which version of PHP to use for a given site within your `Homestead.yaml` file. The available PHP versions are: "5.6", "7.0", "7.1", "7.2", "7.3", "7.4", "8.0" (the default), and "8.1": +Homestead supports running multiple versions of PHP on the same virtual machine. You may specify which version of PHP to use for a given site within your `Homestead.yaml` file. The available PHP versions are: "5.6", "7.0", "7.1", "7.2", "7.3", "7.4", "8.0", "8.1", "8.2", and "8.3", (the default): ```yaml sites: @@ -564,6 +591,8 @@ php7.3 artisan list php7.4 artisan list php8.0 artisan list php8.1 artisan list +php8.2 artisan list +php8.3 artisan list ``` You may change the default version of PHP used by the CLI by issuing the following commands from within your Homestead virtual machine: @@ -577,28 +606,33 @@ php73 php74 php80 php81 +php82 +php83 ``` -### Connecting To Databases +### Connecting to Databases A `homestead` database is configured for both MySQL and PostgreSQL out of the box. To connect to your MySQL or PostgreSQL database from your host machine's database client, you should connect to `127.0.0.1` on port `33060` (MySQL) or `54320` (PostgreSQL). The username and password for both databases is `homestead` / `secret`. -> {note} You should only use these non-standard ports when connecting to the databases from your host machine. You will use the default 3306 and 5432 ports in your Laravel application's `database` configuration file since Laravel is running _within_ the virtual machine. +> [!WARNING] +> You should only use these non-standard ports when connecting to the databases from your host machine. You will use the default 3306 and 5432 ports in your Laravel application's `database` configuration file since Laravel is running _within_ the virtual machine. ### Database Backups Homestead can automatically backup your database when your Homestead virtual machine is destroyed. To utilize this feature, you must be using Vagrant 2.1.0 or greater. Or, if you are using an older version of Vagrant, you must install the `vagrant-triggers` plug-in. To enable automatic database backups, add the following line to your `Homestead.yaml` file: - backup: true +```yaml +backup: true +``` -Once configured, Homestead will export your databases to `mysql_backup` and `postgres_backup` directories when the `vagrant destroy` command is executed. These directories can be found in the folder where you installed Homestead or in the root of your project if you are using the [per project installation](#per-project-installation) method. +Once configured, Homestead will export your databases to `.backup/mysql_backup` and `.backup/postgres_backup` directories when the `vagrant destroy` command is executed. These directories can be found in the folder where you installed Homestead or in the root of your project if you are using the [per project installation](#per-project-installation) method. ### Configuring Cron Schedules -Laravel provides a convenient way to [schedule cron jobs](/docs/{{version}}/scheduling) by scheduling a single `schedule:run` Artisan command to run every minute. The `schedule:run` command will examine the job schedule defined in your `App\Console\Kernel` class to determine which scheduled tasks to run. +Laravel provides a convenient way to [schedule cron jobs](/docs/{{version}}/scheduling) by scheduling a single `schedule:run` Artisan command to run every minute. The `schedule:run` command will examine the job schedule defined in your `routes/console.php` file to determine which scheduled tasks to run. If you would like the `schedule:run` command to be run for a Homestead site, you may set the `schedule` option to `true` when defining the site: @@ -611,10 +645,10 @@ sites: The cron job for the site will be defined in the `/etc/cron.d` directory of the Homestead virtual machine. - -### Configuring MailHog + +### Configuring Mailpit -[MailHog](https://github.com/mailhog/MailHog) allows you to intercept your outgoing email and examine it without actually sending the mail to its recipients. To get started, update your application's `.env` file to use the following mail settings: +[Mailpit](https://github.com/axllent/mailpit) allows you to intercept your outgoing email and examine it without actually sending the mail to its recipients. To get started, update your application's `.env` file to use the following mail settings: ```ini MAIL_MAILER=smtp @@ -625,7 +659,7 @@ MAIL_PASSWORD=null MAIL_ENCRYPTION=null ``` -Once MailHog has been configured, you may access the MailHog dashboard at `http://localhost:8025`. +Once Mailpit has been configured, you may access the Mailpit dashboard at `http://localhost:8025`. ### Configuring Minio @@ -636,25 +670,14 @@ Once MailHog has been configured, you may access the MailHog dashboard at `http: By default, Minio is available on port 9600. You may access the Minio control panel by visiting `http://localhost:9600`. The default access key is `homestead`, while the default secret key is `secretkey`. When accessing Minio, you should always use region `us-east-1`. -In order to use Minio, you will need to adjust the S3 disk configuration in your application's `config/filesystems.php` configuration file. You will need to add the `use_path_style_endpoint` option to the disk configuration as well as change the `url` key to `endpoint`: - - 's3' => [ - 'driver' => 's3', - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'region' => env('AWS_DEFAULT_REGION'), - 'bucket' => env('AWS_BUCKET'), - 'endpoint' => env('AWS_URL'), - 'use_path_style_endpoint' => true, - ] - -Finally, ensure your `.env` file has the following options: +In order to use Minio, ensure your `.env` file has the following options: ```ini +AWS_USE_PATH_STYLE_ENDPOINT=true +AWS_ENDPOINT=http://localhost:9600 AWS_ACCESS_KEY_ID=homestead AWS_SECRET_ACCESS_KEY=secretkey AWS_DEFAULT_REGION=us-east-1 -AWS_URL=http://localhost:9600 ``` To provision Minio powered "S3" buckets, add a `buckets` directive to your `Homestead.yaml` file. After defining your buckets, you should execute the `vagrant reload --provision` command in your terminal: @@ -672,7 +695,7 @@ Supported `policy` values include: `none`, `download`, `upload`, and `public`. ### Laravel Dusk -In order to run [Laravel Dusk](/docs/{{version}}/dusk) tests within Homestead, you should enable the [`webdriver` feature](#installing-optional-features) in your Homestead configuration: +In order to run [Laravel Dusk](/docs/{{version}}/dusk) tests within Homestead, you should enable the [webdriver feature](#installing-optional-features) in your Homestead configuration: ```yaml features: @@ -698,10 +721,13 @@ After running the command, you will see an Ngrok screen appear which contains th share homestead.test -region=eu -subdomain=laravel ``` -> {note} Remember, Vagrant is inherently insecure and you are exposing your virtual machine to the Internet when running the `share` command. +If you need to share content over HTTPS rather than HTTP, using the `sshare` command instead of `share` will enable you to do so. + +> [!WARNING] +> Remember, Vagrant is inherently insecure and you are exposing your virtual machine to the Internet when running the `share` command. -## Debugging & Profiling +## Debugging and Profiling ### Debugging Web Requests With Xdebug @@ -710,7 +736,8 @@ Homestead includes support for step debugging using [Xdebug](https://xdebug.org) By default, Xdebug is already running and ready to accept connections. If you need to enable Xdebug on the CLI, execute the `sudo phpenmod xdebug` command within your Homestead virtual machine. Next, follow your IDE's instructions to enable debugging. Finally, configure your browser to trigger Xdebug with an extension or [bookmarklet](https://www.jetbrains.com/phpstorm/marklets/). -> {note} Xdebug causes PHP to run significantly slower. To disable Xdebug, run `sudo phpdismod xdebug` within your Homestead virtual machine and restart the FPM service. +> [!WARNING] +> Xdebug causes PHP to run significantly slower. To disable Xdebug, run `sudo phpdismod xdebug` within your Homestead virtual machine and restart the FPM service. #### Autostarting Xdebug @@ -719,8 +746,9 @@ When debugging functional tests that make requests to the web server, it is easi ```ini ; If Homestead.yaml contains a different subnet for the IP address, this address may be different... -xdebug.remote_host = 192.168.10.1 -xdebug.remote_autostart = 1 +xdebug.client_host = 192.168.10.1 +xdebug.mode = debug +xdebug.start_with_request = yes ``` @@ -728,10 +756,12 @@ xdebug.remote_autostart = 1 To debug a PHP CLI application, use the `xphp` shell alias inside your Homestead virtual machine: - xphp /path/to/script +```shell +xphp /path/to/script +``` -### Profiling Applications with Blackfire +### Profiling Applications With Blackfire [Blackfire](https://blackfire.io/docs/introduction) is a service for profiling web requests and CLI applications. It offers an interactive user interface which displays profile data in call-graphs and timelines. It is built for use in development, staging, and production, with no overhead for end users. In addition, Blackfire provides performance, quality, and security checks on code and `php.ini` configuration settings. @@ -748,7 +778,7 @@ features: client_token: "client_value" ``` -Blackfire server credentials and client credentials [require a Blackfire account](https://blackfire.io/signup). Blackfire offers various options to profile an application, including a CLI tool and browser extension. Please [review the Blackfire documentation for more details](https://blackfire.io/docs/cookbooks/index). +Blackfire server credentials and client credentials [require a Blackfire account](https://blackfire.io/signup). Blackfire offers various options to profile an application, including a CLI tool and browser extension. Please [review the Blackfire documentation for more details](https://blackfire.io/docs/php/integrations/laravel/index). ## Network Interfaces @@ -761,7 +791,7 @@ networks: ip: "192.168.10.20" ``` -To enable a [bridged](https://www.vagrantup.com/docs/networking/public_network.html) interface, configure a `bridge` setting for the network and change the network type to `public_network`: +To enable a [bridged](https://developer.hashicorp.com/vagrant/docs/networking/public_network) interface, configure a `bridge` setting for the network and change the network type to `public_network`: ```yaml networks: @@ -770,12 +800,22 @@ networks: bridge: "en1: Wi-Fi (AirPort)" ``` -To enable [DHCP](https://www.vagrantup.com/docs/networking/public_network.html), just remove the `ip` option from your configuration: +To enable [DHCP](https://developer.hashicorp.com/vagrant/docs/networking/public_network#dhcp), just remove the `ip` option from your configuration: + +```yaml +networks: + - type: "public_network" + bridge: "en1: Wi-Fi (AirPort)" +``` + +To update what device the network is using, you may add a `dev` option to the network's configuration. The default `dev` value is `eth0`: ```yaml networks: - type: "public_network" + ip: "192.168.10.20" bridge: "en1: Wi-Fi (AirPort)" + dev: "enp2s0" ``` @@ -812,14 +852,3 @@ By default, Homestead configures the `natdnshostresolver` setting to `on`. This provider: virtualbox natdnshostresolver: 'off' ``` - - -#### Symbolic Links On Windows - -If symbolic links are not working properly on your Windows machine, you may need to add the following block to your `Vagrantfile`: - -```ruby -config.vm.provider "virtualbox" do |v| - v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root", "1"] -end -``` diff --git a/horizon.md b/horizon.md index f049137a925..f5628aced49 100644 --- a/horizon.md +++ b/horizon.md @@ -3,8 +3,15 @@ - [Introduction](#introduction) - [Installation](#installation) - [Configuration](#configuration) - - [Balancing Strategies](#balancing-strategies) - [Dashboard Authorization](#dashboard-authorization) + - [Max Job Attempts](#max-job-attempts) + - [Job Timeout](#job-timeout) + - [Job Backoff](#job-backoff) + - [Silenced Jobs](#silenced-jobs) +- [Balancing Strategies](#balancing-strategies) + - [Auto Balancing](#auto-balancing) + - [Simple Balancing](#simple-balancing) + - [No Balancing](#no-balancing) - [Upgrading Horizon](#upgrading-horizon) - [Running Horizon](#running-horizon) - [Deploying Horizon](#deploying-horizon) @@ -17,7 +24,8 @@ ## Introduction -> {tip} Before digging into Laravel Horizon, you should familiarize yourself with Laravel's base [queue services](/docs/{{version}}/queues). Horizon augments Laravel's queue with additional features that may be confusing if you are not already familiar with the basic queue features offered by Laravel. +> [!NOTE] +> Before digging into Laravel Horizon, you should familiarize yourself with Laravel's base [queue services](/docs/{{version}}/queues). Horizon augments Laravel's queue with additional features that may be confusing if you are not already familiar with the basic queue features offered by Laravel. [Laravel Horizon](https://github.com/laravel/horizon) provides a beautiful dashboard and code-driven configuration for your Laravel powered [Redis queues](/docs/{{version}}/queues). Horizon allows you to easily monitor key metrics of your queue system such as job throughput, runtime, and job failures. @@ -28,7 +36,8 @@ When using Horizon, all of your queue worker configuration is stored in a single ## Installation -> {note} Laravel Horizon requires that you use [Redis](https://redis.io) to power your queue. Therefore, you should ensure that your queue connection is set to `redis` in your application's `config/queue.php` configuration file. +> [!WARNING] +> Laravel Horizon requires that you use [Redis](https://redis.io) to power your queue. Therefore, you should ensure that your queue connection is set to `redis` in your application's `config/queue.php` configuration file. You may install Horizon into your project using the Composer package manager: @@ -47,122 +56,386 @@ php artisan horizon:install After publishing Horizon's assets, its primary configuration file will be located at `config/horizon.php`. This configuration file allows you to configure the queue worker options for your application. Each configuration option includes a description of its purpose, so be sure to thoroughly explore this file. -> {note} Horizon uses a Redis connection named `horizon` internally. This Redis connection name is reserved and should not be assigned to another Redis connection in the `database.php` configuration file or as the value of the `use` option in the `horizon.php` configuration file. +> [!WARNING] +> Horizon uses a Redis connection named `horizon` internally. This Redis connection name is reserved and should not be assigned to another Redis connection in the `database.php` configuration file or as the value of the `use` option in the `horizon.php` configuration file. #### Environments After installation, the primary Horizon configuration option that you should familiarize yourself with is the `environments` configuration option. This configuration option is an array of environments that your application runs on and defines the worker process options for each environment. By default, this entry contains a `production` and `local` environment. However, you are free to add more environments as needed: - 'environments' => [ - 'production' => [ - 'supervisor-1' => [ - 'maxProcesses' => 10, - 'balanceMaxShift' => 1, - 'balanceCooldown' => 3, - ], +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + 'maxProcesses' => 10, + 'balanceMaxShift' => 1, + 'balanceCooldown' => 3, ], + ], + + 'local' => [ + 'supervisor-1' => [ + 'maxProcesses' => 3, + ], + ], +], +``` + +You may also define a wildcard environment (`*`) which will be used when no other matching environment is found: - 'local' => [ - 'supervisor-1' => [ - 'maxProcesses' => 3, - ], +```php +'environments' => [ + // ... + + '*' => [ + 'supervisor-1' => [ + 'maxProcesses' => 3, ], ], +], +``` When you start Horizon, it will use the worker process configuration options for the environment that your application is running on. Typically, the environment is determined by the value of the `APP_ENV` [environment variable](/docs/{{version}}/configuration#determining-the-current-environment). For example, the default `local` Horizon environment is configured to start three worker processes and automatically balance the number of worker processes assigned to each queue. The default `production` environment is configured to start a maximum of 10 worker processes and automatically balance the number of worker processes assigned to each queue. -> {note} You should ensure that the `environments` portion of your `horizon` configuration file contains an entry for each [environment](/docs/{{version}}/configuration#environment-configuration) on which you plan to run Horizon. +> [!WARNING] +> You should ensure that the `environments` portion of your `horizon` configuration file contains an entry for each [environment](/docs/{{version}}/configuration#environment-configuration) on which you plan to run Horizon. #### Supervisors -As you can see in Horizon's default configuration file. Each environment can contain one or more "supervisors". By default, the configuration file defines this supervisor as `supervisor-1`; however, you are free to name your supervisors whatever you want. Each supervisor is essentially responsible for "supervising" a group of worker processes and takes care of balancing worker processes across queues. +As you can see in Horizon's default configuration file, each environment can contain one or more "supervisors". By default, the configuration file defines this supervisor as `supervisor-1`; however, you are free to name your supervisors whatever you want. Each supervisor is essentially responsible for "supervising" a group of worker processes and takes care of balancing worker processes across queues. You may add additional supervisors to a given environment if you would like to define a new group of worker processes that should run in that environment. You may choose to do this if you would like to define a different balancing strategy or worker process count for a given queue used by your application. + +#### Maintenance Mode + +While your application is in [maintenance mode](/docs/{{version}}/configuration#maintenance-mode), queued jobs will not be processed by Horizon unless the supervisor's `force` option is defined as `true` within the Horizon configuration file: + +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'force' => true, + ], + ], +], +``` + #### Default Values Within Horizon's default configuration file, you will notice a `defaults` configuration option. This configuration option specifies the default values for your application's [supervisors](#supervisors). The supervisor's default configuration values will be merged into the supervisor's configuration for each environment, allowing you to avoid unnecessary repetition when defining your supervisors. - -### Balancing Strategies + +### Dashboard Authorization + +The Horizon dashboard may be accessed via the `/horizon` route. By default, you will only be able to access this dashboard in the `local` environment. However, within your `app/Providers/HorizonServiceProvider.php` file, there is an [authorization gate](/docs/{{version}}/authorization#gates) definition. This authorization gate controls access to Horizon in **non-local** environments. You are free to modify this gate as needed to restrict access to your Horizon installation: + +```php +/** + * Register the Horizon gate. + * + * This gate determines who can access Horizon in non-local environments. + */ +protected function gate(): void +{ + Gate::define('viewHorizon', function (User $user) { + return in_array($user->email, [ + 'taylor@laravel.com', + ]); + }); +} +``` + + +#### Alternative Authentication Strategies -Unlike Laravel's default queue system, Horizon allows you to choose from three worker balancing strategies: `simple`, `auto`, and `false`. The `simple` strategy, which is the configuration file's default, splits incoming jobs evenly between worker processes: +Remember that Laravel automatically injects the authenticated user into the gate closure. If your application is providing Horizon security via another method, such as IP restrictions, then your Horizon users may not need to "login". Therefore, you will need to change `function (User $user)` closure signature above to `function (User $user = null)` in order to force Laravel to not require authentication. - 'balance' => 'simple', + +### Max Job Attempts -The `auto` strategy adjusts the number of worker processes per queue based on the current workload of the queue. For example, if your `notifications` queue has 1,000 pending jobs while your `render` queue is empty, Horizon will allocate more workers to your `notifications` queue until the queue is empty. +> [!NOTE] +> Before refining these options, make sure you are familiar with Laravel's default [queue services](/docs/{{version}}/queues#max-job-attempts-and-timeout) and the concept of 'attempts'. -When using the `auto` strategy, you may define the `minProcesses` and `maxProcesses` configuration options to control the minimum and the maximum number of worker processes Horizon should scale up and down to: +You can define the maximum number of attempts a job can consume within a supervisor's configuration: - 'environments' => [ - 'production' => [ - 'supervisor-1' => [ - 'connection' => 'redis', - 'queue' => ['default'], - 'balance' => 'auto', - 'minProcesses' => 1, - 'maxProcesses' => 10, - 'balanceMaxShift' => 1, - 'balanceCooldown' => 3, - 'tries' => 3, - ], +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'tries' => 10, ], ], +], +``` -The `balanceMaxShift` and `balanceCooldown` configuration values to determine how quickly Horizon will scale to meet worker demand. In the example above, a maximum of one new process will be created or destroyed every three seconds. You are free to tweak these values as necessary based on your application's needs. +> [!NOTE] +> This option is similar to the `--tries` option when using the Artisan command to process queues. -When the `balance` option is set to `false`, the default Laravel behavior will be used, which processes queues in the order they are listed in your configuration. +Adjusting the `tries` option is essential when using middlewares such as `WithoutOverlapping` or `RateLimited` because they consume attempts. To handle this, adjust the `tries` configuration value either at the supervisor level or by defining the `$tries` property on the job class. - -### Dashboard Authorization +If you don't set the `tries` option, Horizon defaults to a single attempt, unless the job class defines `$tries`, which takes precedence over the Horizon configuration. -Horizon exposes a dashboard at the `/horizon` URI. By default, you will only be able to access this dashboard in the `local` environment. However, within your `app/Providers/HorizonServiceProvider.php` file, there is an [authorization gate](/docs/{{version}}/authorization#gates) definition. This authorization gate controls access to Horizon in **non-local** environments. You are free to modify this gate as needed to restrict access to your Horizon installation: +Setting `tries` or `$tries` to 0 allows unlimited attempts, which is ideal when the number of attempts is uncertain. To prevent endless failures, you can limit the number of exceptions allowed by setting the `$maxExceptions` property on the job class. - /** - * Register the Horizon gate. - * - * This gate determines who can access Horizon in non-local environments. - * - * @return void - */ - protected function gate() - { - Gate::define('viewHorizon', function ($user) { - return in_array($user->email, [ - 'taylor@laravel.com', - ]); - }); - } + +### Job Timeout - -#### Alternative Authentication Strategies +Similarly, you can set a `timeout` value at the supervisor level, which specifies how many seconds a worker process can run a job before it's forcefully terminated. Once terminated, the job will either be retried or marked as failed, depending on your queue configuration: -Remember that Laravel automatically injects the authenticated user into the gate closure. If your application is providing Horizon security via another method, such as IP restrictions, then your Horizon users may not need to "login". Therefore, you will need to change `function ($user)` closure signature above to `function ($user = null)` in order to force Laravel to not require authentication. +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ...¨ + 'timeout' => 60, + ], + ], +], +``` - -## Upgrading Horizon +> [!WARNING] +> When using the `auto` balancing strategy, Horizon will consider in-progress workers as "hanging" and force-kill them after the Horizon timeout during scale down. Always ensure the Horizon timeout is greater than any job-level timeout, otherwise jobs may be terminated mid-execution. In addition, the `timeout` value should always be at least a few seconds shorter than the `retry_after` value defined in your `config/queue.php` configuration file. Otherwise, your jobs may be processed twice. -When upgrading to a new major version of Horizon, it's important that you carefully review [the upgrade guide](https://github.com/laravel/horizon/blob/master/UPGRADE.md). In addition, when upgrading to any new Horizon version, you should re-publish Horizon's assets: + +### Job Backoff -```shell -php artisan horizon:publish +You can define the `backoff` value at the supervisor level to specify how long Horizon should wait before retrying a job that encounters an unhandled exception: + +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'backoff' => 10, + ], + ], +], ``` -To keep the assets up-to-date and avoid issues in future updates, you may add the `horizon:publish` command to the `post-update-cmd` scripts in your application's `composer.json` file: +You may also configure "exponential" backoffs by using an array for the `backoff` value. In this example, the retry delay will be 1 second for the first retry, 5 seconds for the second retry, 10 seconds for the third retry, and 10 seconds for every subsequent retry if there are more attempts remaining: -```json +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'backoff' => [1, 5, 10], + ], + ], +], +``` + + +### Silenced Jobs + +Sometimes, you may not be interested in viewing certain jobs dispatched by your application or third-party packages. Instead of these jobs taking up space in your "Completed Jobs" list, you can silence them. To get started, add the job's class name to the `silenced` configuration option in your application's `horizon` configuration file: + +```php +'silenced' => [ + App\Jobs\ProcessPodcast::class, +], +``` + +In addition to silencing individual job classes, Horizon also supports silencing jobs based on [tags](#tags). This can be useful if you want to hide multiple jobs that share a common tag: + +```php +'silenced_tags' => [ + 'notifications' +], +``` + +Alternatively, the job you wish to silence can implement the `Laravel\Horizon\Contracts\Silenced` interface. If a job implements this interface, it will automatically be silenced, even if it is not present in the `silenced` configuration array: + +```php +use Laravel\Horizon\Contracts\Silenced; + +class ProcessPodcast implements ShouldQueue, Silenced { - "scripts": { - "post-update-cmd": [ - "@php artisan horizon:publish --ansi" - ] - } + use Queueable; + + // ... } ``` + +## Balancing Strategies + +Each supervisor can process one or more queues but unlike Laravel's default queue system, Horizon allows you to choose from three worker balancing strategies: `auto`, `simple`, and `false`. + + +### Auto Balancing + +The `auto` strategy, which is the default strategy, adjusts the number of worker processes per queue based on the current workload of the queue. For example, if your `notifications` queue has 1,000 pending jobs while your `default` queue is empty, Horizon will allocate more workers to your `notifications` queue until the queue is empty. + +When using the `auto` strategy, you may also configure the `minProcesses` and `maxProcesses` configuration options: + +
+ +- `minProcesses` defines the minimum number of worker processes per queue. This value must be greater than or equal to 1. +- `maxProcesses` defines the maximum total number of worker processes Horizon may scale up to across all queues. This value should typically be greater than the number of queues multiplied by the `minProcesses` value. To prevent the supervisor from spawning any processes, you may set this value to 0. + +
+ +For example, you may configure Horizon to maintain at least one process per queue and scale up to a total of 10 worker processes: + +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + 'connection' => 'redis', + 'queue' => ['default', 'notifications'], + 'balance' => 'auto', + 'autoScalingStrategy' => 'time', + 'minProcesses' => 1, + 'maxProcesses' => 10, + 'balanceMaxShift' => 1, + 'balanceCooldown' => 3, + ], + ], +], +``` + +The `autoScalingStrategy` configuration option determines how Horizon will assign more worker processes to queues. You can choose between two strategies: + +
+ +- The `time` strategy will assign workers based on the total estimated amount of time it will take to clear the queue. +- The `size` strategy will assign workers based on the total number of jobs on the queue. + +
+ +The `balanceMaxShift` and `balanceCooldown` configuration values determine how quickly Horizon will scale to meet worker demand. In the example above, a maximum of one new process will be created or destroyed every three seconds. You are free to tweak these values as necessary based on your application's needs. + + +#### Queue Priorities and Auto Balancing + +When using the `auto` balancing strategy, Horizon does not enforce strict priority between queues. The order of queues in a supervisor's configuration does not affect how worker processes are assigned. Instead, Horizon relies on the selected `autoScalingStrategy` to dynamically allocate worker processes based on queue load. + +For example, in the following configuration, the high queue is not prioritized over the default queue, despite appearing first in the list: + +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'queue' => ['high', 'default'], + 'minProcesses' => 1, + 'maxProcesses' => 10, + ], + ], +], +``` + +If you need to enforce a relative priority between queues, you may define multiple supervisors and explicitly allocate processing resources: + +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'queue' => ['default'], + 'minProcesses' => 1, + 'maxProcesses' => 10, + ], + 'supervisor-2' => [ + // ... + 'queue' => ['images'], + 'minProcesses' => 1, + 'maxProcesses' => 1, + ], + ], +], +``` + +In this example, the default `queue` can scale up to 10 processes, while the `images` queue is limited to one process. This configuration ensures that your queues can scale independently. + +> [!NOTE] +> When dispatching resource-intensive jobs, it's sometimes best to assign them to a dedicated queue with a limited `maxProcesses` value. Otherwise, these jobs could consume excessive CPU resources and overload your system. + + +### Simple Balancing + +The `simple` strategy distributes worker processes evenly across the specified queues. With this strategy, Horizon does not automatically scale the number of worker processes. Rather, it uses a fixed number of processes: + +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'queue' => ['default', 'notifications'], + 'balance' => 'simple', + 'processes' => 10, + ], + ], +], +``` + +In the example above, Horizon will assign 5 processes to each queue, splitting the total of 10 evenly. + +If you'd like to control the number of worker processes assigned to each queue individually, you can define multiple supervisors: + +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'queue' => ['default'], + 'balance' => 'simple', + 'processes' => 10, + ], + 'supervisor-notifications' => [ + // ... + 'queue' => ['notifications'], + 'balance' => 'simple', + 'processes' => 2, + ], + ], +], +``` + +With this configuration, Horizon will assign 10 processes to the `default` queue and 2 processes to the `notifications` queue. + + +### No Balancing + +When the `balance` option is set to `false`, Horizon processes queues strictly in the order they're listed, similar to Laravel's default queue system. However, it will still scale the number of worker processes if jobs begin to accumulate: + +```php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + // ... + 'queue' => ['default', 'notifications'], + 'balance' => false, + 'minProcesses' => 1, + 'maxProcesses' => 10, + ], + ], +], +``` + +In the example above, jobs in the `default` queue are always prioritized over jobs in the `notifications` queue. For instance, if there are 1,000 jobs in `default` and only 10 in `notifications`, Horizon will fully process all `default` jobs before handling any from `notifications`. + +You can control Horizon's ability to scale worker processes using the `minProcesses` and `maxProcesses` options: + +
+ +- `minProcesses` defines the minimum number of worker processes in total. This value must be greater than or equal to 1. +- `maxProcesses` defines the maximum total number of worker processes Horizon may scale up to. + +
+ + +## Upgrading Horizon + +When upgrading to a new major version of Horizon, it's important that you carefully review [the upgrade guide](https://github.com/laravel/horizon/blob/master/UPGRADE.md). + ## Running Horizon @@ -194,7 +467,13 @@ You may check the current status of the Horizon process using the `horizon:statu php artisan horizon:status ``` -You may gracefully terminate the Horizon process using the `horizon:terminate` Artisan command. Any jobs that are currently being processed by will be completed and then Horizon will stop executing: +You may check the current status of a specific Horizon [supervisor](#supervisors) using the `horizon:supervisor-status` Artisan command: + +```shell +php artisan horizon:supervisor-status supervisor-1 +``` + +You may gracefully terminate the Horizon process using the `horizon:terminate` Artisan command. Any jobs that are currently being processed will be completed and then Horizon will stop executing: ```shell php artisan horizon:terminate @@ -220,7 +499,8 @@ Supervisor is a process monitor for the Linux operating system and will automati sudo apt-get install supervisor ``` -> {tip} If configuring Supervisor yourself sounds overwhelming, consider using [Laravel Forge](https://forge.laravel.com), which will automatically install and configure Supervisor for your Laravel projects. +> [!NOTE] +> If configuring Supervisor yourself sounds overwhelming, consider using [Laravel Cloud](https://cloud.laravel.com), which can manage background processes for your Laravel applications. #### Supervisor Configuration @@ -239,7 +519,10 @@ stdout_logfile=/home/forge/example.com/horizon.log stopwaitsecs=3600 ``` -> {note} You should ensure that the value of `stopwaitsecs` is greater than the number of seconds consumed by your longest running job. Otherwise, Supervisor may kill the job before it is finished processing. +When defining your Supervisor configuration, you should ensure that the value of `stopwaitsecs` is greater than the number of seconds consumed by your longest running job. Otherwise, Supervisor may kill the job before it is finished processing. + +> [!WARNING] +> While the examples above are valid for Ubuntu based servers, the location and file extension expected of Supervisor configuration files may vary between other server operating systems. Please consult your server's documentation for more information. #### Starting Supervisor @@ -254,130 +537,148 @@ sudo supervisorctl update sudo supervisorctl start horizon ``` -> {tip} For more information on running Supervisor, consult the [Supervisor documentation](http://supervisord.org/index.html). +> [!NOTE] +> For more information on running Supervisor, consult the [Supervisor documentation](http://supervisord.org/index.html). ## Tags -Horizon allows you to assign “tags” to jobs, including mailables, broadcast events, notifications, and queued event listeners. In fact, Horizon will intelligently and automatically tag most jobs depending on the Eloquent models that are attached to the job. For example, take a look at the following job: +Horizon allows you to assign "tags" to jobs, including mailables, broadcast events, notifications, and queued event listeners. In fact, Horizon will intelligently and automatically tag most jobs depending on the Eloquent models that are attached to the job. For example, take a look at the following job: - video = $video; - } - - /** - * Execute the job. - * - * @return void - */ - public function handle() - { - // - } + // ... } +} +``` If this job is queued with an `App\Models\Video` instance that has an `id` attribute of `1`, it will automatically receive the tag `App\Models\Video:1`. This is because Horizon will search the job's properties for any Eloquent models. If Eloquent models are found, Horizon will intelligently tag the job using the model's class name and primary key: - use App\Jobs\RenderVideo; - use App\Models\Video; +```php +use App\Jobs\RenderVideo; +use App\Models\Video; - $video = Video::find(1); +$video = Video::find(1); - RenderVideo::dispatch($video); +RenderVideo::dispatch($video); +``` #### Manually Tagging Jobs If you would like to manually define the tags for one of your queueable objects, you may define a `tags` method on the class: - class RenderVideo implements ShouldQueue +```php +class RenderVideo implements ShouldQueue +{ + /** + * Get the tags that should be assigned to the job. + * + * @return array + */ + public function tags(): array { - /** - * Get the tags that should be assigned to the job. - * - * @return array - */ - public function tags() - { - return ['render', 'video:'.$this->video->id]; - } + return ['render', 'video:'.$this->video->id]; } +} +``` - -## Notifications - -> {note} When configuring Horizon to send Slack or SMS notifications, you should review the [prerequisites for the relevant notification channel](/docs/{{version}}/notifications). + +#### Manually Tagging Event Listeners -If you would like to be notified when one of your queues has a long wait time, you may use the `Horizon::routeMailNotificationsTo`, `Horizon::routeSlackNotificationsTo`, and `Horizon::routeSmsNotificationsTo` methods. You may call these methods from the `boot` method of your application's `App\Providers\HorizonServiceProvider`: +When retrieving the tags for a queued event listener, Horizon will automatically pass the event instance to the `tags` method, allowing you to add event data to the tags: +```php +class SendRenderNotifications implements ShouldQueue +{ /** - * Bootstrap any application services. + * Get the tags that should be assigned to the listener. * - * @return void + * @return array */ - public function boot() + public function tags(VideoRendered $event): array { - parent::boot(); - - Horizon::routeSmsNotificationsTo('15556667777'); - Horizon::routeMailNotificationsTo('example@example.com'); - Horizon::routeSlackNotificationsTo('slack-webhook-url', '#channel'); + return ['video:'.$event->video->id]; } +} +``` + + +## Notifications + +> [!WARNING] +> When configuring Horizon to send Slack or SMS notifications, you should review the [prerequisites for the relevant notification channel](/docs/{{version}}/notifications). + +If you would like to be notified when one of your queues has a long wait time, you may use the `Horizon::routeMailNotificationsTo`, `Horizon::routeSlackNotificationsTo`, and `Horizon::routeSmsNotificationsTo` methods. You may call these methods from the `boot` method of your application's `App\Providers\HorizonServiceProvider`: + +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + parent::boot(); + + Horizon::routeSmsNotificationsTo('15556667777'); + Horizon::routeMailNotificationsTo('example@example.com'); + Horizon::routeSlackNotificationsTo('slack-webhook-url', '#channel'); +} +``` #### Configuring Notification Wait Time Thresholds -You may configure how many seconds are considered a "long wait" within your application's `config/horizon.php` configuration file. The `waits` configuration option within this file allows you to control the long wait threshold for each connection / queue combination: +You may configure how many seconds are considered a "long wait" within your application's `config/horizon.php` configuration file. The `waits` configuration option within this file allows you to control the long wait threshold for each connection / queue combination. Any undefined connection / queue combinations will default to a long wait threshold of 60 seconds: - 'waits' => [ - 'redis:default' => 60, - 'redis:critical,high' => 90, - ], +```php +'waits' => [ + 'redis:critical' => 30, + 'redis:default' => 60, + 'redis:batch' => 120, +], +``` + +Setting a queue's threshold to `0` will disable long wait notifications for that queue. ## Metrics -Horizon includes a metrics dashboard which provides information regarding your job and queue wait times and throughput. In order to populate this dashboard, you should configure Horizon's `snapshot` Artisan command to run every five minutes via your application's [scheduler](/docs/{{version}}/scheduling): +Horizon includes a metrics dashboard which provides information regarding your job and queue wait times and throughput. In order to populate this dashboard, you should configure Horizon's `snapshot` Artisan command to run every five minutes in your application's `routes/console.php` file: - /** - * Define the application's command schedule. - * - * @param \Illuminate\Console\Scheduling\Schedule $schedule - * @return void - */ - protected function schedule(Schedule $schedule) - { - $schedule->command('horizon:snapshot')->everyFiveMinutes(); - } +```php +use Illuminate\Support\Facades\Schedule; + +Schedule::command('horizon:snapshot')->everyFiveMinutes(); +``` + +If you would like to delete all metric data, you can invoke the `horizon:clear-metrics` Artisan command: + +```shell +php artisan horizon:clear-metrics +``` ## Deleting Failed Jobs @@ -388,6 +689,12 @@ If you would like to delete a failed job, you may use the `horizon:forget` comma php artisan horizon:forget 5 ``` +If you would like to delete all failed jobs, you may provide the `--all` option to the `horizon:forget` command: + +```shell +php artisan horizon:forget --all +``` + ## Clearing Jobs From Queues diff --git a/http-client.md b/http-client.md index 564e21ab1d7..9e9eb65328a 100644 --- a/http-client.md +++ b/http-client.md @@ -8,12 +8,16 @@ - [Timeout](#timeout) - [Retries](#retries) - [Error Handling](#error-handling) + - [Guzzle Middleware](#guzzle-middleware) - [Guzzle Options](#guzzle-options) - [Concurrent Requests](#concurrent-requests) + - [Request Pooling](#request-pooling) + - [Request Batching](#request-batching) - [Macros](#macros) - [Testing](#testing) - [Faking Responses](#faking-responses) - [Inspecting Requests](#inspecting-requests) + - [Preventing Stray Requests](#preventing-stray-requests) - [Events](#events) @@ -21,262 +25,620 @@ Laravel provides an expressive, minimal API around the [Guzzle HTTP client](http://docs.guzzlephp.org/en/stable/), allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel's wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience. -Before getting started, you should ensure that you have installed the Guzzle package as a dependency of your application. By default, Laravel automatically includes this dependency. However, if you have previously removed the package, you may install it again via Composer: - -```shell -composer require guzzlehttp/guzzle -``` - ## Making Requests To make requests, you may use the `head`, `get`, `post`, `put`, `patch`, and `delete` methods provided by the `Http` facade. First, let's examine how to make a basic `GET` request to another URL: - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Support\Facades\Http; - $response = Http::get('http://example.com/'); +$response = Http::get('http://example.com/'); +``` The `get` method returns an instance of `Illuminate\Http\Client\Response`, which provides a variety of methods that may be used to inspect the response: - $response->body() : string; - $response->json($key = null) : array|mixed; - $response->object() : object; - $response->collect($key = null) : Illuminate\Support\Collection; - $response->status() : int; - $response->ok() : bool; - $response->successful() : bool; - $response->redirect(): bool; - $response->failed() : bool; - $response->serverError() : bool; - $response->clientError() : bool; - $response->header($header) : string; - $response->headers() : array; +```php +$response->body() : string; +$response->json($key = null, $default = null) : mixed; +$response->object() : object; +$response->collect($key = null) : Illuminate\Support\Collection; +$response->resource() : resource; +$response->status() : int; +$response->successful() : bool; +$response->redirect(): bool; +$response->failed() : bool; +$response->clientError() : bool; +$response->header($header) : string; +$response->headers() : array; +``` The `Illuminate\Http\Client\Response` object also implements the PHP `ArrayAccess` interface, allowing you to access JSON response data directly on the response: - return Http::get('http://example.com/users/1')['name']; +```php +return Http::get('http://example.com/users/1')['name']; +``` + +In addition to the response methods listed above, the following methods may be used to determine if the response has a specific status code: + +```php +$response->ok() : bool; // 200 OK +$response->created() : bool; // 201 Created +$response->accepted() : bool; // 202 Accepted +$response->noContent() : bool; // 204 No Content +$response->movedPermanently() : bool; // 301 Moved Permanently +$response->found() : bool; // 302 Found +$response->badRequest() : bool; // 400 Bad Request +$response->unauthorized() : bool; // 401 Unauthorized +$response->paymentRequired() : bool; // 402 Payment Required +$response->forbidden() : bool; // 403 Forbidden +$response->notFound() : bool; // 404 Not Found +$response->requestTimeout() : bool; // 408 Request Timeout +$response->conflict() : bool; // 409 Conflict +$response->unprocessableEntity() : bool; // 422 Unprocessable Entity +$response->tooManyRequests() : bool; // 429 Too Many Requests +$response->serverError() : bool; // 500 Internal Server Error +``` + + +#### URI Templates + +The HTTP client also allows you to construct request URLs using the [URI template specification](https://www.rfc-editor.org/rfc/rfc6570). To define the URL parameters that can be expanded by your URI template, you may use the `withUrlParameters` method: + +```php +Http::withUrlParameters([ + 'endpoint' => 'https://laravel.com/', + 'page' => 'docs', + 'version' => '12.x', + 'topic' => 'validation', +])->get('{+endpoint}/{page}/{version}/{topic}'); +``` #### Dumping Requests If you would like to dump the outgoing request instance before it is sent and terminate the script's execution, you may add the `dd` method to the beginning of your request definition: - return Http::dd()->get('http://example.com/'); +```php +return Http::dd()->get('http://example.com/'); +``` ### Request Data Of course, it is common when making `POST`, `PUT`, and `PATCH` requests to send additional data with your request, so these methods accept an array of data as their second argument. By default, data will be sent using the `application/json` content type: - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Support\Facades\Http; - $response = Http::post('http://example.com/users', [ - 'name' => 'Steve', - 'role' => 'Network Administrator', - ]); +$response = Http::post('http://example.com/users', [ + 'name' => 'Steve', + 'role' => 'Network Administrator', +]); +``` #### GET Request Query Parameters When making `GET` requests, you may either append a query string to the URL directly or pass an array of key / value pairs as the second argument to the `get` method: - $response = Http::get('http://example.com/users', [ - 'name' => 'Taylor', - 'page' => 1, - ]); +```php +$response = Http::get('http://example.com/users', [ + 'name' => 'Taylor', + 'page' => 1, +]); +``` + +Alternatively, the `withQueryParameters` method may be used: + +```php +Http::retry(3, 100)->withQueryParameters([ + 'name' => 'Taylor', + 'page' => 1, +])->get('http://example.com/users'); +``` #### Sending Form URL Encoded Requests If you would like to send data using the `application/x-www-form-urlencoded` content type, you should call the `asForm` method before making your request: - $response = Http::asForm()->post('http://example.com/users', [ - 'name' => 'Sara', - 'role' => 'Privacy Consultant', - ]); +```php +$response = Http::asForm()->post('http://example.com/users', [ + 'name' => 'Sara', + 'role' => 'Privacy Consultant', +]); +``` -#### Sending A Raw Request Body +#### Sending a Raw Request Body You may use the `withBody` method if you would like to provide a raw request body when making a request. The content type may be provided via the method's second argument: - $response = Http::withBody( - base64_encode($photo), 'image/jpeg' - )->post('http://example.com/photo'); +```php +$response = Http::withBody( + base64_encode($photo), 'image/jpeg' +)->post('http://example.com/photo'); +``` #### Multi-Part Requests -If you would like to send files as multi-part requests, you should call the `attach` method before making your request. This method accepts the name of the file and its contents. If needed, you may provide a third argument which will be considered the file's filename: +If you would like to send files as multi-part requests, you should call the `attach` method before making your request. This method accepts the name of the file and its contents. If needed, you may provide a third argument which will be considered the file's filename, while a fourth argument may be used to provide headers associated with the file: - $response = Http::attach( - 'attachment', file_get_contents('photo.jpg'), 'photo.jpg' - )->post('http://example.com/attachments'); +```php +$response = Http::attach( + 'attachment', file_get_contents('photo.jpg'), 'photo.jpg', ['Content-Type' => 'image/jpeg'] +)->post('http://example.com/attachments'); +``` Instead of passing the raw contents of a file, you may pass a stream resource: - $photo = fopen('photo.jpg', 'r'); +```php +$photo = fopen('photo.jpg', 'r'); - $response = Http::attach( - 'attachment', $photo, 'photo.jpg' - )->post('http://example.com/attachments'); +$response = Http::attach( + 'attachment', $photo, 'photo.jpg' +)->post('http://example.com/attachments'); +``` ### Headers Headers may be added to requests using the `withHeaders` method. This `withHeaders` method accepts an array of key / value pairs: - $response = Http::withHeaders([ - 'X-First' => 'foo', - 'X-Second' => 'bar' - ])->post('http://example.com/users', [ - 'name' => 'Taylor', - ]); +```php +$response = Http::withHeaders([ + 'X-First' => 'foo', + 'X-Second' => 'bar' +])->post('http://example.com/users', [ + 'name' => 'Taylor', +]); +``` You may use the `accept` method to specify the content type that your application is expecting in response to your request: - $response = Http::accept('application/json')->get('http://example.com/users'); +```php +$response = Http::accept('application/json')->get('http://example.com/users'); +``` For convenience, you may use the `acceptJson` method to quickly specify that your application expects the `application/json` content type in response to your request: - $response = Http::acceptJson()->get('http://example.com/users'); +```php +$response = Http::acceptJson()->get('http://example.com/users'); +``` + +The `withHeaders` method merges new headers into the request's existing headers. If needed, you may replace all of the headers entirely using the `replaceHeaders` method: + +```php +$response = Http::withHeaders([ + 'X-Original' => 'foo', +])->replaceHeaders([ + 'X-Replacement' => 'bar', +])->post('http://example.com/users', [ + 'name' => 'Taylor', +]); +``` ### Authentication You may specify basic and digest authentication credentials using the `withBasicAuth` and `withDigestAuth` methods, respectively: - // Basic authentication... - $response = Http::withBasicAuth('taylor@laravel.com', 'secret')->post(...); +```php +// Basic authentication... +$response = Http::withBasicAuth('taylor@laravel.com', 'secret')->post(/* ... */); - // Digest authentication... - $response = Http::withDigestAuth('taylor@laravel.com', 'secret')->post(...); +// Digest authentication... +$response = Http::withDigestAuth('taylor@laravel.com', 'secret')->post(/* ... */); +``` #### Bearer Tokens If you would like to quickly add a bearer token to the request's `Authorization` header, you may use the `withToken` method: - $response = Http::withToken('token')->post(...); +```php +$response = Http::withToken('token')->post(/* ... */); +``` ### Timeout -The `timeout` method may be used to specify the maximum number of seconds to wait for a response: +The `timeout` method may be used to specify the maximum number of seconds to wait for a response. By default, the HTTP client will timeout after 30 seconds: - $response = Http::timeout(3)->get(...); +```php +$response = Http::timeout(3)->get(/* ... */); +``` If the given timeout is exceeded, an instance of `Illuminate\Http\Client\ConnectionException` will be thrown. -You may specify the maximum number of seconds to wait while trying to connect to a server using the `connectTimeout` method: +You may specify the maximum number of seconds to wait while trying to connect to a server using the `connectTimeout` method. The default is 10 seconds: - $response = Http::connectTimeout(3)->get(...); +```php +$response = Http::connectTimeout(3)->get(/* ... */); +``` ### Retries -If you would like HTTP client to automatically retry the request if a client or server error occurs, you may use the `retry` method. The `retry` method accepts the maximum number of times the request should be attempted and the number of milliseconds that Laravel should wait in between attempts: +If you would like the HTTP client to automatically retry the request if a client or server error occurs, you may use the `retry` method. The `retry` method accepts the maximum number of times the request should be attempted and the number of milliseconds that Laravel should wait in between attempts: + +```php +$response = Http::retry(3, 100)->post(/* ... */); +``` + +If you would like to manually calculate the number of milliseconds to sleep between attempts, you may pass a closure as the second argument to the `retry` method: + +```php +use Exception; + +$response = Http::retry(3, function (int $attempt, Exception $exception) { + return $attempt * 100; +})->post(/* ... */); +``` + +For convenience, you may also provide an array as the first argument to the `retry` method. This array will be used to determine how many milliseconds to sleep between subsequent attempts: - $response = Http::retry(3, 100)->post(...); +```php +$response = Http::retry([100, 200])->post(/* ... */); +``` If needed, you may pass a third argument to the `retry` method. The third argument should be a callable that determines if the retries should actually be attempted. For example, you may wish to only retry the request if the initial request encounters an `ConnectionException`: - $response = Http::retry(3, 100, function ($exception) { - return $exception instanceof ConnectionException; - })->post(...); +```php +use Exception; +use Illuminate\Http\Client\PendingRequest; + +$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) { + return $exception instanceof ConnectionException; +})->post(/* ... */); +``` + +If a request attempt fails, you may wish to make a change to the request before a new attempt is made. You can achieve this by modifying the request argument provided to the callable you provided to the `retry` method. For example, you might want to retry the request with a new authorization token if the first attempt returned an authentication error: + +```php +use Exception; +use Illuminate\Http\Client\PendingRequest; +use Illuminate\Http\Client\RequestException; + +$response = Http::withToken($this->getToken())->retry(2, 0, function (Exception $exception, PendingRequest $request) { + if (! $exception instanceof RequestException || $exception->response->status() !== 401) { + return false; + } + + $request->withToken($this->getNewToken()); + + return true; +})->post(/* ... */); +``` If all of the requests fail, an instance of `Illuminate\Http\Client\RequestException` will be thrown. If you would like to disable this behavior, you may provide a `throw` argument with a value of `false`. When disabled, the last response received by the client will be returned after all retries have been attempted: - $response = Http::retry(3, 100, throw: false)->post(...); +```php +$response = Http::retry(3, 100, throw: false)->post(/* ... */); +``` + +> [!WARNING] +> If all of the requests fail because of a connection issue, a `Illuminate\Http\Client\ConnectionException` will still be thrown even when the `throw` argument is set to `false`. ### Error Handling Unlike Guzzle's default behavior, Laravel's HTTP client wrapper does not throw exceptions on client or server errors (`400` and `500` level responses from servers). You may determine if one of these errors was returned using the `successful`, `clientError`, or `serverError` methods: - // Determine if the status code is >= 200 and < 300... - $response->successful(); +```php +// Determine if the status code is >= 200 and < 300... +$response->successful(); - // Determine if the status code is >= 400... - $response->failed(); +// Determine if the status code is >= 400... +$response->failed(); - // Determine if the response has a 400 level status code... - $response->clientError(); +// Determine if the response has a 400 level status code... +$response->clientError(); - // Determine if the response has a 500 level status code... - $response->serverError(); +// Determine if the response has a 500 level status code... +$response->serverError(); - // Immediately execute the given callback if there was a client or server error... - $response->onError(callable $callback); +// Immediately execute the given callback if there was a client or server error... +$response->onError(callable $callback); +``` #### Throwing Exceptions If you have a response instance and would like to throw an instance of `Illuminate\Http\Client\RequestException` if the response status code indicates a client or server error, you may use the `throw` or `throwIf` methods: - $response = Http::post(...); +```php +use Illuminate\Http\Client\Response; - // Throw an exception if a client or server error occurred... - $response->throw(); +$response = Http::post(/* ... */); - // Throw an exception if an error occurred and the given condition is true... - $response->throwIf($condition); +// Throw an exception if a client or server error occurred... +$response->throw(); - return $response['user']['id']; +// Throw an exception if an error occurred and the given condition is true... +$response->throwIf($condition); + +// Throw an exception if an error occurred and the given closure resolves to true... +$response->throwIf(fn (Response $response) => true); + +// Throw an exception if an error occurred and the given condition is false... +$response->throwUnless($condition); + +// Throw an exception if an error occurred and the given closure resolves to false... +$response->throwUnless(fn (Response $response) => false); + +// Throw an exception if the response has a specific status code... +$response->throwIfStatus(403); + +// Throw an exception unless the response has a specific status code... +$response->throwUnlessStatus(200); + +return $response['user']['id']; +``` The `Illuminate\Http\Client\RequestException` instance has a public `$response` property which will allow you to inspect the returned response. The `throw` method returns the response instance if no error occurred, allowing you to chain other operations onto the `throw` method: - return Http::post(...)->throw()->json(); +```php +return Http::post(/* ... */)->throw()->json(); +``` If you would like to perform some additional logic before the exception is thrown, you may pass a closure to the `throw` method. The exception will be thrown automatically after the closure is invoked, so you do not need to re-throw the exception from within the closure: - return Http::post(...)->throw(function ($response, $e) { - // - })->json(); +```php +use Illuminate\Http\Client\Response; +use Illuminate\Http\Client\RequestException; + +return Http::post(/* ... */)->throw(function (Response $response, RequestException $e) { + // ... +})->json(); +``` + +By default, `RequestException` messages are truncated to 120 characters when logged or reported. To customize or disable this behavior, you may utilize the `truncateRequestExceptionsAt` and `dontTruncateRequestExceptions` methods when configuring your application's exception handling behavior in your `bootstrap/app.php` file: + +```php +use Illuminate\Foundation\Configuration\Exceptions; + +->withExceptions(function (Exceptions $exceptions): void { + // Truncate request exception messages to 240 characters... + $exceptions->truncateRequestExceptionsAt(240); + + // Disable request exception message truncation... + $exceptions->dontTruncateRequestExceptions(); +}) +``` + +Alternatively, you may customize the exception truncation behavior per request using the `truncateExceptionsAt` method: + +```php +return Http::truncateExceptionsAt(240)->post(/* ... */); +``` + + +### Guzzle Middleware + +Since Laravel's HTTP client is powered by Guzzle, you may take advantage of [Guzzle Middleware](https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html) to manipulate the outgoing request or inspect the incoming response. To manipulate the outgoing request, register a Guzzle middleware via the `withRequestMiddleware` method: + +```php +use Illuminate\Support\Facades\Http; +use Psr\Http\Message\RequestInterface; + +$response = Http::withRequestMiddleware( + function (RequestInterface $request) { + return $request->withHeader('X-Example', 'Value'); + } +)->get('http://example.com/'); +``` + +Likewise, you can inspect the incoming HTTP response by registering a middleware via the `withResponseMiddleware` method: + +```php +use Illuminate\Support\Facades\Http; +use Psr\Http\Message\ResponseInterface; + +$response = Http::withResponseMiddleware( + function (ResponseInterface $response) { + $header = $response->getHeader('X-Example'); + + // ... + + return $response; + } +)->get('http://example.com/'); +``` + + +#### Global Middleware + +Sometimes, you may want to register a middleware that applies to every outgoing request and incoming response. To accomplish this, you may use the `globalRequestMiddleware` and `globalResponseMiddleware` methods. Typically, these methods should be invoked in the `boot` method of your application's `AppServiceProvider`: + +```php +use Illuminate\Support\Facades\Http; + +Http::globalRequestMiddleware(fn ($request) => $request->withHeader( + 'User-Agent', 'Example Application/1.0' +)); + +Http::globalResponseMiddleware(fn ($response) => $response->withHeader( + 'X-Finished-At', now()->toDateTimeString() +)); +``` ### Guzzle Options -You may specify additional [Guzzle request options](http://docs.guzzlephp.org/en/stable/request-options.html) using the `withOptions` method. The `withOptions` method accepts an array of key / value pairs: +You may specify additional [Guzzle request options](http://docs.guzzlephp.org/en/stable/request-options.html) for an outgoing request using the `withOptions` method. The `withOptions` method accepts an array of key / value pairs: + +```php +$response = Http::withOptions([ + 'debug' => true, +])->get('http://example.com/users'); +``` + + +#### Global Options + +To configure default options for every outgoing request, you may utilize the `globalOptions` method. Typically, this method should be invoked from the `boot` method of your application's `AppServiceProvider`: + +```php +use Illuminate\Support\Facades\Http; - $response = Http::withOptions([ - 'debug' => true, - ])->get('http://example.com/users'); +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Http::globalOptions([ + 'allow_redirects' => false, + ]); +} +``` ## Concurrent Requests Sometimes, you may wish to make multiple HTTP requests concurrently. In other words, you want several requests to be dispatched at the same time instead of issuing the requests sequentially. This can lead to substantial performance improvements when interacting with slow HTTP APIs. + +### Request Pooling + Thankfully, you may accomplish this using the `pool` method. The `pool` method accepts a closure which receives an `Illuminate\Http\Client\Pool` instance, allowing you to easily add requests to the request pool for dispatching: - use Illuminate\Http\Client\Pool; - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Http\Client\Pool; +use Illuminate\Support\Facades\Http; - $responses = Http::pool(fn (Pool $pool) => [ - $pool->get('http://localhost/first'), - $pool->get('http://localhost/second'), - $pool->get('http://localhost/third'), - ]); +$responses = Http::pool(fn (Pool $pool) => [ + $pool->get('http://localhost/first'), + $pool->get('http://localhost/second'), + $pool->get('http://localhost/third'), +]); - return $responses[0]->ok() && - $responses[1]->ok() && - $responses[2]->ok(); +return $responses[0]->ok() && + $responses[1]->ok() && + $responses[2]->ok(); +``` As you can see, each response instance can be accessed based on the order it was added to the pool. If you wish, you can name the requests using the `as` method, which allows you to access the corresponding responses by name: - use Illuminate\Http\Client\Pool; - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Http\Client\Pool; +use Illuminate\Support\Facades\Http; - $responses = Http::pool(fn (Pool $pool) => [ - $pool->as('first')->get('http://localhost/first'), - $pool->as('second')->get('http://localhost/second'), - $pool->as('third')->get('http://localhost/third'), - ]); +$responses = Http::pool(fn (Pool $pool) => [ + $pool->as('first')->get('http://localhost/first'), + $pool->as('second')->get('http://localhost/second'), + $pool->as('third')->get('http://localhost/third'), +]); - return $responses['first']->ok(); +return $responses['first']->ok(); +``` + + +#### Customizing Concurrent Requests + +The `pool` method cannot be chained with other HTTP client methods such as the `withHeaders` or `middleware` methods. If you want to apply custom headers or middleware to pooled requests, you should configure those options on each request in the pool: + +```php +use Illuminate\Http\Client\Pool; +use Illuminate\Support\Facades\Http; + +$headers = [ + 'X-Example' => 'example', +]; + +$responses = Http::pool(fn (Pool $pool) => [ + $pool->withHeaders($headers)->get('http://laravel.test/test'), + $pool->withHeaders($headers)->get('http://laravel.test/test'), + $pool->withHeaders($headers)->get('http://laravel.test/test'), +]); +``` + + +### Request Batching + +Another way of working with concurrent requests in Laravel is to use the `batch` method. Like the `pool` method, it accepts a closure which receives an `Illuminate\Http\Client\Batch` instance, allowing you to easily add requests to the request pool for dispatching, but it also allows you to define completion callbacks: + +```php +use Illuminate\Http\Client\Batch; +use Illuminate\Http\Client\ConnectionException; +use Illuminate\Http\Client\RequestException; +use Illuminate\Http\Client\Response; +use Illuminate\Support\Facades\Http; + +$responses = Http::batch(fn (Batch $batch) => [ + $batch->get('http://localhost/first'), + $batch->get('http://localhost/second'), + $batch->get('http://localhost/third'), +])->before(function (Batch $batch) { + // The batch has been created but no requests have been initialized... +})->progress(function (Batch $batch, int|string $key, Response $response) { + // An individual request has completed successfully... +})->then(function (Batch $batch, array $results) { + // All requests completed successfully... +})->catch(function (Batch $batch, int|string $key, Response|RequestException|ConnectionException $response) { + // First batch request failure detected... +})->finally(function (Batch $batch, array $results) { + // The batch has finished executing... +})->send(); +``` + +Like the `pool` method, you can use the `as` method to name your requests: + +```php +$responses = Http::batch(fn (Batch $batch) => [ + $batch->as('first')->get('http://localhost/first'), + $batch->as('second')->get('http://localhost/second'), + $batch->as('third')->get('http://localhost/third'), +])->send(); +``` + +After a `batch` is started by calling the `send` method, you can't add new requests to it. Trying to do so will result in a `Illuminate\Http\Client\BatchInProgressException` exception being thrown. + + +#### Inspecting Batches + +The `Illuminate\Http\Client\Batch` instance that is provided to batch completion callbacks has a variety of properties and methods to assist you in interacting with and inspecting a given batch of requests: + +```php +// The number of requests assigned to the batch... +$batch->totalRequests; + +// The number of requests that have not been processed yet... +$batch->pendingRequests; + +// The number of requests that have failed... +$batch->failedRequests; + +// The number of requests that have been processed thus far... +$batch->processedRequests(); + +// Indicates if the batch has finished executing... +$batch->finished(); + +// Indicates if the batch has request failures... +$batch->hasFailures(); +``` + +#### Deferring Batches + +When the `defer` method is invoked, the batch of requests is not executed immediately. Instead, Laravel will execute the batch after the current application request's HTTP response has been sent to the user, keeping your application feeling fast and responsive: + +```php +use Illuminate\Http\Client\Batch; +use Illuminate\Support\Facades\Http; + +$responses = Http::batch(fn (Batch $batch) => [ + $batch->get('http://localhost/first'), + $batch->get('http://localhost/second'), + $batch->get('http://localhost/third'), +])->then(function (Batch $batch, array $results) { + // All requests completed successfully... +})->defer(); +``` ## Macros @@ -288,10 +650,8 @@ use Illuminate\Support\Facades\Http; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Http::macro('github', function () { return Http::withHeaders([ @@ -310,79 +670,124 @@ $response = Http::github()->get('/'); ## Testing -Many Laravel services provide functionality to help you easily and expressively write tests, and Laravel's HTTP wrapper is no exception. The `Http` facade's `fake` method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made. +Many Laravel services provide functionality to help you easily and expressively write tests, and Laravel's HTTP client is no exception. The `Http` facade's `fake` method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made. ### Faking Responses For example, to instruct the HTTP client to return empty, `200` status code responses for every request, you may call the `fake` method with no arguments: - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Support\Facades\Http; - Http::fake(); +Http::fake(); - $response = Http::post(...); +$response = Http::post(/* ... */); +``` #### Faking Specific URLs -Alternatively, you may pass an array to the `fake` method. The array's keys should represent URL patterns that you wish to fake and their associated responses. The `*` character may be used as a wildcard character. Any requests made to URLs that have not been faked will actually be executed. You may use the `Http` facade's `response` method to construct stub / fake responses for these endpoints: +Alternatively, you may pass an array to the `fake` method. The array's keys should represent URL patterns that you wish to fake and their associated responses. The `*` character may be used as a wildcard character. You may use the `Http` facade's `response` method to construct stub / fake responses for these endpoints: - Http::fake([ - // Stub a JSON response for GitHub endpoints... - 'github.com/*' => Http::response(['foo' => 'bar'], 200, $headers), +```php +Http::fake([ + // Stub a JSON response for GitHub endpoints... + 'github.com/*' => Http::response(['foo' => 'bar'], 200, $headers), - // Stub a string response for Google endpoints... - 'google.com/*' => Http::response('Hello World', 200, $headers), - ]); + // Stub a string response for Google endpoints... + 'google.com/*' => Http::response('Hello World', 200, $headers), +]); +``` -If you would like to specify a fallback URL pattern that will stub all unmatched URLs, you may use a single `*` character: +Any requests made to URLs that have not been faked will actually be executed. If you would like to specify a fallback URL pattern that will stub all unmatched URLs, you may use a single `*` character: - Http::fake([ - // Stub a JSON response for GitHub endpoints... - 'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']), +```php +Http::fake([ + // Stub a JSON response for GitHub endpoints... + 'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']), - // Stub a string response for all other endpoints... - '*' => Http::response('Hello World', 200, ['Headers']), - ]); + // Stub a string response for all other endpoints... + '*' => Http::response('Hello World', 200, ['Headers']), +]); +``` + +For convenience, simple string, JSON, and empty responses may be generated by providing a string, array, or integer as the response: + +```php +Http::fake([ + 'google.com/*' => 'Hello World', + 'github.com/*' => ['foo' => 'bar'], + 'chatgpt.com/*' => 200, +]); +``` + + +#### Faking Exceptions + +Sometimes you may need to test your application's behavior if the HTTP client encounters an `Illuminate\Http\Client\ConnectionException` when attempting to make a request. You can instruct the HTTP client to throw a connection exception using the `failedConnection` method: + +```php +Http::fake([ + 'github.com/*' => Http::failedConnection(), +]); +``` + +To test your application's behavior if a `Illuminate\Http\Client\RequestException` is thrown, you may use the `failedRequest` method: + +```php +Http::fake([ + 'github.com/*' => Http::failedRequest(['code' => 'not_found'], 404), +]); +``` #### Faking Response Sequences Sometimes you may need to specify that a single URL should return a series of fake responses in a specific order. You may accomplish this using the `Http::sequence` method to build the responses: - Http::fake([ - // Stub a series of responses for GitHub endpoints... - 'github.com/*' => Http::sequence() - ->push('Hello World', 200) - ->push(['foo' => 'bar'], 200) - ->pushStatus(404), - ]); +```php +Http::fake([ + // Stub a series of responses for GitHub endpoints... + 'github.com/*' => Http::sequence() + ->push('Hello World', 200) + ->push(['foo' => 'bar'], 200) + ->pushStatus(404), +]); +``` -When all of the responses in a response sequence have been consumed, any further requests will cause the response sequence to throw an exception. If you would like to specify a default response that should be returned when a sequence is empty, you may use the `whenEmpty` method: +When all the responses in a response sequence have been consumed, any further requests will cause the response sequence to throw an exception. If you would like to specify a default response that should be returned when a sequence is empty, you may use the `whenEmpty` method: - Http::fake([ - // Stub a series of responses for GitHub endpoints... - 'github.com/*' => Http::sequence() - ->push('Hello World', 200) - ->push(['foo' => 'bar'], 200) - ->whenEmpty(Http::response()), - ]); +```php +Http::fake([ + // Stub a series of responses for GitHub endpoints... + 'github.com/*' => Http::sequence() + ->push('Hello World', 200) + ->push(['foo' => 'bar'], 200) + ->whenEmpty(Http::response()), +]); +``` If you would like to fake a sequence of responses but do not need to specify a specific URL pattern that should be faked, you may use the `Http::fakeSequence` method: - Http::fakeSequence() - ->push('Hello World', 200) - ->whenEmpty(Http::response()); +```php +Http::fakeSequence() + ->push('Hello World', 200) + ->whenEmpty(Http::response()); +``` #### Fake Callback If you require more complicated logic to determine what responses to return for certain endpoints, you may pass a closure to the `fake` method. This closure will receive an instance of `Illuminate\Http\Client\Request` and should return a response instance. Within your closure, you may perform whatever logic is necessary to determine what type of response to return: - Http::fake(function ($request) { - return Http::response('Hello World', 200); - }); +```php +use Illuminate\Http\Client\Request; + +Http::fake(function (Request $request) { + return Http::response('Hello World', 200); +}); +``` ### Inspecting Requests @@ -391,73 +796,157 @@ When faking responses, you may occasionally wish to inspect the requests the cli The `assertSent` method accepts a closure which will receive an `Illuminate\Http\Client\Request` instance and should return a boolean value indicating if the request matches your expectations. In order for the test to pass, at least one request must have been issued matching the given expectations: - use Illuminate\Http\Client\Request; - use Illuminate\Support\Facades\Http; - - Http::fake(); - - Http::withHeaders([ - 'X-First' => 'foo', - ])->post('http://example.com/users', [ - 'name' => 'Taylor', - 'role' => 'Developer', - ]); +```php +use Illuminate\Http\Client\Request; +use Illuminate\Support\Facades\Http; - Http::assertSent(function (Request $request) { - return $request->hasHeader('X-First', 'foo') && - $request->url() == 'http://example.com/users' && - $request['name'] == 'Taylor' && - $request['role'] == 'Developer'; - }); +Http::fake(); + +Http::withHeaders([ + 'X-First' => 'foo', +])->post('http://example.com/users', [ + 'name' => 'Taylor', + 'role' => 'Developer', +]); + +Http::assertSent(function (Request $request) { + return $request->hasHeader('X-First', 'foo') && + $request->url() == 'http://example.com/users' && + $request['name'] == 'Taylor' && + $request['role'] == 'Developer'; +}); +``` If needed, you may assert that a specific request was not sent using the `assertNotSent` method: - use Illuminate\Http\Client\Request; - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Http\Client\Request; +use Illuminate\Support\Facades\Http; - Http::fake(); +Http::fake(); - Http::post('http://example.com/users', [ - 'name' => 'Taylor', - 'role' => 'Developer', - ]); +Http::post('http://example.com/users', [ + 'name' => 'Taylor', + 'role' => 'Developer', +]); - Http::assertNotSent(function (Request $request) { - return $request->url() === 'http://example.com/posts'; - }); +Http::assertNotSent(function (Request $request) { + return $request->url() === 'http://example.com/posts'; +}); +``` You may use the `assertSentCount` method to assert how many requests were "sent" during the test: - Http::fake(); +```php +Http::fake(); - Http::assertSentCount(5); +Http::assertSentCount(5); +``` Or, you may use the `assertNothingSent` method to assert that no requests were sent during the test: - Http::fake(); +```php +Http::fake(); + +Http::assertNothingSent(); +``` + + +#### Recording Requests / Responses + +You may use the `recorded` method to gather all requests and their corresponding responses. The `recorded` method returns a collection of arrays that contains instances of `Illuminate\Http\Client\Request` and `Illuminate\Http\Client\Response`: + +```php +Http::fake([ + 'https://laravel.com/' => Http::response(status: 500), + 'https://nova.laravel.com/' => Http::response(), +]); - Http::assertNothingSent(); +Http::get('https://laravel.com/'); +Http::get('https://nova.laravel.com/'); + +$recorded = Http::recorded(); + +[$request, $response] = $recorded[0]; +``` + +Additionally, the `recorded` method accepts a closure which will receive an instance of `Illuminate\Http\Client\Request` and `Illuminate\Http\Client\Response` and may be used to filter request / response pairs based on your expectations: + +```php +use Illuminate\Http\Client\Request; +use Illuminate\Http\Client\Response; + +Http::fake([ + 'https://laravel.com/' => Http::response(status: 500), + 'https://nova.laravel.com/' => Http::response(), +]); + +Http::get('https://laravel.com/'); +Http::get('https://nova.laravel.com/'); + +$recorded = Http::recorded(function (Request $request, Response $response) { + return $request->url() !== 'https://laravel.com/' && + $response->successful(); +}); +``` + + +### Preventing Stray Requests + +If you would like to ensure that all requests sent via the HTTP client have been faked throughout your individual test or complete test suite, you can call the `preventStrayRequests` method. After calling this method, any requests that do not have a corresponding fake response will throw an exception rather than making the actual HTTP request: + +```php +use Illuminate\Support\Facades\Http; + +Http::preventStrayRequests(); + +Http::fake([ + 'github.com/*' => Http::response('ok'), +]); + +// An "ok" response is returned... +Http::get('https://github.com/laravel/framework'); + +// An exception is thrown... +Http::get('https://laravel.com/'); +``` + +Sometimes, you may wish to prevent most stray requests while still allowing specific requests to execute. To accomplish this, you may pass an array of URL patterns to the `allowStrayRequests` method. Any request matching one of the given patterns will be allowed, while all other requests will continue to throw an exception: + +```php +use Illuminate\Support\Facades\Http; + +Http::preventStrayRequests(); + +Http::allowStrayRequests([ + 'http://127.0.0.1:5000/*', +]); + +// This request is executed... +Http::get('http://127.0.0.1:5000/generate'); + +// An exception is thrown... +Http::get('https://laravel.com/'); +``` ## Events Laravel fires three events during the process of sending HTTP requests. The `RequestSending` event is fired prior to a request being sent, while the `ResponseReceived` event is fired after a response is received for a given request. The `ConnectionFailed` event is fired if no response is received for a given request. -The `RequestSending` and `ConnectionFailed` events both contain a public `$request` property that you may use to inspect the `Illuminate\Http\Client\Request` instance. Likewise, the `ResponseReceived` event contains a `$request` property as well as a `$response` property which may be used to inspect the `Illuminate\Http\Client\Response` instance. You may register event listeners for this event in your `App\Providers\EventServiceProvider` service provider: +The `RequestSending` and `ConnectionFailed` events both contain a public `$request` property that you may use to inspect the `Illuminate\Http\Client\Request` instance. Likewise, the `ResponseReceived` event contains a `$request` property as well as a `$response` property which may be used to inspect the `Illuminate\Http\Client\Response` instance. You may create [event listeners](/docs/{{version}}/events) for these events within your application: + +```php +use Illuminate\Http\Client\Events\RequestSending; +class LogRequest +{ /** - * The event listener mappings for the application. - * - * @var array + * Handle the event. */ - protected $listen = [ - 'Illuminate\Http\Client\Events\RequestSending' => [ - 'App\Listeners\LogRequestSending', - ], - 'Illuminate\Http\Client\Events\ResponseReceived' => [ - 'App\Listeners\LogResponseReceived', - ], - 'Illuminate\Http\Client\Events\ConnectionFailed' => [ - 'App\Listeners\LogConnectionFailed', - ], - ]; + public function handle(RequestSending $event): void + { + // $event->request ... + } +} +``` diff --git a/http-tests.md b/http-tests.md index 1b3855f2368..4f705ea3dd4 100644 --- a/http-tests.md +++ b/http-tests.md @@ -11,38 +11,47 @@ - [Fluent JSON Testing](#fluent-json-testing) - [Testing File Uploads](#testing-file-uploads) - [Testing Views](#testing-views) - - [Rendering Blade & Components](#rendering-blade-and-components) + - [Rendering Blade and Components](#rendering-blade-and-components) - [Available Assertions](#available-assertions) - [Response Assertions](#response-assertions) - [Authentication Assertions](#authentication-assertions) + - [Validation Assertions](#validation-assertions) ## Introduction Laravel provides a very fluent API for making HTTP requests to your application and examining the responses. For example, take a look at the feature test defined below: - get('/'); - use Illuminate\Foundation\Testing\RefreshDatabase; - use Illuminate\Foundation\Testing\WithoutMiddleware; - use Tests\TestCase; + $response->assertStatus(200); +}); +``` + +```php tab=PHPUnit +get('/'); + $response = $this->get('/'); - $response->assertStatus(200); - } + $response->assertStatus(200); } +} +``` The `get` method makes a `GET` request into the application, while the `assertStatus` method asserts that the returned response should have the given HTTP status code. In addition to this simple assertion, Laravel also contains a variety of assertions for inspecting the response headers, content, JSON structure, and more. @@ -53,426 +62,720 @@ To make a request to your application, you may invoke the `get`, `post`, `put`, Instead of returning an `Illuminate\Http\Response` instance, test request methods return an instance of `Illuminate\Testing\TestResponse`, which provides a [variety of helpful assertions](#available-assertions) that allow you to inspect your application's responses: - get('/'); - namespace Tests\Feature; + $response->assertStatus(200); +}); +``` + +```php tab=PHPUnit +get('/'); + $response = $this->get('/'); - $response->assertStatus(200); - } + $response->assertStatus(200); } +} +``` In general, each of your tests should only make one request to your application. Unexpected behavior may occur if multiple requests are executed within a single test method. -> {tip} For convenience, the CSRF middleware is automatically disabled when running tests. +> [!NOTE] +> For convenience, the CSRF middleware is automatically disabled when running tests. ### Customizing Request Headers You may use the `withHeaders` method to customize the request's headers before it is sent to the application. This method allows you to add any custom headers you would like to the request: - withHeaders([ + 'X-Header' => 'Value', + ])->post('/user', ['name' => 'Sally']); + + $response->assertStatus(201); +}); +``` + +```php tab=PHPUnit +withHeaders([ - 'X-Header' => 'Value', - ])->post('/user', ['name' => 'Sally']); + $response = $this->withHeaders([ + 'X-Header' => 'Value', + ])->post('/user', ['name' => 'Sally']); - $response->assertStatus(201); - } + $response->assertStatus(201); } +} +``` ### Cookies You may use the `withCookie` or `withCookies` methods to set cookie values before making a request. The `withCookie` method accepts a cookie name and value as its two arguments, while the `withCookies` method accepts an array of name / value pairs: - withCookie('color', 'blue')->get('/'); + + $response = $this->withCookies([ + 'color' => 'blue', + 'name' => 'Taylor', + ])->get('/'); - namespace Tests\Feature; + // +}); +``` + +```php tab=PHPUnit +withCookie('color', 'blue')->get('/'); + $response = $this->withCookie('color', 'blue')->get('/'); - $response = $this->withCookies([ - 'color' => 'blue', - 'name' => 'Taylor', - ])->get('/'); - } + $response = $this->withCookies([ + 'color' => 'blue', + 'name' => 'Taylor', + ])->get('/'); + + // } +} +``` ### Session / Authentication Laravel provides several helpers for interacting with the session during HTTP testing. First, you may set the session data to a given array using the `withSession` method. This is useful for loading the session with data before issuing a request to your application: - withSession(['banned' => false])->get('/'); + + // +}); +``` - namespace Tests\Feature; +```php tab=PHPUnit +withSession(['banned' => false])->get('/'); - } + $response = $this->withSession(['banned' => false])->get('/'); + + // } +} +``` + +Laravel's session is typically used to maintain state for the currently authenticated user. Therefore, the `actingAs` helper method provides a simple way to authenticate a given user as the current user. For example, we may use a [model factory](/docs/{{version}}/eloquent-factories) to generate and authenticate a user: -Laravel's session is typically used to maintain state for the currently authenticated user. Therefore, the `actingAs` helper method provides a simple way to authenticate a given user as the current user. For example, we may use a [model factory](/docs/{{version}}/database-testing#writing-factories) to generate and authenticate a user: +```php tab=Pest +create(); - use App\Models\User; - use Tests\TestCase; + $response = $this->actingAs($user) + ->withSession(['banned' => false]) + ->get('/'); - class ExampleTest extends TestCase + // +}); +``` + +```php tab=PHPUnit +create(); + $user = User::factory()->create(); - $response = $this->actingAs($user) - ->withSession(['banned' => false]) - ->get('/'); - } + $response = $this->actingAs($user) + ->withSession(['banned' => false]) + ->get('/'); + + // } +} +``` -You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the `actingAs` method: +You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the `actingAs` method. The guard that is provided to the `actingAs` method will also become the default guard for the duration of the test: - $this->actingAs($user, 'web') +```php +$this->actingAs($user, 'web'); +``` + +If you would like to ensure the request is unauthenticated, you may use the `actingAsGuest` method: + +```php +$this->actingAsGuest(); +``` ### Debugging Responses After making a test request to your application, the `dump`, `dumpHeaders`, and `dumpSession` methods may be used to examine and debug the response contents: - get('/'); - use Tests\TestCase; + $response->dump(); + $response->dumpHeaders(); + $response->dumpSession(); +}); +``` - class ExampleTest extends TestCase - { - /** - * A basic test example. - * - * @return void - */ - public function test_basic_test() - { - $response = $this->get('/'); +```php tab=PHPUnit +dumpHeaders(); +namespace Tests\Feature; - $response->dumpSession(); +use Tests\TestCase; - $response->dump(); - } +class ExampleTest extends TestCase +{ + /** + * A basic test example. + */ + public function test_basic_test(): void + { + $response = $this->get('/'); + + $response->dump(); + $response->dumpHeaders(); + $response->dumpSession(); } +} +``` -Alternatively, you may use the `dd`, `ddHeaders`, and `ddSession` methods to dump information about the response and then stop execution: +Alternatively, you may use the `dd`, `ddHeaders`, `ddBody`, `ddJson`, and `ddSession` methods to dump information about the response and then stop execution: - get('/'); - use Tests\TestCase; + $response->dd(); + $response->ddHeaders(); + $response->ddBody(); + $response->ddJson(); + $response->ddSession(); +}); +``` - class ExampleTest extends TestCase - { - /** - * A basic test example. - * - * @return void - */ - public function test_basic_test() - { - $response = $this->get('/'); +```php tab=PHPUnit +ddHeaders(); +namespace Tests\Feature; - $response->ddSession(); +use Tests\TestCase; - $response->dd(); - } +class ExampleTest extends TestCase +{ + /** + * A basic test example. + */ + public function test_basic_test(): void + { + $response = $this->get('/'); + + $response->dd(); + $response->ddHeaders(); + $response->ddBody(); + $response->ddJson(); + $response->ddSession(); } +} +``` ### Exception Handling -Sometimes you may want to test that your application is throwing a specific exception. To ensure that the exception does not get caught by Laravel's exception handler and returned as an HTTP response, you may invoke the `withoutExceptionHandling` method before making your request: +Sometimes you may need to test that your application is throwing a specific exception. To accomplish this, you may "fake" the exception handler via the `Exceptions` facade. Once the exception handler has been faked, you may utilize the `assertReported` and `assertNotReported` methods to make assertions against exceptions that were thrown during the request: + +```php tab=Pest +withoutExceptionHandling()->get('/'); +use App\Exceptions\InvalidOrderException; +use Illuminate\Support\Facades\Exceptions; + +test('exception is thrown', function () { + Exceptions::fake(); + + $response = $this->get('/order/1'); + + // Assert an exception was thrown... + Exceptions::assertReported(InvalidOrderException::class); + + // Assert against the exception... + Exceptions::assertReported(function (InvalidOrderException $e) { + return $e->getMessage() === 'The order was invalid.'; + }); +}); +``` + +```php tab=PHPUnit +get('/'); + + // Assert an exception was thrown... + Exceptions::assertReported(InvalidOrderException::class); + + // Assert against the exception... + Exceptions::assertReported(function (InvalidOrderException $e) { + return $e->getMessage() === 'The order was invalid.'; + }); + } +} +``` + +The `assertNotReported` and `assertNothingReported` methods may be used to assert that a given exception was not thrown during the request or that no exceptions were thrown: + +```php +Exceptions::assertNotReported(InvalidOrderException::class); + +Exceptions::assertNothingReported(); +``` + +You may totally disable exception handling for a given request by invoking the `withoutExceptionHandling` method before making your request: + +```php +$response = $this->withoutExceptionHandling()->get('/'); +``` In addition, if you would like to ensure that your application is not utilizing features that have been deprecated by the PHP language or the libraries your application is using, you may invoke the `withoutDeprecationHandling` method before making your request. When deprecation handling is disabled, deprecation warnings will be converted to exceptions, thus causing your test to fail: - $response = $this->withoutDeprecationHandling()->get('/'); +```php +$response = $this->withoutDeprecationHandling()->get('/'); +``` + +The `assertThrows` method may be used to assert that code within a given closure throws an exception of the specified type: + +```php +$this->assertThrows( + fn () => (new ProcessOrder)->execute(), + OrderInvalid::class +); +``` + +If you would like to inspect and make assertions against the exception that is thrown, you may provide a closure as the second argument to the `assertThrows` method: + +```php +$this->assertThrows( + fn () => (new ProcessOrder)->execute(), + fn (OrderInvalid $e) => $e->orderId() === 123; +); +``` + +The `assertDoesntThrow` method may be used to assert that the code within a given closure does not throw any exceptions: + +```php +$this->assertDoesntThrow(fn () => (new ProcessOrder)->execute()); +``` ## Testing JSON APIs Laravel also provides several helpers for testing JSON APIs and their responses. For example, the `json`, `getJson`, `postJson`, `putJson`, `patchJson`, `deleteJson`, and `optionsJson` methods may be used to issue JSON requests with various HTTP verbs. You may also easily pass data and headers to these methods. To get started, let's write a test to make a `POST` request to `/api/user` and assert that the expected JSON data was returned: - postJson('/api/user', ['name' => 'Sally']); + + $response + ->assertStatus(201) + ->assertJson([ + 'created' => true, + ]); +}); +``` - namespace Tests\Feature; +```php tab=PHPUnit +postJson('/api/user', ['name' => 'Sally']); + $response = $this->postJson('/api/user', ['name' => 'Sally']); - $response - ->assertStatus(201) - ->assertJson([ - 'created' => true, - ]); - } + $response + ->assertStatus(201) + ->assertJson([ + 'created' => true, + ]); } +} +``` In addition, JSON response data may be accessed as array variables on the response, making it convenient for you to inspect the individual values returned within a JSON response: - $this->assertTrue($response['created']); +```php tab=Pest +expect($response['created'])->toBeTrue(); +``` + +```php tab=PHPUnit +$this->assertTrue($response['created']); +``` -> {tip} The `assertJson` method converts the response to an array and utilizes `PHPUnit::assertArraySubset` to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present. +> [!NOTE] +> The `assertJson` method converts the response to an array to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present. #### Asserting Exact JSON Matches As previously mentioned, the `assertJson` method may be used to assert that a fragment of JSON exists within the JSON response. If you would like to verify that a given array **exactly matches** the JSON returned by your application, you should use the `assertExactJson` method: - postJson('/user', ['name' => 'Sally']); - use Tests\TestCase; + $response + ->assertStatus(201) + ->assertExactJson([ + 'created' => true, + ]); +}); +``` + +```php tab=PHPUnit +postJson('/user', ['name' => 'Sally']); + $response = $this->postJson('/user', ['name' => 'Sally']); - $response - ->assertStatus(201) - ->assertExactJson([ - 'created' => true, - ]); - } + $response + ->assertStatus(201) + ->assertExactJson([ + 'created' => true, + ]); } +} +``` -#### Asserting On JSON Paths +#### Asserting on JSON Paths If you would like to verify that the JSON response contains the given data at a specified path, you should use the `assertJsonPath` method: - postJson('/user', ['name' => 'Sally']); - namespace Tests\Feature; + $response + ->assertStatus(201) + ->assertJsonPath('team.owner.name', 'Darian'); +}); +``` + +```php tab=PHPUnit +postJson('/user', ['name' => 'Sally']); + $response = $this->postJson('/user', ['name' => 'Sally']); - $response - ->assertStatus(201) - ->assertJsonPath('team.owner.name', 'Darian'); - } + $response + ->assertStatus(201) + ->assertJsonPath('team.owner.name', 'Darian'); } +} +``` + +The `assertJsonPath` method also accepts a closure, which may be used to dynamically determine if the assertion should pass: + +```php +$response->assertJsonPath('team.owner.name', fn (string $name) => strlen($name) >= 3); +``` ### Fluent JSON Testing Laravel also offers a beautiful way to fluently test your application's JSON responses. To get started, pass a closure to the `assertJson` method. This closure will be invoked with an instance of `Illuminate\Testing\Fluent\AssertableJson` which can be used to make assertions against the JSON that was returned by your application. The `where` method may be used to make assertions against a particular attribute of the JSON, while the `missing` method may be used to assert that a particular attribute is missing from the JSON: - use Illuminate\Testing\Fluent\AssertableJson; +```php tab=Pest +use Illuminate\Testing\Fluent\AssertableJson; - /** - * A basic functional test example. - * - * @return void - */ - public function test_fluent_json() - { - $response = $this->getJson('/users/1'); +test('fluent json', function () { + $response = $this->getJson('/users/1'); - $response - ->assertJson(fn (AssertableJson $json) => - $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->missing('password') - ->etc() - ); - } + $response + ->assertJson(fn (AssertableJson $json) => + $json->where('id', 1) + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->whereNot('status', 'pending') + ->missing('password') + ->etc() + ); +}); +``` + +```php tab=PHPUnit +use Illuminate\Testing\Fluent\AssertableJson; + +/** + * A basic functional test example. + */ +public function test_fluent_json(): void +{ + $response = $this->getJson('/users/1'); + + $response + ->assertJson(fn (AssertableJson $json) => + $json->where('id', 1) + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->whereNot('status', 'pending') + ->missing('password') + ->etc() + ); +} +``` -#### Understanding The `etc` Method +#### Understanding the `etc` Method In the example above, you may have noticed we invoked the `etc` method at the end of our assertion chain. This method informs Laravel that there may be other attributes present on the JSON object. If the `etc` method is not used, the test will fail if other attributes that you did not make assertions against exist on the JSON object. The intention behind this behavior is to protect you from unintentionally exposing sensitive information in your JSON responses by forcing you to either explicitly make an assertion against the attribute or explicitly allow additional attributes via the `etc` method. +However, you should be aware that not including the `etc` method in your assertion chain does not ensure that additional attributes are not being added to arrays that are nested within your JSON object. The `etc` method only ensures that no additional attributes exist at the nesting level in which the `etc` method is invoked. + #### Asserting Attribute Presence / Absence To assert that an attribute is present or absent, you may use the `has` and `missing` methods: - $response->assertJson(fn (AssertableJson $json) => - $json->has('data') - ->missing('message') - ); +```php +$response->assertJson(fn (AssertableJson $json) => + $json->has('data') + ->missing('message') +); +``` In addition, the `hasAll` and `missingAll` methods allow asserting the presence or absence of multiple attributes simultaneously: - $response->assertJson(fn (AssertableJson $json) => - $json->hasAll('status', 'data') - ->missingAll('message', 'code') - ); +```php +$response->assertJson(fn (AssertableJson $json) => + $json->hasAll(['status', 'data']) + ->missingAll(['message', 'code']) +); +``` You may use the `hasAny` method to determine if at least one of a given list of attributes is present: - $response->assertJson(fn (AssertableJson $json) => - $json->has('status') - ->hasAny('data', 'message', 'code') - ); +```php +$response->assertJson(fn (AssertableJson $json) => + $json->has('status') + ->hasAny('data', 'message', 'code') +); +``` #### Asserting Against JSON Collections Often, your route will return a JSON response that contains multiple items, such as multiple users: - Route::get('/users', function () { - return User::all(); - }); +```php +Route::get('/users', function () { + return User::all(); +}); +``` In these situations, we may use the fluent JSON object's `has` method to make assertions against the users included in the response. For example, let's assert that the JSON response contains three users. Next, we'll make some assertions about the first user in the collection using the `first` method. The `first` method accepts a closure which receives another assertable JSON string that we can use to make assertions about the first object in the JSON collection: - $response - ->assertJson(fn (AssertableJson $json) => - $json->has(3) - ->first(fn ($json) => - $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->missing('password') - ->etc() - ) - ); +```php +$response + ->assertJson(fn (AssertableJson $json) => + $json->has(3) + ->first(fn (AssertableJson $json) => + $json->where('id', 1) + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->missing('password') + ->etc() + ) + ); +``` #### Scoping JSON Collection Assertions Sometimes, your application's routes will return JSON collections that are assigned named keys: - Route::get('/users', function () { - return [ - 'meta' => [...], - 'users' => User::all(), - ]; - }) +```php +Route::get('/users', function () { + return [ + 'meta' => [...], + 'users' => User::all(), + ]; +}) +``` When testing these routes, you may use the `has` method to assert against the number of items in the collection. In addition, you may use the `has` method to scope a chain of assertions: - $response - ->assertJson(fn (AssertableJson $json) => - $json->has('meta') - ->has('users', 3) - ->has('users.0', fn ($json) => - $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->missing('password') - ->etc() - ) - ); +```php +$response + ->assertJson(fn (AssertableJson $json) => + $json->has('meta') + ->has('users', 3) + ->has('users.0', fn (AssertableJson $json) => + $json->where('id', 1) + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->missing('password') + ->etc() + ) + ); +``` However, instead of making two separate calls to the `has` method to assert against the `users` collection, you may make a single call which provides a closure as its third parameter. When doing so, the closure will automatically be invoked and scoped to the first item in the collection: - $response - ->assertJson(fn (AssertableJson $json) => - $json->has('meta') - ->has('users', 3, fn ($json) => - $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->missing('password') - ->etc() - ) - ); +```php +$response + ->assertJson(fn (AssertableJson $json) => + $json->has('meta') + ->has('users', 3, fn (AssertableJson $json) => + $json->where('id', 1) + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->missing('password') + ->etc() + ) + ); +``` #### Asserting JSON Types You may only want to assert that the properties in the JSON response are of a certain type. The `Illuminate\Testing\Fluent\AssertableJson` class provides the `whereType` and `whereAllType` methods for doing just that: - $response->assertJson(fn (AssertableJson $json) => - $json->whereType('id', 'integer') - ->whereAllType([ - 'users.0.name' => 'string', - 'meta' => 'array' - ]) - ); +```php +$response->assertJson(fn (AssertableJson $json) => + $json->whereType('id', 'integer') + ->whereAllType([ + 'users.0.name' => 'string', + 'meta' => 'array' + ]) +); +``` You may specify multiple types using the `|` character, or passing an array of types as the second parameter to the `whereType` method. The assertion will be successful if the response value is any of the listed types: - $response->assertJson(fn (AssertableJson $json) => - $json->whereType('name', 'string|null') - ->whereType('id', ['string', 'integer']) - ); +```php +$response->assertJson(fn (AssertableJson $json) => + $json->whereType('name', 'string|null') + ->whereType('id', ['string', 'integer']) +); +``` The `whereType` and `whereAllType` methods recognize the following types: `string`, `integer`, `double`, `boolean`, `array`, and `null`. @@ -481,112 +784,159 @@ The `whereType` and `whereAllType` methods recognize the following types: `strin The `Illuminate\Http\UploadedFile` class provides a `fake` method which may be used to generate dummy files or images for testing. This, combined with the `Storage` facade's `fake` method, greatly simplifies the testing of file uploads. For example, you may combine these two features to easily test an avatar upload form: - image('avatar.jpg'); - class ExampleTest extends TestCase + $response = $this->post('/avatar', [ + 'avatar' => $file, + ]); + + Storage::disk('avatars')->assertExists($file->hashName()); +}); +``` + +```php tab=PHPUnit +image('avatar.jpg'); + $file = UploadedFile::fake()->image('avatar.jpg'); - $response = $this->post('/avatar', [ - 'avatar' => $file, - ]); + $response = $this->post('/avatar', [ + 'avatar' => $file, + ]); - Storage::disk('avatars')->assertExists($file->hashName()); - } + Storage::disk('avatars')->assertExists($file->hashName()); } +} +``` If you would like to assert that a given file does not exist, you may use the `assertMissing` method provided by the `Storage` facade: - Storage::fake('avatars'); +```php +Storage::fake('avatars'); - // ... +// ... - Storage::disk('avatars')->assertMissing('missing.jpg'); +Storage::disk('avatars')->assertMissing('missing.jpg'); +``` #### Fake File Customization When creating files using the `fake` method provided by the `UploadedFile` class, you may specify the width, height, and size of the image (in kilobytes) in order to better test your application's validation rules: - UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100); +```php +UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100); +``` In addition to creating images, you may create files of any other type using the `create` method: - UploadedFile::fake()->create('document.pdf', $sizeInKilobytes); +```php +UploadedFile::fake()->create('document.pdf', $sizeInKilobytes); +``` If needed, you may pass a `$mimeType` argument to the method to explicitly define the MIME type that should be returned by the file: - UploadedFile::fake()->create( - 'document.pdf', $sizeInKilobytes, 'application/pdf' - ); +```php +UploadedFile::fake()->create( + 'document.pdf', $sizeInKilobytes, 'application/pdf' +); +``` ## Testing Views Laravel also allows you to render a view without making a simulated HTTP request to the application. To accomplish this, you may call the `view` method within your test. The `view` method accepts the view name and an optional array of data. The method returns an instance of `Illuminate\Testing\TestView`, which offers several methods to conveniently make assertions about the view's contents: - view('welcome', ['name' => 'Taylor']); + + $view->assertSee('Taylor'); +}); +``` + +```php tab=PHPUnit +view('welcome', ['name' => 'Taylor']); + $view = $this->view('welcome', ['name' => 'Taylor']); - $view->assertSee('Taylor'); - } + $view->assertSee('Taylor'); } +} +``` The `TestView` class provides the following assertion methods: `assertSee`, `assertSeeInOrder`, `assertSeeText`, `assertSeeTextInOrder`, `assertDontSee`, and `assertDontSeeText`. If needed, you may get the raw, rendered view contents by casting the `TestView` instance to a string: - $contents = (string) $this->view('welcome'); +```php +$contents = (string) $this->view('welcome'); +``` #### Sharing Errors Some views may depend on errors shared in the [global error bag provided by Laravel](/docs/{{version}}/validation#quick-displaying-the-validation-errors). To hydrate the error bag with error messages, you may use the `withViewErrors` method: - $view = $this->withViewErrors([ - 'name' => ['Please provide a valid name.'] - ])->view('form'); +```php +$view = $this->withViewErrors([ + 'name' => ['Please provide a valid name.'] +])->view('form'); - $view->assertSee('Please provide a valid name.'); +$view->assertSee('Please provide a valid name.'); +``` -### Rendering Blade & Components +### Rendering Blade and Components If necessary, you may use the `blade` method to evaluate and render a raw [Blade](/docs/{{version}}/blade) string. Like the `view` method, the `blade` method returns an instance of `Illuminate\Testing\TestView`: - $view = $this->blade( - '', - ['name' => 'Taylor'] - ); +```php +$view = $this->blade( + '', + ['name' => 'Taylor'] +); - $view->assertSee('Taylor'); +$view->assertSee('Taylor'); +``` -You may use the `component` method to evaluate and render a [Blade component](/docs/{{version}}/blade#components). Like the `view` method, the `component` method returns an instance of `Illuminate\Testing\TestView`: +You may use the `component` method to evaluate and render a [Blade component](/docs/{{version}}/blade#components). The `component` method returns an instance of `Illuminate\Testing\TestComponent`: - $view = $this->component(Profile::class, ['name' => 'Taylor']); +```php +$view = $this->component(Profile::class, ['name' => 'Taylor']); - $view->assertSee('Taylor'); +$view->assertSee('Taylor'); +``` ## Available Assertions @@ -598,17 +948,23 @@ Laravel's `Illuminate\Testing\TestResponse` class provides a variety of custom a
+[assertAccepted](#assert-accepted) +[assertBadRequest](#assert-bad-request) +[assertClientError](#assert-client-error) +[assertConflict](#assert-conflict) [assertCookie](#assert-cookie) [assertCookieExpired](#assert-cookie-expired) [assertCookieNotExpired](#assert-cookie-not-expired) @@ -618,31 +974,51 @@ Laravel's `Illuminate\Testing\TestResponse` class provides a variety of custom a [assertDontSeeText](#assert-dont-see-text) [assertDownload](#assert-download) [assertExactJson](#assert-exact-json) +[assertExactJsonStructure](#assert-exact-json-structure) [assertForbidden](#assert-forbidden) +[assertFound](#assert-found) +[assertGone](#assert-gone) [assertHeader](#assert-header) [assertHeaderMissing](#assert-header-missing) +[assertInternalServerError](#assert-internal-server-error) [assertJson](#assert-json) [assertJsonCount](#assert-json-count) [assertJsonFragment](#assert-json-fragment) +[assertJsonIsArray](#assert-json-is-array) +[assertJsonIsObject](#assert-json-is-object) [assertJsonMissing](#assert-json-missing) [assertJsonMissingExact](#assert-json-missing-exact) [assertJsonMissingValidationErrors](#assert-json-missing-validation-errors) [assertJsonPath](#assert-json-path) +[assertJsonMissingPath](#assert-json-missing-path) [assertJsonStructure](#assert-json-structure) [assertJsonValidationErrors](#assert-json-validation-errors) [assertJsonValidationErrorFor](#assert-json-validation-error-for) [assertLocation](#assert-location) +[assertMethodNotAllowed](#assert-method-not-allowed) +[assertMovedPermanently](#assert-moved-permanently) +[assertContent](#assert-content) [assertNoContent](#assert-no-content) +[assertStreamed](#assert-streamed) +[assertStreamedContent](#assert-streamed-content) [assertNotFound](#assert-not-found) [assertOk](#assert-ok) +[assertPaymentRequired](#assert-payment-required) [assertPlainCookie](#assert-plain-cookie) [assertRedirect](#assert-redirect) +[assertRedirectBack](#assert-redirect-back) +[assertRedirectBackWithErrors](#assert-redirect-back-with-errors) +[assertRedirectBackWithoutErrors](#assert-redirect-back-without-errors) [assertRedirectContains](#assert-redirect-contains) +[assertRedirectToRoute](#assert-redirect-to-route) [assertRedirectToSignedRoute](#assert-redirect-to-signed-route) +[assertRequestTimeout](#assert-request-timeout) [assertSee](#assert-see) [assertSeeInOrder](#assert-see-in-order) [assertSeeText](#assert-see-text) [assertSeeTextInOrder](#assert-see-text-in-order) +[assertServerError](#assert-server-error) +[assertServiceUnavailable](#assert-service-unavailable) [assertSessionHas](#assert-session-has) [assertSessionHasInput](#assert-session-has-input) [assertSessionHasAll](#assert-session-has-all) @@ -651,11 +1027,12 @@ Laravel's `Illuminate\Testing\TestResponse` class provides a variety of custom a [assertSessionHasNoErrors](#assert-session-has-no-errors) [assertSessionDoesntHaveErrors](#assert-session-doesnt-have-errors) [assertSessionMissing](#assert-session-missing) -[assertSimilarJson](#assert-similar-json) [assertStatus](#assert-status) [assertSuccessful](#assert-successful) +[assertTooManyRequests](#assert-too-many-requests) [assertUnauthorized](#assert-unauthorized) [assertUnprocessable](#assert-unprocessable) +[assertUnsupportedMediaType](#assert-unsupported-media-type) [assertValid](#assert-valid) [assertInvalid](#assert-invalid) [assertViewHas](#assert-view-has) @@ -665,160 +1042,293 @@ Laravel's `Illuminate\Testing\TestResponse` class provides a variety of custom a
+ +#### assertAccepted + +Assert that the response has an accepted (202) HTTP status code: + +```php +$response->assertAccepted(); +``` + + +#### assertBadRequest + +Assert that the response has a bad request (400) HTTP status code: + +```php +$response->assertBadRequest(); +``` + + +#### assertClientError + +Assert that the response has a client error (>= 400, < 500) HTTP status code: + +```php +$response->assertClientError(); +``` + + +#### assertConflict + +Assert that the response has a conflict (409) HTTP status code: + +```php +$response->assertConflict(); +``` + #### assertCookie Assert that the response contains the given cookie: - $response->assertCookie($cookieName, $value = null); +```php +$response->assertCookie($cookieName, $value = null); +``` #### assertCookieExpired Assert that the response contains the given cookie and it is expired: - $response->assertCookieExpired($cookieName); +```php +$response->assertCookieExpired($cookieName); +``` #### assertCookieNotExpired Assert that the response contains the given cookie and it is not expired: - $response->assertCookieNotExpired($cookieName); +```php +$response->assertCookieNotExpired($cookieName); +``` #### assertCookieMissing -Assert that the response does not contains the given cookie: +Assert that the response does not contain the given cookie: - $response->assertCookieMissing($cookieName); +```php +$response->assertCookieMissing($cookieName); +``` #### assertCreated Assert that the response has a 201 HTTP status code: - $response->assertCreated(); +```php +$response->assertCreated(); +``` #### assertDontSee Assert that the given string is not contained within the response returned by the application. This assertion will automatically escape the given string unless you pass a second argument of `false`: - $response->assertDontSee($value, $escaped = true); +```php +$response->assertDontSee($value, $escape = true); +``` #### assertDontSeeText Assert that the given string is not contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of `false`. This method will pass the response content to the `strip_tags` PHP function before making the assertion: - $response->assertDontSeeText($value, $escaped = true); +```php +$response->assertDontSeeText($value, $escape = true); +``` #### assertDownload Assert that the response is a "download". Typically, this means the invoked route that returned the response returned a `Response::download` response, `BinaryFileResponse`, or `Storage::download` response: - $response->assertDownload(); +```php +$response->assertDownload(); +``` If you wish, you may assert that the downloadable file was assigned a given file name: - $response->assertDownload('image.jpg'); +```php +$response->assertDownload('image.jpg'); +``` #### assertExactJson Assert that the response contains an exact match of the given JSON data: - $response->assertExactJson(array $data); +```php +$response->assertExactJson(array $data); +``` + + +#### assertExactJsonStructure + +Assert that the response contains an exact match of the given JSON structure: + +```php +$response->assertExactJsonStructure(array $data); +``` + +This method is a more strict variant of [assertJsonStructure](#assert-json-structure). In contrast with `assertJsonStructure`, this method will fail if the response contains any keys that aren't explicitly included in the expected JSON structure. #### assertForbidden Assert that the response has a forbidden (403) HTTP status code: - $response->assertForbidden(); +```php +$response->assertForbidden(); +``` + + +#### assertFound + +Assert that the response has a found (302) HTTP status code: + +```php +$response->assertFound(); +``` + + +#### assertGone + +Assert that the response has a gone (410) HTTP status code: + +```php +$response->assertGone(); +``` #### assertHeader Assert that the given header and value is present on the response: - $response->assertHeader($headerName, $value = null); +```php +$response->assertHeader($headerName, $value = null); +``` #### assertHeaderMissing Assert that the given header is not present on the response: - $response->assertHeaderMissing($headerName); +```php +$response->assertHeaderMissing($headerName); +``` + + +#### assertInternalServerError + +Assert that the response has an "Internal Server Error" (500) HTTP status code: + +```php +$response->assertInternalServerError(); +``` #### assertJson Assert that the response contains the given JSON data: - $response->assertJson(array $data, $strict = false); +```php +$response->assertJson(array $data, $strict = false); +``` -The `assertJson` method converts the response to an array and utilizes `PHPUnit::assertArraySubset` to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present. +The `assertJson` method converts the response to an array to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present. #### assertJsonCount Assert that the response JSON has an array with the expected number of items at the given key: - $response->assertJsonCount($count, $key = null); +```php +$response->assertJsonCount($count, $key = null); +``` #### assertJsonFragment Assert that the response contains the given JSON data anywhere in the response: - Route::get('/users', function () { - return [ - 'users' => [ - [ - 'name' => 'Taylor Otwell', - ], +```php +Route::get('/users', function () { + return [ + 'users' => [ + [ + 'name' => 'Taylor Otwell', ], - ]; - }); + ], + ]; +}); + +$response->assertJsonFragment(['name' => 'Taylor Otwell']); +``` + + +#### assertJsonIsArray + +Assert that the response JSON is an array: + +```php +$response->assertJsonIsArray(); +``` + + +#### assertJsonIsObject - $response->assertJsonFragment(['name' => 'Taylor Otwell']); +Assert that the response JSON is an object: + +```php +$response->assertJsonIsObject(); +``` #### assertJsonMissing Assert that the response does not contain the given JSON data: - $response->assertJsonMissing(array $data); +```php +$response->assertJsonMissing(array $data); +``` #### assertJsonMissingExact Assert that the response does not contain the exact JSON data: - $response->assertJsonMissingExact(array $data); +```php +$response->assertJsonMissingExact(array $data); +``` #### assertJsonMissingValidationErrors Assert that the response has no JSON validation errors for the given keys: - $response->assertJsonMissingValidationErrors($keys); +```php +$response->assertJsonMissingValidationErrors($keys); +``` -> {tip} The more generic [assertValid](#assert-valid) method may be used to assert that a response does not have validation errors that were returned as JSON **and** that no errors were flashed to session storage. +> [!NOTE] +> The more generic [assertValid](#assert-valid) method may be used to assert that a response does not have validation errors that were returned as JSON **and** that no errors were flashed to session storage. #### assertJsonPath Assert that the response contains the given data at the specified path: - $response->assertJsonPath($path, $expectedValue); +```php +$response->assertJsonPath($path, $expectedValue); +``` -For example, if the JSON response returned by your application contains the following data: +For example, if the following JSON response is returned by your application: -```js +```json { "user": { "name": "Steve Schoger" @@ -828,18 +1338,47 @@ For example, if the JSON response returned by your application contains the foll You may assert that the `name` property of the `user` object matches a given value like so: - $response->assertJsonPath('user.name', 'Steve Schoger'); +```php +$response->assertJsonPath('user.name', 'Steve Schoger'); +``` + + +#### assertJsonMissingPath + +Assert that the response does not contain the given path: + +```php +$response->assertJsonMissingPath($path); +``` + +For example, if the following JSON response is returned by your application: + +```json +{ + "user": { + "name": "Steve Schoger" + } +} +``` + +You may assert that it does not contain the `email` property of the `user` object: + +```php +$response->assertJsonMissingPath('user.email'); +``` #### assertJsonStructure Assert that the response has a given JSON structure: - $response->assertJsonStructure(array $structure); +```php +$response->assertJsonStructure(array $structure); +``` For example, if the JSON response returned by your application contains the following data: -```js +```json { "user": { "name": "Steve Schoger" @@ -849,15 +1388,17 @@ For example, if the JSON response returned by your application contains the foll You may assert that the JSON structure matches your expectations like so: - $response->assertJsonStructure([ - 'user' => [ - 'name', - ] - ]); +```php +$response->assertJsonStructure([ + 'user' => [ + 'name', + ] +]); +``` Sometimes, JSON responses returned by your application may contain arrays of objects: -```js +```json { "user": [ { @@ -876,307 +1417,547 @@ Sometimes, JSON responses returned by your application may contain arrays of obj In this situation, you may use the `*` character to assert against the structure of all of the objects in the array: - $response->assertJsonStructure([ - 'user' => [ - '*' => [ - 'name', - 'age', - 'location' - ] +```php +$response->assertJsonStructure([ + 'user' => [ + '*' => [ + 'name', + 'age', + 'location' ] - ]); + ] +]); +``` #### assertJsonValidationErrors Assert that the response has the given JSON validation errors for the given keys. This method should be used when asserting against responses where the validation errors are returned as a JSON structure instead of being flashed to the session: - $response->assertJsonValidationErrors(array $data, $responseKey = 'errors'); +```php +$response->assertJsonValidationErrors(array $data, $responseKey = 'errors'); +``` -> {tip} The more generic [assertInvalid](#assert-invalid) method may be used to assert that a response has validation errors returned as JSON **or** that errors were flashed to session storage. +> [!NOTE] +> The more generic [assertInvalid](#assert-invalid) method may be used to assert that a response has validation errors returned as JSON **or** that errors were flashed to session storage. #### assertJsonValidationErrorFor Assert the response has any JSON validation errors for the given key: - $response->assertJsonValidationErrorFor(string $key, $responseKey = 'errors'); +```php +$response->assertJsonValidationErrorFor(string $key, $responseKey = 'errors'); +``` + + +#### assertMethodNotAllowed + +Assert that the response has a method not allowed (405) HTTP status code: + +```php +$response->assertMethodNotAllowed(); +``` + + +#### assertMovedPermanently + +Assert that the response has a moved permanently (301) HTTP status code: + +```php +$response->assertMovedPermanently(); +``` #### assertLocation Assert that the response has the given URI value in the `Location` header: - $response->assertLocation($uri); +```php +$response->assertLocation($uri); +``` + + +#### assertContent + +Assert that the given string matches the response content: + +```php +$response->assertContent($value); +``` #### assertNoContent Assert that the response has the given HTTP status code and no content: - $response->assertNoContent($status = 204); +```php +$response->assertNoContent($status = 204); +``` + + +#### assertStreamed + +Assert that the response was a streamed response: + + $response->assertStreamed(); + + +#### assertStreamedContent + +Assert that the given string matches the streamed response content: + +```php +$response->assertStreamedContent($value); +``` #### assertNotFound Assert that the response has a not found (404) HTTP status code: - $response->assertNotFound(); +```php +$response->assertNotFound(); +``` #### assertOk Assert that the response has a 200 HTTP status code: - $response->assertOk(); +```php +$response->assertOk(); +``` + + +#### assertPaymentRequired + +Assert that the response has a payment required (402) HTTP status code: + +```php +$response->assertPaymentRequired(); +``` #### assertPlainCookie Assert that the response contains the given unencrypted cookie: - $response->assertPlainCookie($cookieName, $value = null); +```php +$response->assertPlainCookie($cookieName, $value = null); +``` #### assertRedirect Assert that the response is a redirect to the given URI: - $response->assertRedirect($uri); +```php +$response->assertRedirect($uri = null); +``` + + +#### assertRedirectBack + +Assert whether the response is redirecting back to the previous page: + +```php +$response->assertRedirectBack(); +``` + + +#### assertRedirectBackWithErrors + +Assert whether the response is redirecting back to the previous page and the [session has the given errors](#assert-session-has-errors): + +```php +$response->assertRedirectBackWithErrors( + array $keys = [], $format = null, $errorBag = 'default' +); +``` + + +#### assertRedirectBackWithoutErrors + +Assert whether the response is redirecting back to the previous page and the session does not contain any error messages: + +```php +$response->assertRedirectBackWithoutErrors(); +``` #### assertRedirectContains Assert whether the response is redirecting to a URI that contains the given string: - $response->assertRedirectContains($string); +```php +$response->assertRedirectContains($string); +``` + + +#### assertRedirectToRoute + +Assert that the response is a redirect to the given [named route](/docs/{{version}}/routing#named-routes): + +```php +$response->assertRedirectToRoute($name, $parameters = []); +``` #### assertRedirectToSignedRoute -Assert that the response is a redirect to the given signed route: +Assert that the response is a redirect to the given [signed route](/docs/{{version}}/urls#signed-urls): - $response->assertRedirectToSignedRoute($name = null, $parameters = []); +```php +$response->assertRedirectToSignedRoute($name = null, $parameters = []); +``` + + +#### assertRequestTimeout + +Assert that the response has a request timeout (408) HTTP status code: + +```php +$response->assertRequestTimeout(); +``` #### assertSee Assert that the given string is contained within the response. This assertion will automatically escape the given string unless you pass a second argument of `false`: - $response->assertSee($value, $escaped = true); +```php +$response->assertSee($value, $escape = true); +``` #### assertSeeInOrder Assert that the given strings are contained in order within the response. This assertion will automatically escape the given strings unless you pass a second argument of `false`: - $response->assertSeeInOrder(array $values, $escaped = true); +```php +$response->assertSeeInOrder(array $values, $escape = true); +``` #### assertSeeText Assert that the given string is contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of `false`. The response content will be passed to the `strip_tags` PHP function before the assertion is made: - $response->assertSeeText($value, $escaped = true); +```php +$response->assertSeeText($value, $escape = true); +``` #### assertSeeTextInOrder Assert that the given strings are contained in order within the response text. This assertion will automatically escape the given strings unless you pass a second argument of `false`. The response content will be passed to the `strip_tags` PHP function before the assertion is made: - $response->assertSeeTextInOrder(array $values, $escaped = true); +```php +$response->assertSeeTextInOrder(array $values, $escape = true); +``` + + +#### assertServerError + +Assert that the response has a server error (>= 500 , < 600) HTTP status code: + +```php +$response->assertServerError(); +``` + + +#### assertServiceUnavailable + +Assert that the response has a "Service Unavailable" (503) HTTP status code: + +```php +$response->assertServiceUnavailable(); +``` #### assertSessionHas Assert that the session contains the given piece of data: - $response->assertSessionHas($key, $value = null); +```php +$response->assertSessionHas($key, $value = null); +``` If needed, a closure can be provided as the second argument to the `assertSessionHas` method. The assertion will pass if the closure returns `true`: - $response->assertSessionHas($key, function ($value) { - return $value->name === 'Taylor Otwell'; - }); +```php +$response->assertSessionHas($key, function (User $value) { + return $value->name === 'Taylor Otwell'; +}); +``` #### assertSessionHasInput Assert that the session has a given value in the [flashed input array](/docs/{{version}}/responses#redirecting-with-flashed-session-data): - $response->assertSessionHasInput($key, $value = null); +```php +$response->assertSessionHasInput($key, $value = null); +``` If needed, a closure can be provided as the second argument to the `assertSessionHasInput` method. The assertion will pass if the closure returns `true`: - $response->assertSessionHasInput($key, function ($value) { - return Crypt::decryptString($value) === 'secret'; - }); +```php +use Illuminate\Support\Facades\Crypt; + +$response->assertSessionHasInput($key, function (string $value) { + return Crypt::decryptString($value) === 'secret'; +}); +``` #### assertSessionHasAll Assert that the session contains a given array of key / value pairs: - $response->assertSessionHasAll(array $data); +```php +$response->assertSessionHasAll(array $data); +``` For example, if your application's session contains `name` and `status` keys, you may assert that both exist and have the specified values like so: - $response->assertSessionHasAll([ - 'name' => 'Taylor Otwell', - 'status' => 'active', - ]); +```php +$response->assertSessionHasAll([ + 'name' => 'Taylor Otwell', + 'status' => 'active', +]); +``` #### assertSessionHasErrors Assert that the session contains an error for the given `$keys`. If `$keys` is an associative array, assert that the session contains a specific error message (value) for each field (key). This method should be used when testing routes that flash validation errors to the session instead of returning them as a JSON structure: - $response->assertSessionHasErrors( - array $keys, $format = null, $errorBag = 'default' - ); +```php +$response->assertSessionHasErrors( + array $keys = [], $format = null, $errorBag = 'default' +); +``` For example, to assert that the `name` and `email` fields have validation error messages that were flashed to the session, you may invoke the `assertSessionHasErrors` method like so: - $response->assertSessionHasErrors(['name', 'email']); +```php +$response->assertSessionHasErrors(['name', 'email']); +``` Or, you may assert that a given field has a particular validation error message: - $response->assertSessionHasErrors([ - 'name' => 'The given name was invalid.' - ]); +```php +$response->assertSessionHasErrors([ + 'name' => 'The given name was invalid.' +]); +``` + +> [!NOTE] +> The more generic [assertInvalid](#assert-invalid) method may be used to assert that a response has validation errors returned as JSON **or** that errors were flashed to session storage. #### assertSessionHasErrorsIn Assert that the session contains an error for the given `$keys` within a specific [error bag](/docs/{{version}}/validation#named-error-bags). If `$keys` is an associative array, assert that the session contains a specific error message (value) for each field (key), within the error bag: - $response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null); +```php +$response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null); +``` #### assertSessionHasNoErrors Assert that the session has no validation errors: - $response->assertSessionHasNoErrors(); +```php +$response->assertSessionHasNoErrors(); +``` #### assertSessionDoesntHaveErrors Assert that the session has no validation errors for the given keys: - $response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default'); +```php +$response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default'); +``` + +> [!NOTE] +> The more generic [assertValid](#assert-valid) method may be used to assert that a response does not have validation errors that were returned as JSON **and** that no errors were flashed to session storage. #### assertSessionMissing Assert that the session does not contain the given key: - $response->assertSessionMissing($key); +```php +$response->assertSessionMissing($key); +``` #### assertStatus Assert that the response has a given HTTP status code: - $response->assertStatus($code); +```php +$response->assertStatus($code); +``` #### assertSuccessful Assert that the response has a successful (>= 200 and < 300) HTTP status code: - $response->assertSuccessful(); +```php +$response->assertSuccessful(); +``` + + +#### assertTooManyRequests + +Assert that the response has a too many requests (429) HTTP status code: + +```php +$response->assertTooManyRequests(); +``` #### assertUnauthorized Assert that the response has an unauthorized (401) HTTP status code: - $response->assertUnauthorized(); +```php +$response->assertUnauthorized(); +``` #### assertUnprocessable Assert that the response has an unprocessable entity (422) HTTP status code: - $response->assertUnprocessable(); +```php +$response->assertUnprocessable(); +``` + + +#### assertUnsupportedMediaType + +Assert that the response has an unsupported media type (415) HTTP status code: + +```php +$response->assertUnsupportedMediaType(); +``` #### assertValid Assert that the response has no validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned as a JSON structure or where the validation errors have been flashed to the session: - // Assert that no validation errors are present... - $response->assertValid(); +```php +// Assert that no validation errors are present... +$response->assertValid(); - // Assert that the given keys do not have validation errors... - $response->assertValid(['name', 'email']); +// Assert that the given keys do not have validation errors... +$response->assertValid(['name', 'email']); +``` #### assertInvalid Assert that the response has validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned as a JSON structure or where the validation errors have been flashed to the session: - $response->assertInvalid(['name', 'email']); +```php +$response->assertInvalid(['name', 'email']); +``` You may also assert that a given key has a particular validation error message. When doing so, you may provide the entire message or only a small portion of the message: - $response->assertInvalid([ - 'name' => 'The name field is required.', - 'email' => 'valid email address', - ]); +```php +$response->assertInvalid([ + 'name' => 'The name field is required.', + 'email' => 'valid email address', +]); +``` + +If you would like to assert that the given fields are the only fields with validation errors, you may use the `assertOnlyInvalid` method: + +```php +$response->assertOnlyInvalid(['name', 'email']); +``` #### assertViewHas -Assert that the response view contains given a piece of data: +Assert that the response view contains a given piece of data: - $response->assertViewHas($key, $value = null); +```php +$response->assertViewHas($key, $value = null); +``` Passing a closure as the second argument to the `assertViewHas` method will allow you to inspect and make assertions against a particular piece of view data: - $response->assertViewHas('user', function (User $user) { - return $user->name === 'Taylor'; - }); +```php +$response->assertViewHas('user', function (User $user) { + return $user->name === 'Taylor'; +}); +``` In addition, view data may be accessed as array variables on the response, allowing you to conveniently inspect it: - $this->assertEquals('Taylor', $response['name']); +```php tab=Pest +expect($response['name'])->toBe('Taylor'); +``` + +```php tab=PHPUnit +$this->assertEquals('Taylor', $response['name']); +``` #### assertViewHasAll Assert that the response view has a given list of data: - $response->assertViewHasAll(array $data); +```php +$response->assertViewHasAll(array $data); +``` This method may be used to assert that the view simply contains data matching the given keys: - $response->assertViewHasAll([ - 'name', - 'email', - ]); +```php +$response->assertViewHasAll([ + 'name', + 'email', +]); +``` Or, you may assert that the view data is present and has specific values: - $response->assertViewHasAll([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@example.com,', - ]); +```php +$response->assertViewHasAll([ + 'name' => 'Taylor Otwell', + 'email' => 'taylor@example.com,', +]); +``` #### assertViewIs Assert that the given view was returned by the route: - $response->assertViewIs($value); +```php +$response->assertViewIs($value); +``` #### assertViewMissing Assert that the given data key was not made available to the view returned in the application's response: - $response->assertViewMissing($key); +```php +$response->assertViewMissing($key); +``` ### Authentication Assertions @@ -1188,18 +1969,60 @@ Laravel also provides a variety of authentication related assertions that you ma Assert that a user is authenticated: - $this->assertAuthenticated($guard = null); +```php +$this->assertAuthenticated($guard = null); +``` #### assertGuest Assert that a user is not authenticated: - $this->assertGuest($guard = null); +```php +$this->assertGuest($guard = null); +``` #### assertAuthenticatedAs Assert that a specific user is authenticated: - $this->assertAuthenticatedAs($user, $guard = null); +```php +$this->assertAuthenticatedAs($user, $guard = null); +``` + + +## Validation Assertions + +Laravel provides two primary validation related assertions that you may use to ensure the data provided in your request was either valid or invalid. + + +#### assertValid + +Assert that the response has no validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned as a JSON structure or where the validation errors have been flashed to the session: + +```php +// Assert that no validation errors are present... +$response->assertValid(); + +// Assert that the given keys do not have validation errors... +$response->assertValid(['name', 'email']); +``` + + +#### assertInvalid + +Assert that the response has validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned as a JSON structure or where the validation errors have been flashed to the session: + +```php +$response->assertInvalid(['name', 'email']); +``` + +You may also assert that a given key has a particular validation error message. When doing so, you may provide the entire message or only a small portion of the message: + +```php +$response->assertInvalid([ + 'name' => 'The name field is required.', + 'email' => 'valid email address', +]); +``` diff --git a/installation.md b/installation.md index d6b81486d42..603257864c1 100644 --- a/installation.md +++ b/installation.md @@ -2,18 +2,22 @@ - [Meet Laravel](#meet-laravel) - [Why Laravel?](#why-laravel) -- [Your First Laravel Project](#your-first-laravel-project) - - [Getting Started On macOS](#getting-started-on-macos) - - [Getting Started On Windows](#getting-started-on-windows) - - [Getting Started On Linux](#getting-started-on-linux) - - [Choosing Your Sail Services](#choosing-your-sail-services) - - [Installation Via Composer](#installation-via-composer) +- [Creating a Laravel Application](#creating-a-laravel-project) + - [Installing PHP and the Laravel Installer](#installing-php) + - [Creating an Application](#creating-an-application) - [Initial Configuration](#initial-configuration) - [Environment Based Configuration](#environment-based-configuration) + - [Databases and Migrations](#databases-and-migrations) - [Directory Configuration](#directory-configuration) +- [Installation Using Herd](#installation-using-herd) + - [Herd on macOS](#herd-on-macos) + - [Herd on Windows](#herd-on-windows) +- [IDE Support](#ide-support) +- [Laravel and AI](#laravel-and-ai) + - [Installing Laravel Boost](#installing-laravel-boost) - [Next Steps](#next-steps) - - [Laravel The Full Stack Framework](#laravel-the-fullstack-framework) - - [Laravel The API Backend](#laravel-the-api-backend) + - [Laravel the Full Stack Framework](#laravel-the-fullstack-framework) + - [Laravel the API Backend](#laravel-the-api-backend) ## Meet Laravel @@ -22,7 +26,7 @@ Laravel is a web application framework with expressive, elegant syntax. A web fr Laravel strives to provide an amazing developer experience while providing powerful features such as thorough dependency injection, an expressive database abstraction layer, queues and scheduled jobs, unit and integration testing, and more. -Whether you are new to PHP or web frameworks or have years of experience, Laravel is a framework that can grow with you. We'll help you take your first steps as a web developer or give you a boost as you take your expertise to the next level. We can't wait to see what you build. +Whether you are new to PHP web frameworks or have years of experience, Laravel is a framework that can grow with you. We'll help you take your first steps as a web developer or give you a boost as you take your expertise to the next level. We can't wait to see what you build. ### Why Laravel? @@ -39,224 +43,218 @@ If you're a senior developer, Laravel gives you robust tools for [dependency inj Laravel is incredibly scalable. Thanks to the scaling-friendly nature of PHP and Laravel's built-in support for fast, distributed cache systems like Redis, horizontal scaling with Laravel is a breeze. In fact, Laravel applications have been easily scaled to handle hundreds of millions of requests per month. -Need extreme scaling? Platforms like [Laravel Vapor](https://vapor.laravel.com) allow you to run your Laravel application at nearly limitless scale on AWS's latest serverless technology. +Need extreme scaling? Platforms like [Laravel Cloud](https://cloud.laravel.com) allow you to run your Laravel application at nearly limitless scale. #### A Community Framework Laravel combines the best packages in the PHP ecosystem to offer the most robust and developer friendly framework available. In addition, thousands of talented developers from around the world have [contributed to the framework](https://github.com/laravel/framework). Who knows, maybe you'll even become a Laravel contributor. - -## Your First Laravel Project + +## Creating a Laravel Application -We want it to be as easy as possible to get started with Laravel. There are a variety of options for developing and running a Laravel project on your own computer. While you may wish to explore these options at a later time, Laravel provides [Sail](/docs/{{version}}/sail), a built-in solution for running your Laravel project using [Docker](https://www.docker.com). + +### Installing PHP and the Laravel Installer -Docker is a tool for running applications and services in small, light-weight "containers" which do not interfere with your local computer's installed software or configuration. This means you don't have to worry about configuring or setting up complicated development tools such as web servers and databases on your personal computer. To get started, you only need to install [Docker Desktop](https://www.docker.com/products/docker-desktop). +Before creating your first Laravel application, make sure that your local machine has [PHP](https://php.net), [Composer](https://getcomposer.org), and [the Laravel installer](https://github.com/laravel/installer) installed. In addition, you should install either [Node and NPM](https://nodejs.org) or [Bun](https://bun.sh/) so that you can compile your application's frontend assets. -Laravel Sail is a light-weight command-line interface for interacting with Laravel's default Docker configuration. Sail provides a great starting point for building a Laravel application using PHP, MySQL, and Redis without requiring prior Docker experience. +If you don't have PHP and Composer installed on your local machine, the following commands will install PHP, Composer, and the Laravel installer on macOS, Windows, or Linux: -> {tip} Already a Docker expert? Don't worry! Everything about Sail can be customized using the `docker-compose.yml` file included with Laravel. - - -### Getting Started On macOS +```shell tab=macOS +/bin/bash -c "$(curl -fsSL https://php.new/install/mac/8.4)" +``` -If you're developing on a Mac and [Docker Desktop](https://www.docker.com/products/docker-desktop) is already installed, you can use a simple terminal command to create a new Laravel project. For example, to create a new Laravel application in a directory named "example-app", you may run the following command in your terminal: +```shell tab=Windows PowerShell +# Run as administrator... +Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://php.new/install/windows/8.4')) +``` -```shell -curl -s "https://laravel.build/example-app" | bash +```shell tab=Linux +/bin/bash -c "$(curl -fsSL https://php.new/install/linux/8.4)" ``` -Of course, you can change "example-app" in this URL to anything you like. The Laravel application's directory will be created within the directory you execute the command from. +After running one of the commands above, you should restart your terminal session. To update PHP, Composer, and the Laravel installer after installing them via `php.new`, you can re-run the command in your terminal. -After the project has been created, you can navigate to the application directory and start Laravel Sail. Laravel Sail provides a simple command-line interface for interacting with Laravel's default Docker configuration: +If you already have PHP and Composer installed, you may install the Laravel installer via Composer: ```shell -cd example-app - -./vendor/bin/sail up +composer global require laravel/installer ``` -The first time you run the Sail `up` command, Sail's application containers will be built on your machine. This could take several minutes. **Don't worry, subsequent attempts to start Sail will be much faster.** - -Once the application's Docker containers have been started, you can access the application in your web browser at: http://localhost. - -> {tip} To continue learning more about Laravel Sail, review its [complete documentation](/docs/{{version}}/sail). +> [!NOTE] +> For a fully-featured, graphical PHP installation and management experience, check out [Laravel Herd](#installation-using-herd). - -### Getting Started On Windows + +### Creating an Application -Before we create a new Laravel application on your Windows machine, make sure to install [Docker Desktop](https://www.docker.com/products/docker-desktop). Next, you should ensure that Windows Subsystem for Linux 2 (WSL2) is installed and enabled. WSL allows you to run Linux binary executables natively on Windows 10. Information on how to install and enable WSL2 can be found within Microsoft's [developer environment documentation](https://docs.microsoft.com/en-us/windows/wsl/install-win10). - -> {tip} After installing and enabling WSL2, you should ensure that Docker Desktop is [configured to use the WSL2 backend](https://docs.docker.com/docker-for-windows/wsl/). - -Next, you are ready to create your first Laravel project. Launch [Windows Terminal](https://www.microsoft.com/en-us/p/windows-terminal/9n0dx20hk701?rtc=1&activetab=pivot:overviewtab) and begin a new terminal session for your WSL2 Linux operating system. Next, you can use a simple terminal command to create a new Laravel project. For example, to create a new Laravel application in a directory named "example-app", you may run the following command in your terminal: +After you have installed PHP, Composer, and the Laravel installer, you're ready to create a new Laravel application. The Laravel installer will prompt you to select your preferred testing framework, database, and starter kit: ```shell -curl -s https://laravel.build/example-app | bash +laravel new example-app ``` -Of course, you can change "example-app" in this URL to anything you like. The Laravel application's directory will be created within the directory you execute the command from. - -After the project has been created, you can navigate to the application directory and start Laravel Sail. Laravel Sail provides a simple command-line interface for interacting with Laravel's default Docker configuration: +Once the application has been created, you can start Laravel's local development server, queue worker, and Vite development server using the `dev` Composer script: ```shell cd example-app - -./vendor/bin/sail up +npm install && npm run build +composer run dev ``` -The first time you run the Sail `up` command, Sail's application containers will be built on your machine. This could take several minutes. **Don't worry, subsequent attempts to start Sail will be much faster.** - -Once the application's Docker containers have been started, you can access the application in your web browser at: http://localhost. - -> {tip} To continue learning more about Laravel Sail, review its [complete documentation](/docs/{{version}}/sail). - -#### Developing Within WSL2 +Once you have started the development server, your application will be accessible in your web browser at [http://localhost:8000](http://localhost:8000). Next, you're ready to [start taking your next steps into the Laravel ecosystem](#next-steps). Of course, you may also want to [configure a database](#databases-and-migrations). -Of course, you will need to be able to modify the Laravel application files that were created within your WSL2 installation. To accomplish this, we recommend using Microsoft's [Visual Studio Code](https://code.visualstudio.com) editor and their first-party extension for [Remote Development](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack). +> [!NOTE] +> If you would like a head start when developing your Laravel application, consider using one of our [starter kits](/docs/{{version}}/starter-kits). Laravel's starter kits provide backend and frontend authentication scaffolding for your new Laravel application. -Once these tools are installed, you may open any Laravel project by executing the `code .` command from your application's root directory using Windows Terminal. + +## Initial Configuration - -### Getting Started On Linux +All of the configuration files for the Laravel framework are stored in the `config` directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you. -If you're developing on Linux and [Docker Compose](https://docs.docker.com/compose/install/) is already installed, you can use a simple terminal command to create a new Laravel project. For example, to create a new Laravel application in a directory named "example-app", you may run the following command in your terminal: +Laravel needs almost no additional configuration out of the box. You are free to get started developing! However, you may wish to review the `config/app.php` file and its documentation. It contains several options such as `url` and `locale` that you may wish to change according to your application. -```shell -curl -s https://laravel.build/example-app | bash -``` + +### Environment Based Configuration -Of course, you can change "example-app" in this URL to anything you like. The Laravel application's directory will be created within the directory you execute the command from. +Since many of Laravel's configuration option values may vary depending on whether your application is running on your local machine or on a production web server, many important configuration values are defined using the `.env` file that exists at the root of your application. -After the project has been created, you can navigate to the application directory and start Laravel Sail. Laravel Sail provides a simple command-line interface for interacting with Laravel's default Docker configuration: +Your `.env` file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration. Furthermore, this would be a security risk in the event an intruder gains access to your source control repository, since any sensitive credentials would be exposed. -```shell -cd example-app +> [!NOTE] +> For more information about the `.env` file and environment based configuration, check out the full [configuration documentation](/docs/{{version}}/configuration#environment-configuration). -./vendor/bin/sail up -``` + +### Databases and Migrations -The first time you run the Sail `up` command, Sail's application containers will be built on your machine. This could take several minutes. **Don't worry, subsequent attempts to start Sail will be much faster.** +Now that you have created your Laravel application, you probably want to store some data in a database. By default, your application's `.env` configuration file specifies that Laravel will be interacting with an SQLite database. -Once the application's Docker containers have been started, you can access the application in your web browser at: http://localhost. +During the creation of the application, Laravel created a `database/database.sqlite` file for you, and ran the necessary migrations to create the application's database tables. -> {tip} To continue learning more about Laravel Sail, review its [complete documentation](/docs/{{version}}/sail). +If you prefer to use another database driver such as MySQL or PostgreSQL, you can update your `.env` configuration file to use the appropriate database. For example, if you wish to use MySQL, update your `.env` configuration file's `DB_*` variables like so: - -### Choosing Your Sail Services +```ini +DB_CONNECTION=mysql +DB_HOST=127.0.0.1 +DB_PORT=3306 +DB_DATABASE=laravel +DB_USERNAME=root +DB_PASSWORD= +``` -When creating a new Laravel application via Sail, you may use the `with` query string variable to choose which services should be configured in your new application's `docker-compose.yml` file. Available services include `mysql`, `pgsql`, `mariadb`, `redis`, `memcached`, `meilisearch`, `minio`, `selenium`, and `mailhog`: +If you choose to use a database other than SQLite, you will need to create the database and run your application's [database migrations](/docs/{{version}}/migrations): ```shell -curl -s "https://laravel.build/example-app?with=mysql,redis" | bash +php artisan migrate ``` -If you do not specify which services you would like configured, a default stack of `mysql`, `redis`, `meilisearch`, `mailhog`, and `selenium` will be configured. +> [!NOTE] +> If you are developing on macOS or Windows and need to install MySQL, PostgreSQL, or Redis locally, consider using [Herd Pro](https://herd.laravel.com/#plans) or [DBngin](https://dbngin.com/). -You may instruct Sail to install a default [Devcontainer](/docs/{{version}}/sail#using-devcontainers) by adding the `devcontainer` parameter to the URL: + +### Directory Configuration -```shell -curl -s "https://laravel.build/example-app?with=mysql,redis&devcontainer" | bash -``` +Laravel should always be served out of the root of the "web directory" configured for your web server. You should not attempt to serve a Laravel application out of a subdirectory of the "web directory". Attempting to do so could expose sensitive files present within your application. - -### Installation Via Composer + +## Installation Using Herd -If your computer already has PHP and Composer installed, you may create a new Laravel project by using Composer directly. After the application has been created, you may start Laravel's local development server using the Artisan CLI's `serve` command: +[Laravel Herd](https://herd.laravel.com) is a blazing fast, native Laravel and PHP development environment for macOS and Windows. Herd includes everything you need to get started with Laravel development, including PHP and Nginx. -```shell -composer create-project laravel/laravel example-app +Once you install Herd, you're ready to start developing with Laravel. Herd includes command line tools for `php`, `composer`, `laravel`, `expose`, `node`, `npm`, and `nvm`. -cd example-app +> [!NOTE] +> [Herd Pro](https://herd.laravel.com/#plans) augments Herd with additional powerful features, such as the ability to create and manage local MySQL, Postgres, and Redis databases, as well as local mail viewing and log monitoring. -php artisan serve -``` + +### Herd on macOS - -#### The Laravel Installer +If you develop on macOS, you can download the Herd installer from the [Herd website](https://herd.laravel.com). The installer automatically downloads the latest version of PHP and configures your Mac to always run [Nginx](https://www.nginx.com/) in the background. -Or, you may install the Laravel Installer as a global Composer dependency: +Herd for macOS uses [dnsmasq](https://en.wikipedia.org/wiki/Dnsmasq) to support "parked" directories. Any Laravel application in a parked directory will automatically be served by Herd. By default, Herd creates a parked directory at `~/Herd` and you can access any Laravel application in this directory on the `.test` domain using its directory name. -```shell -composer global require laravel/installer +After installing Herd, the fastest way to create a new Laravel application is using the Laravel CLI, which is bundled with Herd: -laravel new example-app +```shell +cd ~/Herd +laravel new my-app +cd my-app +herd open +``` -cd example-app +Of course, you can always manage your parked directories and other PHP settings via Herd's UI, which can be opened from the Herd menu in your system tray. -php artisan serve -``` +You can learn more about Herd by checking out the [Herd documentation](https://herd.laravel.com/docs). -Make sure to place Composer's system-wide vendor bin directory in your `$PATH` so the `laravel` executable can be located by your system. This directory exists in different locations based on your operating system; however, some common locations include: + +### Herd on Windows -
+You can download the Windows installer for Herd on the [Herd website](https://herd.laravel.com/windows). After the installation finishes, you can start Herd to complete the onboarding process and access the Herd UI for the first time. -- macOS: `$HOME/.composer/vendor/bin` -- Windows: `%USERPROFILE%\AppData\Roaming\Composer\vendor\bin` -- GNU / Linux Distributions: `$HOME/.config/composer/vendor/bin` or `$HOME/.composer/vendor/bin` +The Herd UI is accessible by left-clicking on Herd's system tray icon. A right-click opens the quick menu with access to all tools that you need on a daily basis. -
+During installation, Herd creates a "parked" directory in your home directory at `%USERPROFILE%\Herd`. Any Laravel application in a parked directory will automatically be served by Herd, and you can access any Laravel application in this directory on the `.test` domain using its directory name. -For convenience, the Laravel installer can also create a Git repository for your new project. To indicate that you want a Git repository to be created, pass the `--git` flag when creating a new project: +After installing Herd, the fastest way to create a new Laravel application is using the Laravel CLI, which is bundled with Herd. To get started, open Powershell and run the following commands: ```shell -laravel new example-app --git +cd ~\Herd +laravel new my-app +cd my-app +herd open ``` -This command will initialize a new Git repository for your project and automatically commit the base Laravel skeleton. The `git` flag assumes you have properly installed and configured Git. You can also use the `--branch` flag to set the initial branch name: +You can learn more about Herd by checking out the [Herd documentation for Windows](https://herd.laravel.com/docs/windows). -```shell -laravel new example-app --git --branch="main" -``` + +## IDE Support -Instead of using the `--git` flag, you may also use the `--github` flag to create a Git repository and also create a corresponding private repository on GitHub: +You are free to use any code editor you wish when developing Laravel applications. If you're looking for lightweight and extensible editors, [VS Code](https://code.visualstudio.com) or [Cursor](https://cursor.com) combined with the official [Laravel VS Code Extension](https://marketplace.visualstudio.com/items?itemName=laravel.vscode-laravel) offers excellent Laravel support with features like syntax highlighting, snippets, artisan command integration, and smart autocompletion for Eloquent models, routes, middleware, assets, config, and Inertia.js. -```shell -laravel new example-app --github -``` +For extensive and robust support of Laravel, take a look at [PhpStorm](https://www.jetbrains.com/phpstorm/laravel/?utm_source=laravel.com&utm_medium=link&utm_campaign=laravel-2025&utm_content=partner&ref=laravel-2025), a JetBrains IDE. With the [Laravel Idea plugin](https://laravel-idea.com/), it provides accurate support for Laravel and its ecosystem, including Laravel Pint, Pest, Larastan, and more. Laravel Idea's framework support includes Blade templates, smart autocompletion for Eloquent models, routes, views, translations, and components, along with powerful code generation and navigation across Laravel projects. -The created repository will then be available at `https://github.com//example-app`. The `github` flag assumes you have properly installed the [GitHub CLI](https://cli.github.com) and are authenticated with GitHub. Additionally, you should have `git` installed and properly configured. If needed, you can pass additional flags that are supported by the GitHub CLI: +For those seeking a cloud-based development experience, [Firebase Studio](https://firebase.studio/) provides instant access to building with Laravel directly in your browser. With zero setup required, Firebase Studio makes it easy to start building Laravel applications from any device. -```shell -laravel new example-app --github="--public" -``` + +## Laravel and AI -You may use the `--organization` flag to create the repository under a specific GitHub organization: +[Laravel Boost](https://github.com/laravel/boost) is a powerful tool that bridges the gap between AI coding agents and Laravel applications. Boost provides AI agents with Laravel-specific context, tools, and guidelines so they can generate more accurate, version-specific code that follows Laravel conventions. -```shell -laravel new example-app --github="--public" --organization="laravel" -``` +When you install Boost in your Laravel application, AI agents gain access to over 15 specialized tools including the ability to know which packages you are using, query your database, search the Laravel documentation, read browser logs, generate tests, and execute code via Tinker. - -## Initial Configuration +In addition, Boost gives AI agents access to over 17,000 pieces of vectorized Laravel ecosystem documentation, specific to your installed package versions. This means agents can provide guidance targeted to the exact versions your project uses. -All of the configuration files for the Laravel framework are stored in the `config` directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you. +Boost also includes Laravel-maintained AI guidelines that help agents to follow framework conventions, write appropriate tests, and avoid common pitfalls when generating Laravel code. -Laravel needs almost no additional configuration out of the box. You are free to get started developing! However, you may wish to review the `config/app.php` file and its documentation. It contains several options such as `timezone` and `locale` that you may wish to change according to your application. + +### Installing Laravel Boost - -### Environment Based Configuration +Boost can be installed in Laravel 10, 11, and 12 applications running PHP 8.1 or higher. To get started, install Boost as a development dependency: -Since many of Laravel's configuration option values may vary depending on whether your application is running on your local computer or on a production web server, many important configuration values are defined using the `.env` file that exists at the root of your application. +```shell +composer require laravel/boost --dev +``` -Your `.env` file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration. Furthermore, this would be a security risk in the event an intruder gains access to your source control repository, since any sensitive credentials would get exposed. +Once installed, run the interactive installer: -> {tip} For more information about the `.env` file and environment based configuration, check out the full [configuration documentation](/docs/{{version}}/configuration#environment-configuration). +```shell +php artisan boost:install +``` - -### Directory Configuration +The installer will auto-detect your IDE and AI agents, allowing you to opt into the features that make sense for your project. Boost respects existing project conventions and doesn't force opinionated style rules by default. -Laravel should always be served out of the root of the "web directory" configured for your web server. You should not attempt to serve a Laravel application out of a subdirectory of the "web directory". Attempting to do so could expose sensitive files that exist within your application. +> [!NOTE] +> To learn more about Boost, check out the [Laravel Boost repository on GitHub](https://github.com/laravel/boost). ## Next Steps -Now that you have created your Laravel project, you may be wondering what to learn next. First, we strongly recommend becoming familiar with how Laravel works by reading the following documentation: +Now that you have created your Laravel application, you may be wondering what to learn next. First, we strongly recommend becoming familiar with how Laravel works by reading the following documentation:
- [Request Lifecycle](/docs/{{version}}/lifecycle) - [Configuration](/docs/{{version}}/configuration) - [Directory Structure](/docs/{{version}}/structure) +- [Frontend](/docs/{{version}}/frontend) - [Service Container](/docs/{{version}}/container) - [Facades](/docs/{{version}}/facades) @@ -265,22 +263,20 @@ Now that you have created your Laravel project, you may be wondering what to lea How you want to use Laravel will also dictate the next steps on your journey. There are a variety of ways to use Laravel, and we'll explore two primary use cases for the framework below. -### Laravel The Full Stack Framework +### Laravel the Full Stack Framework -Laravel may serve as a full stack framework. By "full stack" framework we mean that you are going to use Laravel to route requests to your application and render your frontend via [Blade templates](/docs/{{version}}/blade) or using a single-page application hybrid technology like [Inertia.js](https://inertiajs.com). This is the most common way to use the Laravel framework. +Laravel may serve as a full stack framework. By "full stack" framework we mean that you are going to use Laravel to route requests to your application and render your frontend via [Blade templates](/docs/{{version}}/blade) or a single-page application hybrid technology like [Inertia](https://inertiajs.com). This is the most common way to use the Laravel framework, and, in our opinion, the most productive way to use Laravel. -If this is how you plan to use Laravel, you may want to check out our documentation on [routing](/docs/{{version}}/routing), [views](/docs/{{version}}/views), or the [Eloquent ORM](/docs/{{version}}/eloquent). In addition, you might be interested in learning about community packages like [Livewire](https://laravel-livewire.com) and [Inertia.js](https://inertiajs.com). These packages allow you to use Laravel as a full-stack framework while enjoying many of the UI benefits provided by single-page JavaScript applications. +If this is how you plan to use Laravel, you may want to check out our documentation on [frontend development](/docs/{{version}}/frontend), [routing](/docs/{{version}}/routing), [views](/docs/{{version}}/views), or the [Eloquent ORM](/docs/{{version}}/eloquent). In addition, you might be interested in learning about community packages like [Livewire](https://livewire.laravel.com) and [Inertia](https://inertiajs.com). These packages allow you to use Laravel as a full-stack framework while enjoying many of the UI benefits provided by single-page JavaScript applications. -If you are using Laravel as a full stack framework, we also strongly encourage you to learn how to compile your application's CSS and JavaScript using [Laravel Mix](/docs/{{version}}/mix). +If you are using Laravel as a full stack framework, we also strongly encourage you to learn how to compile your application's CSS and JavaScript using [Vite](/docs/{{version}}/vite). -> {tip} If you want to get a head start building your application, check out one of our official [application starter kits](/docs/{{version}}/starter-kits). +> [!NOTE] +> If you want to get a head start building your application, check out one of our official [application starter kits](/docs/{{version}}/starter-kits). -### Laravel The API Backend +### Laravel the API Backend Laravel may also serve as an API backend to a JavaScript single-page application or mobile application. For example, you might use Laravel as an API backend for your [Next.js](https://nextjs.org) application. In this context, you may use Laravel to provide [authentication](/docs/{{version}}/sanctum) and data storage / retrieval for your application, while also taking advantage of Laravel's powerful services such as queues, emails, notifications, and more. If this is how you plan to use Laravel, you may want to check out our documentation on [routing](/docs/{{version}}/routing), [Laravel Sanctum](/docs/{{version}}/sanctum), and the [Eloquent ORM](/docs/{{version}}/eloquent). - -> {tip} Need a head start scaffolding your Laravel backend and Next.js frontend? Laravel Breeze offers an [API stack](/docs/{{version}}/starter-kits#breeze-and-next) as well as a [Next.js frontend implementation](https://github.com/laravel/breeze-next) so you can get started in minutes. - diff --git a/lifecycle.md b/lifecycle.md index 356e9d2f411..98c78f1dda3 100644 --- a/lifecycle.md +++ b/lifecycle.md @@ -7,7 +7,7 @@ - [Service Providers](#service-providers) - [Routing](#routing) - [Finishing Up](#finishing-up) -- [Focus On Service Providers](#focus-on-service-providers) +- [Focus on Service Providers](#focus-on-service-providers) ## Introduction @@ -29,31 +29,31 @@ The `index.php` file loads the Composer generated autoloader definition, and the ### HTTP / Console Kernels -Next, the incoming request is sent to either the HTTP kernel or the console kernel, depending on the type of request that is entering the application. These two kernels serve as the central location that all requests flow through. For now, let's just focus on the HTTP kernel, which is located in `app/Http/Kernel.php`. +Next, the incoming request is sent to either the HTTP kernel or the console kernel, using the `handleRequest` or `handleCommand` methods of the application instance, depending on the type of request entering the application. These two kernels serve as the central location through which all requests flow. For now, let's just focus on the HTTP kernel, which is an instance of `Illuminate\Foundation\Http\Kernel`. -The HTTP kernel extends the `Illuminate\Foundation\Http\Kernel` class, which defines an array of `bootstrappers` that will be run before the request is executed. These bootstrappers configure error handling, configure logging, [detect the application environment](/docs/{{version}}/configuration#environment-configuration), and perform other tasks that need to be done before the request is actually handled. Typically, these classes handle internal Laravel configuration that you do not need to worry about. +The HTTP kernel defines an array of `bootstrappers` that will be run before the request is executed. These bootstrappers configure error handling, configure logging, [detect the application environment](/docs/{{version}}/configuration#environment-configuration), and perform other tasks that need to be done before the request is actually handled. Typically, these classes handle internal Laravel configuration that you do not need to worry about. -The HTTP kernel also defines a list of HTTP [middleware](/docs/{{version}}/middleware) that all requests must pass through before being handled by the application. These middleware handle reading and writing the [HTTP session](/docs/{{version}}/session), determining if the application is in maintenance mode, [verifying the CSRF token](/docs/{{version}}/csrf), and more. We'll talk more about these soon. +The HTTP kernel is also responsible for passing the request through the application's middleware stack. These middleware handle reading and writing the [HTTP session](/docs/{{version}}/session), determining if the application is in maintenance mode, [verifying the CSRF token](/docs/{{version}}/csrf), and more. We'll talk more about these soon. The method signature for the HTTP kernel's `handle` method is quite simple: it receives a `Request` and returns a `Response`. Think of the kernel as being a big black box that represents your entire application. Feed it HTTP requests and it will return HTTP responses. ### Service Providers -One of the most important kernel bootstrapping actions is loading the [service providers](/docs/{{version}}/providers) for your application. All of the service providers for the application are configured in the `config/app.php` configuration file's `providers` array. +One of the most important kernel bootstrapping actions is loading the [service providers](/docs/{{version}}/providers) for your application. Service providers are responsible for bootstrapping all of the framework's various components, such as the database, queue, validation, and routing components. Laravel will iterate through this list of providers and instantiate each of them. After instantiating the providers, the `register` method will be called on all of the providers. Then, once all of the providers have been registered, the `boot` method will be called on each provider. This is so service providers may depend on every container binding being registered and available by the time their `boot` method is executed. -Service providers are responsible for bootstrapping all of the framework's various components, such as the database, queue, validation, and routing components. Essentially every major feature offered by Laravel is bootstrapped and configured by a service provider. Since they bootstrap and configure so many features offered by the framework, service providers are the most important aspect of the entire Laravel bootstrap process. +Essentially every major feature offered by Laravel is bootstrapped and configured by a service provider. Since they bootstrap and configure so many features offered by the framework, service providers are the most important aspect of the entire Laravel bootstrap process. + +While the framework internally uses dozens of service providers, you also have the option to create your own. You can find a list of the user-defined or third-party service providers that your application is using in the `bootstrap/providers.php` file. ### Routing -One of the most important service providers in your application is the `App\Providers\RouteServiceProvider`. This service provider loads the route files contained within your application's `routes` directory. Go ahead, crack open the `RouteServiceProvider` code and take a look at how it works! - Once the application has been bootstrapped and all service providers have been registered, the `Request` will be handed off to the router for dispatching. The router will dispatch the request to a route or controller, as well as run any route specific middleware. -Middleware provide a convenient mechanism for filtering or examining HTTP requests entering your application. For example, Laravel includes a middleware that verifies if the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. Some middleware are assigned to all routes within the application, like those defined in the `$middleware` property of your HTTP kernel, while some are only assigned to specific routes or route groups. You can learn more about middleware by reading the complete [middleware documentation](/docs/{{version}}/middleware). +Middleware provide a convenient mechanism for filtering or examining HTTP requests entering your application. For example, Laravel includes a middleware that verifies if the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. Some middleware are assigned to all routes within the application, like `PreventRequestsDuringMaintenance`, while some are only assigned to specific routes or route groups. You can learn more about middleware by reading the complete [middleware documentation](/docs/{{version}}/middleware). If the request passes through all of the matched route's assigned middleware, the route or controller method will be executed and the response returned by the route or controller method will be sent back through the route's chain of middleware. @@ -62,13 +62,13 @@ If the request passes through all of the matched route's assigned middleware, th Once the route or controller method returns a response, the response will travel back outward through the route's middleware, giving the application a chance to modify or examine the outgoing response. -Finally, once the response travels back through the middleware, the HTTP kernel's `handle` method returns the response object and the `index.php` file calls the `send` method on the returned response. The `send` method sends the response content to the user's web browser. We've finished our journey through the entire Laravel request lifecycle! +Finally, once the response travels back through the middleware, the HTTP kernel's `handle` method returns the response object to the `handleRequest` of the application instance, and this method calls the `send` method on the returned response. The `send` method sends the response content to the user's web browser. We've now completed our journey through the entire Laravel request lifecycle! -## Focus On Service Providers +## Focus on Service Providers Service providers are truly the key to bootstrapping a Laravel application. The application instance is created, the service providers are registered, and the request is handed to the bootstrapped application. It's really that simple! -Having a firm grasp of how a Laravel application is built and bootstrapped via service providers is very valuable. Your application's default service providers are stored in the `app/Providers` directory. +Having a firm grasp of how a Laravel application is built and bootstrapped via service providers is very valuable. Your application's user-defined service providers are stored in the `app/Providers` directory. By default, the `AppServiceProvider` is fairly empty. This provider is a great place to add your application's own bootstrapping and service container bindings. For large applications, you may wish to create several service providers, each with more granular bootstrapping for specific services used by your application. diff --git a/localization.md b/localization.md index faf658f3681..e7649199486 100644 --- a/localization.md +++ b/localization.md @@ -1,71 +1,123 @@ # Localization - [Introduction](#introduction) - - [Configuring The Locale](#configuring-the-locale) + - [Publishing the Language Files](#publishing-the-language-files) + - [Configuring the Locale](#configuring-the-locale) + - [Pluralization Language](#pluralization-language) - [Defining Translation Strings](#defining-translation-strings) - [Using Short Keys](#using-short-keys) - - [Using Translation Strings As Keys](#using-translation-strings-as-keys) + - [Using Translation Strings as Keys](#using-translation-strings-as-keys) - [Retrieving Translation Strings](#retrieving-translation-strings) - - [Replacing Parameters In Translation Strings](#replacing-parameters-in-translation-strings) + - [Replacing Parameters in Translation Strings](#replacing-parameters-in-translation-strings) - [Pluralization](#pluralization) - [Overriding Package Language Files](#overriding-package-language-files) ## Introduction +> [!NOTE] +> By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. + Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application. -Laravel provides two ways to manage translation strings. First, language strings may be stored in files within the `lang` directory. Within this directory, there may be subdirectories for each language supported by the application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages: +Laravel provides two ways to manage translation strings. First, language strings may be stored in files within the application's `lang` directory. Within this directory, there may be subdirectories for each language supported by the application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages: - /lang - /en - messages.php - /es - messages.php +```text +/lang + /en + messages.php + /es + messages.php +``` -Or, translation strings may be defined within JSON files that are placed within the `lang` directory. When taking this approach, each language supported by your application would have a corresponding JSON file within this directory. This approach is recommended for application's that have a large number of translatable strings: +Or, translation strings may be defined within JSON files that are placed within the `lang` directory. When taking this approach, each language supported by your application would have a corresponding JSON file within this directory. This approach is recommended for applications that have a large number of translatable strings: - /lang - en.json - es.json +```text +/lang + en.json + es.json +``` We'll discuss each approach to managing translation strings within this documentation. - -### Configuring The Locale + +### Publishing the Language Files -The default language for your application is stored in the `config/app.php` configuration file's `locale` configuration option. You are free to modify this value to suit the needs of your application. +By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files or create your own, you should scaffold the `lang` directory via the `lang:publish` Artisan command. The `lang:publish` command will create the `lang` directory in your application and publish the default set of language files used by Laravel: -You may modify the default language for a single HTTP request at runtime using the `setLocale` method provided by the `App` facade: +```shell +php artisan lang:publish +``` - use Illuminate\Support\Facades\App; + +### Configuring the Locale - Route::get('/greeting/{locale}', function ($locale) { - if (! in_array($locale, ['en', 'es', 'fr'])) { - abort(400); - } +The default language for your application is stored in the `config/app.php` configuration file's `locale` configuration option, which is typically set using the `APP_LOCALE` environment variable. You are free to modify this value to suit the needs of your application. - App::setLocale($locale); +You may also configure a "fallback language", which will be used when the default language does not contain a given translation string. Like the default language, the fallback language is also configured in the `config/app.php` configuration file, and its value is typically set using the `APP_FALLBACK_LOCALE` environment variable. - // - }); +You may modify the default language for a single HTTP request at runtime using the `setLocale` method provided by the `App` facade: + +```php +use Illuminate\Support\Facades\App; -You may configure a "fallback language", which will be used when the active language does not contain a given translation string. Like the default language, the fallback language is also configured in the `config/app.php` configuration file: +Route::get('/greeting/{locale}', function (string $locale) { + if (! in_array($locale, ['en', 'es', 'fr'])) { + abort(400); + } + + App::setLocale($locale); - 'fallback_locale' => 'en', + // ... +}); +``` -#### Determining The Current Locale +#### Determining the Current Locale You may use the `currentLocale` and `isLocale` methods on the `App` facade to determine the current locale or check if the locale is a given value: - use Illuminate\Support\Facades\App; +```php +use Illuminate\Support\Facades\App; - $locale = App::currentLocale(); +$locale = App::currentLocale(); - if (App::isLocale('en')) { - // - } +if (App::isLocale('en')) { + // ... +} +``` + + +### Pluralization Language + + + +
+ +You may instruct Laravel's "pluralizer", which is used by Eloquent and other portions of the framework to convert singular strings to plural strings, to use a language other than English. This may be accomplished by invoking the `useLanguage` method within the `boot` method of one of your application's service providers. The pluralizer's currently supported languages are: `french`, `norwegian-bokmal`, `portuguese`, `spanish`, and `turkish`: + +
+ +```php +use Illuminate\Support\Pluralizer; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Pluralizer::useLanguage('spanish'); + + // ... +} +``` + +> [!WARNING] +> If you customize the pluralizer's language, you should explicitly define your Eloquent model's [table names](/docs/{{version}}/eloquent#table-names). ## Defining Translation Strings @@ -75,30 +127,35 @@ You may use the `currentLocale` and `isLocale` methods on the `App` facade to de Typically, translation strings are stored in files within the `lang` directory. Within this directory, there should be a subdirectory for each language supported by your application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages: - /lang - /en - messages.php - /es - messages.php +```text +/lang + /en + messages.php + /es + messages.php +``` All language files return an array of keyed strings. For example: - 'Welcome to our application!', - ]; +return [ + 'welcome' => 'Welcome to our application!', +]; +``` -> {note} For languages that differ by territory, you should name the language directories according to the ISO 15897. For example, "en_GB" should be used for British English rather than "en-gb". +> [!WARNING] +> For languages that differ by territory, you should name the language directories according to the ISO 15897. For example, "en_GB" should be used for British English rather than "en-gb". -### Using Translation Strings As Keys +### Using Translation Strings as Keys For applications with a large number of translatable strings, defining every string with a "short key" can become confusing when referencing the keys in your views and it is cumbersome to continually invent keys for every translation string supported by your application. -For this reason, Laravel also provides support for defining translation strings using the "default" translation of the string as the key. Translation files that use translation strings as keys are stored as JSON files in the `lang` directory. For example, if your application has a Spanish translation, you should create a `lang/es.json` file: +For this reason, Laravel also provides support for defining translation strings using the "default" translation of the string as the key. Language files that use translation strings as keys are stored as JSON files in the `lang` directory. For example, if your application has a Spanish translation, you should create a `lang/es.json` file: ```json { @@ -108,49 +165,85 @@ For this reason, Laravel also provides support for defining translation strings #### Key / File Conflicts -You should not define translation string keys that conflict with other translation filenames. For example, translating `__('Action')` for the "NL" locale while a `nl/action.php` file exists but a `nl.json` file does not exist will result in the translator returning the contents of `nl/action.php`. +You should not define translation string keys that conflict with other translation filenames. For example, translating `__('Action')` for the "NL" locale while a `nl/action.php` file exists but a `nl.json` file does not exist will result in the translator returning the entire contents of `nl/action.php`. ## Retrieving Translation Strings You may retrieve translation strings from your language files using the `__` helper function. If you are using "short keys" to define your translation strings, you should pass the file that contains the key and the key itself to the `__` function using "dot" syntax. For example, let's retrieve the `welcome` translation string from the `lang/en/messages.php` language file: - echo __('messages.welcome'); +```php +echo __('messages.welcome'); +``` If the specified translation string does not exist, the `__` function will return the translation string key. So, using the example above, the `__` function would return `messages.welcome` if the translation string does not exist. - If you are using your [default translation strings as your translation keys](#using-translation-strings-as-keys), you should pass the default translation of your string to the `__` function; +If you are using your [default translation strings as your translation keys](#using-translation-strings-as-keys), you should pass the default translation of your string to the `__` function; - echo __('I love programming.'); +```php +echo __('I love programming.'); +``` Again, if the translation string does not exist, the `__` function will return the translation string key that it was given. If you are using the [Blade templating engine](/docs/{{version}}/blade), you may use the `{{ }}` echo syntax to display the translation string: - {{ __('messages.welcome') }} +```blade +{{ __('messages.welcome') }} +``` -### Replacing Parameters In Translation Strings +### Replacing Parameters in Translation Strings If you wish, you may define placeholders in your translation strings. All placeholders are prefixed with a `:`. For example, you may define a welcome message with a placeholder name: - 'welcome' => 'Welcome, :name', +```php +'welcome' => 'Welcome, :name', +``` To replace the placeholders when retrieving a translation string, you may pass an array of replacements as the second argument to the `__` function: - echo __('messages.welcome', ['name' => 'dayle']); +```php +echo __('messages.welcome', ['name' => 'dayle']); +``` If your placeholder contains all capital letters, or only has its first letter capitalized, the translated value will be capitalized accordingly: - 'welcome' => 'Welcome, :NAME', // Welcome, DAYLE - 'goodbye' => 'Goodbye, :Name', // Goodbye, Dayle +```php +'welcome' => 'Welcome, :NAME', // Welcome, DAYLE +'goodbye' => 'Goodbye, :Name', // Goodbye, Dayle +``` + + +#### Object Replacement Formatting + +If you attempt to provide an object as a translation placeholder, the object's `__toString` method will be invoked. The [__toString](https://www.php.net/manual/en/language.oop5.magic.php#object.tostring) method is one of PHP's built-in "magic methods". However, sometimes you may not have control over the `__toString` method of a given class, such as when the class that you are interacting with belongs to a third-party library. + +In these cases, Laravel allows you to register a custom formatting handler for that particular type of object. To accomplish this, you should invoke the translator's `stringable` method. The `stringable` method accepts a closure, which should type-hint the type of object that it is responsible for formatting. Typically, the `stringable` method should be invoked within the `boot` method of your application's `AppServiceProvider` class: + +```php +use Illuminate\Support\Facades\Lang; +use Money\Money; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Lang::stringable(function (Money $money) { + return $money->formatTo('en_GB'); + }); +} +``` ### Pluralization Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization; however, Laravel can help you translate strings differently based on pluralization rules that you define. Using a `|` character, you may distinguish singular and plural forms of a string: - 'apples' => 'There is one apple|There are many apples', +```php +'apples' => 'There is one apple|There are many apples', +``` Of course, pluralization is also supported when using [translation strings as keys](#using-translation-strings-as-keys): @@ -162,21 +255,29 @@ Of course, pluralization is also supported when using [translation strings as ke You may even create more complex pluralization rules which specify translation strings for multiple ranges of values: - 'apples' => '{0} There are none|[1,19] There are some|[20,*] There are many', +```php +'apples' => '{0} There are none|[1,19] There are some|[20,*] There are many', +``` After defining a translation string that has pluralization options, you may use the `trans_choice` function to retrieve the line for a given "count". In this example, since the count is greater than one, the plural form of the translation string is returned: - echo trans_choice('messages.apples', 10); +```php +echo trans_choice('messages.apples', 10); +``` You may also define placeholder attributes in pluralization strings. These placeholders may be replaced by passing an array as the third argument to the `trans_choice` function: - 'minutes_ago' => '{1} :value minute ago|[2,*] :value minutes ago', +```php +'minutes_ago' => '{1} :value minute ago|[2,*] :value minutes ago', - echo trans_choice('time.minutes_ago', 5, ['value' => 5]); +echo trans_choice('time.minutes_ago', 5, ['value' => 5]); +``` If you would like to display the integer value that was passed to the `trans_choice` function, you may use the built-in `:count` placeholder: - 'apples' => '{0} There are none|{1} There is one|[2,*] There are :count', +```php +'apples' => '{0} There are none|{1} There is one|[2,*] There are :count', +``` ## Overriding Package Language Files diff --git a/logging.md b/logging.md index 02d886d1352..0de5c8ae320 100644 --- a/logging.md +++ b/logging.md @@ -8,11 +8,15 @@ - [Building Log Stacks](#building-log-stacks) - [Writing Log Messages](#writing-log-messages) - [Contextual Information](#contextual-information) - - [Writing To Specific Channels](#writing-to-specific-channels) + - [Writing to Specific Channels](#writing-to-specific-channels) - [Monolog Channel Customization](#monolog-channel-customization) - - [Customizing Monolog For Channels](#customizing-monolog-for-channels) + - [Customizing Monolog for Channels](#customizing-monolog-for-channels) - [Creating Monolog Handler Channels](#creating-monolog-handler-channels) - - [Creating Custom Channels Via Factories](#creating-custom-channels-via-factories) + - [Creating Custom Channels via Factories](#creating-custom-channels-via-factories) +- [Tailing Log Messages Using Pail](#tailing-log-messages-using-pail) + - [Installation](#pail-installation) + - [Usage](#pail-usage) + - [Filtering Logs](#pail-filtering-logs) ## Introduction @@ -26,360 +30,571 @@ Under the hood, Laravel utilizes the [Monolog](https://github.com/Seldaek/monolo ## Configuration -All of the configuration options for your application's logging behavior is housed in the `config/logging.php` configuration file. This file allows you to configure your application's log channels, so be sure to review each of the available channels and their options. We'll review a few common options below. +All of the configuration options that control your application's logging behavior are housed in the `config/logging.php` configuration file. This file allows you to configure your application's log channels, so be sure to review each of the available channels and their options. We'll review a few common options below. By default, Laravel will use the `stack` channel when logging messages. The `stack` channel is used to aggregate multiple log channels into a single channel. For more information on building stacks, check out the [documentation below](#building-log-stacks). - -#### Configuring The Channel Name - -By default, Monolog is instantiated with a "channel name" that matches the current environment, such as `production` or `local`. To change this value, add a `name` option to your channel's configuration: - - 'stack' => [ - 'driver' => 'stack', - 'name' => 'channel-name', - 'channels' => ['single', 'slack'], - ], - ### Available Channel Drivers Each log channel is powered by a "driver". The driver determines how and where the log message is actually recorded. The following log channel drivers are available in every Laravel application. An entry for most of these drivers is already present in your application's `config/logging.php` configuration file, so be sure to review this file to become familiar with its contents: -Name | Description -------------- | ------------- -`custom` | A driver that calls a specified factory to create a channel -`daily` | A `RotatingFileHandler` based Monolog driver which rotates daily -`errorlog` | An `ErrorLogHandler` based Monolog driver -`monolog` | A Monolog factory driver that may use any supported Monolog handler -`null` | A driver that discards all log messages -`papertrail` | A `SyslogUdpHandler` based Monolog driver -`single` | A single file or path based logger channel (`StreamHandler`) -`slack` | A `SlackWebhookHandler` based Monolog driver -`stack` | A wrapper to facilitate creating "multi-channel" channels -`syslog` | A `SyslogHandler` based Monolog driver - -> {tip} Check out the documentation on [advanced channel customization](#monolog-channel-customization) to learn more about the `monolog` and `custom` drivers. +
+ +| Name | Description | +| ------------ | -------------------------------------------------------------------- | +| `custom` | A driver that calls a specified factory to create a channel. | +| `daily` | A `RotatingFileHandler` based Monolog driver which rotates daily. | +| `errorlog` | An `ErrorLogHandler` based Monolog driver. | +| `monolog` | A Monolog factory driver that may use any supported Monolog handler. | +| `papertrail` | A `SyslogUdpHandler` based Monolog driver. | +| `single` | A single file or path based logger channel (`StreamHandler`). | +| `slack` | A `SlackWebhookHandler` based Monolog driver. | +| `stack` | A wrapper to facilitate creating "multi-channel" channels. | +| `syslog` | A `SyslogHandler` based Monolog driver. | + +
+ +> [!NOTE] +> Check out the documentation on [advanced channel customization](#monolog-channel-customization) to learn more about the `monolog` and `custom` drivers. + + +#### Configuring the Channel Name + +By default, Monolog is instantiated with a "channel name" that matches the current environment, such as `production` or `local`. To change this value, you may add a `name` option to your channel's configuration: + +```php +'stack' => [ + 'driver' => 'stack', + 'name' => 'channel-name', + 'channels' => ['single', 'slack'], +], +``` ### Channel Prerequisites -#### Configuring The Single and Daily Channels +#### Configuring the Single and Daily Channels The `single` and `daily` channels have three optional configuration options: `bubble`, `permission`, and `locking`. -Name | Description | Default -------------- | ------------- | ------------- -`bubble` | Indicates if messages should bubble up to other channels after being handled | `true` -`locking` | Attempt to lock the log file before writing to it | `false` -`permission` | The log file's permissions | `0644` +
+ +| Name | Description | Default | +| ------------ | ----------------------------------------------------------------------------- | ------- | +| `bubble` | Indicates if messages should bubble up to other channels after being handled. | `true` | +| `locking` | Attempt to lock the log file before writing to it. | `false` | +| `permission` | The log file's permissions. | `0644` | + +
+ +Additionally, the retention policy for the `daily` channel can be configured via the `LOG_DAILY_DAYS` environment variable or by setting the `days` configuration option. + +
+ +| Name | Description | Default | +| ------ | ----------------------------------------------------------- | ------- | +| `days` | The number of days that daily log files should be retained. | `14` | + +
-#### Configuring The Papertrail Channel +#### Configuring the Papertrail Channel -The `papertrail` channel requires the `host` and `port` configuration options. You can obtain these values from [Papertrail](https://help.papertrailapp.com/kb/configuration/configuring-centralized-logging-from-php-apps/#send-events-from-php-app). +The `papertrail` channel requires `host` and `port` configuration options. These may be defined via the `PAPERTRAIL_URL` and `PAPERTRAIL_PORT` environment variables. You can obtain these values from [Papertrail](https://help.papertrailapp.com/kb/configuration/configuring-centralized-logging-from-php-apps/#send-events-from-php-app). -#### Configuring The Slack Channel +#### Configuring the Slack Channel -The `slack` channel requires a `url` configuration option. This URL should match a URL for an [incoming webhook](https://slack.com/apps/A0F7XDUAZ-incoming-webhooks) that you have configured for your Slack team. +The `slack` channel requires a `url` configuration option. This value may be defined via the `LOG_SLACK_WEBHOOK_URL` environment variable. This URL should match a URL for an [incoming webhook](https://slack.com/apps/A0F7XDUAZ-incoming-webhooks) that you have configured for your Slack team. -By default, Slack will only receive logs at the `critical` level and above; however, you can adjust this in your `config/logging.php` configuration file by modifying the `level` configuration option within your Slack log channel's configuration array. +By default, Slack will only receive logs at the `critical` level and above; however, you can adjust this using the `LOG_LEVEL` environment variable or by modifying the `level` configuration option within your Slack log channel's configuration array. ### Logging Deprecation Warnings -PHP, Laravel, and other libraries often notify their users that some of their features have been deprecated and will be removed in a future version. If you would like to log these deprecation warnings, you may specify your preferred `deprecations` log channel in your application's `config/logging.php` configuration file: +PHP, Laravel, and other libraries often notify their users that some of their features have been deprecated and will be removed in a future version. If you would like to log these deprecation warnings, you may specify your preferred `deprecations` log channel using the `LOG_DEPRECATIONS_CHANNEL` environment variable, or within your application's `config/logging.php` configuration file: - 'deprecations' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), +```php +'deprecations' => [ + 'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), + 'trace' => env('LOG_DEPRECATIONS_TRACE', false), +], - 'channels' => [ - ... - ] +'channels' => [ + // ... +] +``` Or, you may define a log channel named `deprecations`. If a log channel with this name exists, it will always be used to log deprecations: - 'channels' => [ - 'deprecations' => [ - 'driver' => 'single', - 'path' => storage_path('logs/php-deprecation-warnings.log'), - ], +```php +'channels' => [ + 'deprecations' => [ + 'driver' => 'single', + 'path' => storage_path('logs/php-deprecation-warnings.log'), ], +], +``` ## Building Log Stacks As mentioned previously, the `stack` driver allows you to combine multiple channels into a single log channel for convenience. To illustrate how to use log stacks, let's take a look at an example configuration that you might see in a production application: - 'channels' => [ - 'stack' => [ - 'driver' => 'stack', - 'channels' => ['syslog', 'slack'], - ], +```php +'channels' => [ + 'stack' => [ + 'driver' => 'stack', + 'channels' => ['syslog', 'slack'], // [tl! add] + 'ignore_exceptions' => false, + ], - 'syslog' => [ - 'driver' => 'syslog', - 'level' => 'debug', - ], + 'syslog' => [ + 'driver' => 'syslog', + 'level' => env('LOG_LEVEL', 'debug'), + 'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER), + 'replace_placeholders' => true, + ], - 'slack' => [ - 'driver' => 'slack', - 'url' => env('LOG_SLACK_WEBHOOK_URL'), - 'username' => 'Laravel Log', - 'emoji' => ':boom:', - 'level' => 'critical', - ], + 'slack' => [ + 'driver' => 'slack', + 'url' => env('LOG_SLACK_WEBHOOK_URL'), + 'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'), + 'emoji' => env('LOG_SLACK_EMOJI', ':boom:'), + 'level' => env('LOG_LEVEL', 'critical'), + 'replace_placeholders' => true, ], +], +``` Let's dissect this configuration. First, notice our `stack` channel aggregates two other channels via its `channels` option: `syslog` and `slack`. So, when logging messages, both of these channels will have the opportunity to log the message. However, as we will see below, whether these channels actually log the message may be determined by the message's severity / "level". #### Log Levels -Take note of the `level` configuration option present on the `syslog` and `slack` channel configurations in the example above. This option determines the minimum "level" a message must be in order to be logged by the channel. Monolog, which powers Laravel's logging services, offers all of the log levels defined in the [RFC 5424 specification](https://tools.ietf.org/html/rfc5424): **emergency**, **alert**, **critical**, **error**, **warning**, **notice**, **info**, and **debug**. +Take note of the `level` configuration option present on the `syslog` and `slack` channel configurations in the example above. This option determines the minimum "level" a message must be in order to be logged by the channel. Monolog, which powers Laravel's logging services, offers all of the log levels defined in the [RFC 5424 specification](https://tools.ietf.org/html/rfc5424). In descending order of severity, these log levels are: **emergency**, **alert**, **critical**, **error**, **warning**, **notice**, **info**, and **debug**. So, imagine we log a message using the `debug` method: - Log::debug('An informational message.'); +```php +Log::debug('An informational message.'); +``` Given our configuration, the `syslog` channel will write the message to the system log; however, since the error message is not `critical` or above, it will not be sent to Slack. However, if we log an `emergency` message, it will be sent to both the system log and Slack since the `emergency` level is above our minimum level threshold for both channels: - Log::emergency('The system is down!'); +```php +Log::emergency('The system is down!'); +``` ## Writing Log Messages You may write information to the logs using the `Log` [facade](/docs/{{version}}/facades). As previously mentioned, the logger provides the eight logging levels defined in the [RFC 5424 specification](https://tools.ietf.org/html/rfc5424): **emergency**, **alert**, **critical**, **error**, **warning**, **notice**, **info** and **debug**: - use Illuminate\Support\Facades\Log; +```php +use Illuminate\Support\Facades\Log; - Log::emergency($message); - Log::alert($message); - Log::critical($message); - Log::error($message); - Log::warning($message); - Log::notice($message); - Log::info($message); - Log::debug($message); +Log::emergency($message); +Log::alert($message); +Log::critical($message); +Log::error($message); +Log::warning($message); +Log::notice($message); +Log::info($message); +Log::debug($message); +``` You may call any of these methods to log a message for the corresponding level. By default, the message will be written to the default log channel as configured by your `logging` configuration file: - User::findOrFail($id) - ]); - } + Log::info('Showing the user profile for user: {id}', ['id' => $id]); + + return view('user.profile', [ + 'user' => User::findOrFail($id) + ]); } +} +``` ### Contextual Information An array of contextual data may be passed to the log methods. This contextual data will be formatted and displayed with the log message: - use Illuminate\Support\Facades\Log; +```php +use Illuminate\Support\Facades\Log; - Log::info('User failed to login.', ['id' => $user->id]); +Log::info('User {id} failed to login.', ['id' => $user->id]); +``` -Occasionally, you may wish to specify some contextual information that should be included with all subsequent log entries. For example, you may wish to log a request ID that is associated with each incoming request to your application. To accomplish this, you may call the `Log` facade's `withContext` method: +Occasionally, you may wish to specify some contextual information that should be included with all subsequent log entries in a particular channel. For example, you may wish to log a request ID that is associated with each incoming request to your application. To accomplish this, you may call the `Log` facade's `withContext` method: - $requestId - ]); - - return $next($request)->header('Request-Id', $requestId); - } + $requestId = (string) Str::uuid(); + + Log::withContext([ + 'request-id' => $requestId + ]); + + $response = $next($request); + + $response->headers->set('Request-Id', $requestId); + + return $response; } +} +``` + +If you would like to share contextual information across _all_ logging channels, you may invoke the `Log::shareContext()` method. This method will provide the contextual information to all created channels and any channels that are created subsequently: + +```php + $requestId + ]); + + // ... + } +} +``` + +> [!NOTE] +> If you need to share log context while processing queued jobs, you may utilize [job middleware](/docs/{{version}}/queues#job-middleware). -### Writing To Specific Channels +### Writing to Specific Channels Sometimes you may wish to log a message to a channel other than your application's default channel. You may use the `channel` method on the `Log` facade to retrieve and log to any channel defined in your configuration file: - use Illuminate\Support\Facades\Log; +```php +use Illuminate\Support\Facades\Log; - Log::channel('slack')->info('Something happened!'); +Log::channel('slack')->info('Something happened!'); +``` If you would like to create an on-demand logging stack consisting of multiple channels, you may use the `stack` method: - Log::stack(['single', 'slack'])->info('Something happened!'); +```php +Log::stack(['single', 'slack'])->info('Something happened!'); +``` #### On-Demand Channels It is also possible to create an on-demand channel by providing the configuration at runtime without that configuration being present in your application's `logging` configuration file. To accomplish this, you may pass a configuration array to the `Log` facade's `build` method: - use Illuminate\Support\Facades\Log; +```php +use Illuminate\Support\Facades\Log; - Log::build([ - 'driver' => 'single', - 'path' => storage_path('logs/custom.log'), - ])->info('Something happened!'); +Log::build([ + 'driver' => 'single', + 'path' => storage_path('logs/custom.log'), +])->info('Something happened!'); +``` You may also wish to include an on-demand channel in an on-demand logging stack. This can be achieved by including your on-demand channel instance in the array passed to the `stack` method: - use Illuminate\Support\Facades\Log; +```php +use Illuminate\Support\Facades\Log; - $channel = Log::build([ - 'driver' => 'single', - 'path' => storage_path('logs/custom.log'), - ]); +$channel = Log::build([ + 'driver' => 'single', + 'path' => storage_path('logs/custom.log'), +]); - Log::stack(['slack', $channel])->info('Something happened!'); +Log::stack(['slack', $channel])->info('Something happened!'); +``` ## Monolog Channel Customization -### Customizing Monolog For Channels +### Customizing Monolog for Channels Sometimes you may need complete control over how Monolog is configured for an existing channel. For example, you may want to configure a custom Monolog `FormatterInterface` implementation for Laravel's built-in `single` channel. To get started, define a `tap` array on the channel's configuration. The `tap` array should contain a list of classes that should have an opportunity to customize (or "tap" into) the Monolog instance after it is created. There is no conventional location where these classes should be placed, so you are free to create a directory within your application to contain these classes: - 'single' => [ - 'driver' => 'single', - 'tap' => [App\Logging\CustomizeFormatter::class], - 'path' => storage_path('logs/laravel.log'), - 'level' => 'debug', - ], +```php +'single' => [ + 'driver' => 'single', + 'tap' => [App\Logging\CustomizeFormatter::class], + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), + 'replace_placeholders' => true, +], +``` Once you have configured the `tap` option on your channel, you're ready to define the class that will customize your Monolog instance. This class only needs a single method: `__invoke`, which receives an `Illuminate\Log\Logger` instance. The `Illuminate\Log\Logger` instance proxies all method calls to the underlying Monolog instance: - getHandlers() as $handler) { - $handler->setFormatter(new LineFormatter( - '[%datetime%] %channel%.%level_name%: %message% %context% %extra%' - )); - } + foreach ($logger->getHandlers() as $handler) { + $handler->setFormatter(new LineFormatter( + '[%datetime%] %channel%.%level_name%: %message% %context% %extra%' + )); } } +} +``` -> {tip} All of your "tap" classes are resolved by the [service container](/docs/{{version}}/container), so any constructor dependencies they require will automatically be injected. +> [!NOTE] +> All of your "tap" classes are resolved by the [service container](/docs/{{version}}/container), so any constructor dependencies they require will automatically be injected. ### Creating Monolog Handler Channels -Monolog has a variety of [available handlers](https://github.com/Seldaek/monolog/tree/main/src/Monolog/Handler) and Laravel does not include a built-in channel for each one. In some cases, you may wish to create a custom channel that is merely an instance of a specific Monolog handler that does not have a corresponding Laravel log driver. These channels can be easily created using the `monolog` driver. +Monolog has a variety of [available handlers](https://github.com/Seldaek/monolog/tree/main/src/Monolog/Handler) and Laravel does not include a built-in channel for each one. In some cases, you may wish to create a custom channel that is merely an instance of a specific Monolog handler that does not have a corresponding Laravel log driver. These channels can be easily created using the `monolog` driver. -When using the `monolog` driver, the `handler` configuration option is used to specify which handler will be instantiated. Optionally, any constructor parameters the handler needs may be specified using the `with` configuration option: +When using the `monolog` driver, the `handler` configuration option is used to specify which handler will be instantiated. Optionally, any constructor parameters the handler needs may be specified using the `handler_with` configuration option: - 'logentries' => [ - 'driver' => 'monolog', - 'handler' => Monolog\Handler\SyslogUdpHandler::class, - 'with' => [ - 'host' => 'my.logentries.internal.datahubhost.company.com', - 'port' => '10000', - ], +```php +'logentries' => [ + 'driver' => 'monolog', + 'handler' => Monolog\Handler\SyslogUdpHandler::class, + 'handler_with' => [ + 'host' => 'my.logentries.internal.datahubhost.company.com', + 'port' => '10000', ], +], +``` #### Monolog Formatters When using the `monolog` driver, the Monolog `LineFormatter` will be used as the default formatter. However, you may customize the type of formatter passed to the handler using the `formatter` and `formatter_with` configuration options: - 'browser' => [ - 'driver' => 'monolog', - 'handler' => Monolog\Handler\BrowserConsoleHandler::class, - 'formatter' => Monolog\Formatter\HtmlFormatter::class, - 'formatter_with' => [ - 'dateFormat' => 'Y-m-d', - ], +```php +'browser' => [ + 'driver' => 'monolog', + 'handler' => Monolog\Handler\BrowserConsoleHandler::class, + 'formatter' => Monolog\Formatter\HtmlFormatter::class, + 'formatter_with' => [ + 'dateFormat' => 'Y-m-d', ], +], +``` If you are using a Monolog handler that is capable of providing its own formatter, you may set the value of the `formatter` configuration option to `default`: - 'newrelic' => [ - 'driver' => 'monolog', - 'handler' => Monolog\Handler\NewRelicHandler::class, - 'formatter' => 'default', +```php +'newrelic' => [ + 'driver' => 'monolog', + 'handler' => Monolog\Handler\NewRelicHandler::class, + 'formatter' => 'default', +], +``` + + +#### Monolog Processors + +Monolog can also process messages before logging them. You can create your own processors or use the [existing processors offered by Monolog](https://github.com/Seldaek/monolog/tree/main/src/Monolog/Processor). + +If you would like to customize the processors for a `monolog` driver, add a `processors` configuration value to your channel's configuration: + +```php +'memory' => [ + 'driver' => 'monolog', + 'handler' => Monolog\Handler\StreamHandler::class, + 'handler_with' => [ + 'stream' => 'php://stderr', ], + 'processors' => [ + // Simple syntax... + Monolog\Processor\MemoryUsageProcessor::class, + + // With options... + [ + 'processor' => Monolog\Processor\PsrLogMessageProcessor::class, + 'with' => ['removeUsedContextFields' => true], + ], + ], +], +``` -### Creating Custom Channels Via Factories +### Creating Custom Channels via Factories If you would like to define an entirely custom channel in which you have full control over Monolog's instantiation and configuration, you may specify a `custom` driver type in your `config/logging.php` configuration file. Your configuration should include a `via` option that contains the name of the factory class which will be invoked to create the Monolog instance: - 'channels' => [ - 'example-custom-channel' => [ - 'driver' => 'custom', - 'via' => App\Logging\CreateCustomLogger::class, - ], +```php +'channels' => [ + 'example-custom-channel' => [ + 'driver' => 'custom', + 'via' => App\Logging\CreateCustomLogger::class, ], +], +``` Once you have configured the `custom` driver channel, you're ready to define the class that will create your Monolog instance. This class only needs a single `__invoke` method which should return the Monolog logger instance. The method will receive the channels configuration array as its only argument: - +## Tailing Log Messages Using Pail + +Often you may need to tail your application's logs in real time. For example, when debugging an issue or when monitoring your application's logs for specific types of errors. + +Laravel Pail is a package that allows you to easily dive into your Laravel application's log files directly from the command line. Unlike the standard `tail` command, Pail is designed to work with any log driver, including Sentry or Flare. In addition, Pail provides a set of useful filters to help you quickly find what you're looking for. + + + + +### Installation + +> [!WARNING] +> Laravel Pail requires the [PCNTL](https://www.php.net/manual/en/book.pcntl.php) PHP extension. + +To get started, install Pail into your project using the Composer package manager: + +```shell +composer require --dev laravel/pail +``` + + +### Usage + +To start tailing logs, run the `pail` command: + +```shell +php artisan pail +``` + +To increase the verbosity of the output and avoid truncation (…), use the `-v` option: + +```shell +php artisan pail -v +``` + +For maximum verbosity and to display exception stack traces, use the `-vv` option: + +```shell +php artisan pail -vv +``` + +To stop tailing logs, press `Ctrl+C` at any time. + + +### Filtering Logs + + +#### `--filter` + +You may use the `--filter` option to filter logs by their type, file, message, and stack trace content: + +```shell +php artisan pail --filter="QueryException" +``` + + +#### `--message` + +To filter logs by only their message, you may use the `--message` option: + +```shell +php artisan pail --message="User created" +``` + + +#### `--level` + +The `--level` option may be used to filter logs by their [log level](#log-levels): + +```shell +php artisan pail --level=error +``` + + +#### `--user` + +To only display logs that were written while a given user was authenticated, you may provide the user's ID to the `--user` option: + +```shell +php artisan pail --user=1 +``` diff --git a/mail.md b/mail.md index 9ced46384c8..fd32113157c 100644 --- a/mail.md +++ b/mail.md @@ -4,25 +4,31 @@ - [Configuration](#configuration) - [Driver Prerequisites](#driver-prerequisites) - [Failover Configuration](#failover-configuration) + - [Round Robin Configuration](#round-robin-configuration) - [Generating Mailables](#generating-mailables) - [Writing Mailables](#writing-mailables) - - [Configuring The Sender](#configuring-the-sender) - - [Configuring The View](#configuring-the-view) + - [Configuring the Sender](#configuring-the-sender) + - [Configuring the View](#configuring-the-view) - [View Data](#view-data) - [Attachments](#attachments) - [Inline Attachments](#inline-attachments) - - [Customizing The Symfony Message](#customizing-the-symfony-message) + - [Attachable Objects](#attachable-objects) + - [Headers](#headers) + - [Tags and Metadata](#tags-and-metadata) + - [Customizing the Symfony Message](#customizing-the-symfony-message) - [Markdown Mailables](#markdown-mailables) - [Generating Markdown Mailables](#generating-markdown-mailables) - [Writing Markdown Messages](#writing-markdown-messages) - - [Customizing The Components](#customizing-the-components) + - [Customizing the Components](#customizing-the-components) - [Sending Mail](#sending-mail) - [Queueing Mail](#queueing-mail) - [Rendering Mailables](#rendering-mailables) - - [Previewing Mailables In The Browser](#previewing-mailables-in-the-browser) + - [Previewing Mailables in the Browser](#previewing-mailables-in-the-browser) - [Localizing Mailables](#localizing-mailables) -- [Testing Mailables](#testing-mailables) -- [Mail & Local Development](#mail-and-local-development) +- [Testing](#testing-mailables) + - [Testing Mailable Content](#testing-mailable-content) + - [Testing Mailable Sending](#testing-mailable-sending) +- [Mail and Local Development](#mail-and-local-development) - [Events](#events) - [Custom Transports](#custom-transports) - [Additional Symfony Transports](#additional-symfony-transports) @@ -30,7 +36,7 @@ ## Introduction -Sending email doesn't have to be complicated. Laravel provides a clean, simple email API powered by the popular [Symfony Mailer](https://symfony.com/doc/6.0/mailer.html) component. Laravel and Symfony Mailer provide drivers for sending email via SMTP, Mailgun, Postmark, Amazon SES, and `sendmail`, allowing you to quickly get started sending mail through a local or cloud based service of your choice. +Sending email doesn't have to be complicated. Laravel provides a clean, simple email API powered by the popular [Symfony Mailer](https://symfony.com/doc/current/mailer.html) component. Laravel and Symfony Mailer provide drivers for sending email via SMTP, Mailgun, Postmark, Resend, Amazon SES, and `sendmail`, allowing you to quickly get started sending mail through a local or cloud-based service of your choice. ### Configuration @@ -42,7 +48,7 @@ Within your `mail` configuration file, you will find a `mailers` configuration a ### Driver / Transport Prerequisites -The API based drivers such as Mailgun and Postmark are often simpler and faster than sending mail via SMTP servers. Whenever possible, we recommend that you use one of these drivers. +The API based drivers such as Mailgun, Postmark, and Resend are often simpler and faster than sending mail via SMTP servers. Whenever possible, we recommend that you use one of these drivers. #### Mailgun Driver @@ -53,45 +59,93 @@ To use the Mailgun driver, install Symfony's Mailgun Mailer transport via Compos composer require symfony/mailgun-mailer symfony/http-client ``` -Next, set the `default` option in your application's `config/mail.php` configuration file to `mailgun`. After configuring your application's default mailer, verify that your `config/services.php` configuration file contains the following options: +Next, you will need to make two changes in your application's `config/mail.php` configuration file. First, set your default mailer to `mailgun`: - 'mailgun' => [ - 'domain' => env('MAILGUN_DOMAIN'), - 'secret' => env('MAILGUN_SECRET'), - ], +```php +'default' => env('MAIL_MAILER', 'mailgun'), +``` -If you are not using the United States [Mailgun region](https://documentation.mailgun.com/en/latest/api-intro.html#mailgun-regions), you may define your region's endpoint in the `services` configuration file: +Second, add the following configuration array to your array of `mailers`: - 'mailgun' => [ - 'domain' => env('MAILGUN_DOMAIN'), - 'secret' => env('MAILGUN_SECRET'), - 'endpoint' => env('MAILGUN_ENDPOINT', 'api.eu.mailgun.net'), - ], +```php +'mailgun' => [ + 'transport' => 'mailgun', + // 'client' => [ + // 'timeout' => 5, + // ], +], +``` + +After configuring your application's default mailer, add the following options to your `config/services.php` configuration file: + +```php +'mailgun' => [ + 'domain' => env('MAILGUN_DOMAIN'), + 'secret' => env('MAILGUN_SECRET'), + 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), + 'scheme' => 'https', +], +``` + +If you are not using the United States [Mailgun region](https://documentation.mailgun.com/docs/mailgun/api-reference/#mailgun-regions), you may define your region's endpoint in the `services` configuration file: + +```php +'mailgun' => [ + 'domain' => env('MAILGUN_DOMAIN'), + 'secret' => env('MAILGUN_SECRET'), + 'endpoint' => env('MAILGUN_ENDPOINT', 'api.eu.mailgun.net'), + 'scheme' => 'https', +], +``` #### Postmark Driver -To use the Postmark driver, install Symfony's Postmark Mailer transport via Composer: +To use the [Postmark](https://postmarkapp.com/) driver, install Symfony's Postmark Mailer transport via Composer: ```shell composer require symfony/postmark-mailer symfony/http-client ``` -Next, set the `default` option in your application's `config/mail.php` configuration file to `postmark`. After configuring your application's default mailer, verify that your `config/services.php` configuration file contains the following options: +Next, set the `default` option in your application's `config/mail.php` configuration file to `postmark`. After configuring your application's default mailer, ensure that your `config/services.php` configuration file contains the following options: - 'postmark' => [ - 'token' => env('POSTMARK_TOKEN'), - ], +```php +'postmark' => [ + 'token' => env('POSTMARK_TOKEN'), +], +``` If you would like to specify the Postmark message stream that should be used by a given mailer, you may add the `message_stream_id` configuration option to the mailer's configuration array. This configuration array can be found in your application's `config/mail.php` configuration file: - 'postmark' => [ - 'transport' => 'postmark', - 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'), - ], +```php +'postmark' => [ + 'transport' => 'postmark', + 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'), + // 'client' => [ + // 'timeout' => 5, + // ], +], +``` This way you are also able to set up multiple Postmark mailers with different message streams. + +#### Resend Driver + +To use the [Resend](https://resend.com/) driver, install Resend's PHP SDK via Composer: + +```shell +composer require resend/resend-php +``` + +Next, set the `default` option in your application's `config/mail.php` configuration file to `resend`. After configuring your application's default mailer, ensure that your `config/services.php` configuration file contains the following options: + +```php +'resend' => [ + 'key' => env('RESEND_KEY'), +], +``` + #### SES Driver @@ -103,58 +157,113 @@ composer require aws/aws-sdk-php Next, set the `default` option in your `config/mail.php` configuration file to `ses` and verify that your `config/services.php` configuration file contains the following options: - 'ses' => [ - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), - ], +```php +'ses' => [ + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), +], +``` To utilize AWS [temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) via a session token, you may add a `token` key to your application's SES configuration: - 'ses' => [ - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), - 'token' => env('AWS_SESSION_TOKEN'), - ], +```php +'ses' => [ + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'token' => env('AWS_SESSION_TOKEN'), +], +``` + +To interact with SES's [subscription management features](https://docs.aws.amazon.com/ses/latest/dg/sending-email-subscription-management.html), you may return the `X-Ses-List-Management-Options` header in the array returned by the [headers](#headers) method of a mail message: + +```php +/** + * Get the message headers. + */ +public function headers(): Headers +{ + return new Headers( + text: [ + 'X-Ses-List-Management-Options' => 'contactListName=MyContactList;topicName=MyTopic', + ], + ); +} +``` If you would like to define [additional options](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sesv2-2019-09-27.html#sendemail) that Laravel should pass to the AWS SDK's `SendEmail` method when sending an email, you may define an `options` array within your `ses` configuration: - 'ses' => [ - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), - 'options' => [ - 'ConfigurationSetName' => 'MyConfigurationSet', - 'EmailTags' => [ - ['Name' => 'foo', 'Value' => 'bar'], - ], +```php +'ses' => [ + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'options' => [ + 'ConfigurationSetName' => 'MyConfigurationSet', + 'EmailTags' => [ + ['Name' => 'foo', 'Value' => 'bar'], ], ], +], +``` ### Failover Configuration Sometimes, an external service you have configured to send your application's mail may be down. In these cases, it can be useful to define one or more backup mail delivery configurations that will be used in case your primary delivery driver is down. -To accomplish this, you should define a mailer within your application's `mail` configuration file that uses the `failover` transport. The configuration array for your application's `failover` mailer should contain an array of `mailers` that reference the order in which mail drivers should be chosen for delivery: +To accomplish this, you should define a mailer within your application's `mail` configuration file that uses the `failover` transport. The configuration array for your application's `failover` mailer should contain an array of `mailers` that reference the order in which configured mailers should be chosen for delivery: - 'mailers' => [ - 'failover' => [ - 'transport' => 'failover', - 'mailers' => [ - 'postmark', - 'mailgun', - 'sendmail', - ], +```php +'mailers' => [ + 'failover' => [ + 'transport' => 'failover', + 'mailers' => [ + 'postmark', + 'mailgun', + 'sendmail', ], - - // ... + 'retry_after' => 60, ], + // ... +], +``` + Once your failover mailer has been defined, you should set this mailer as the default mailer used by your application by specifying its name as the value of the `default` configuration key within your application's `mail` configuration file: - 'default' => env('MAIL_MAILER', 'failover'), +```php +'default' => env('MAIL_MAILER', 'failover'), +``` + + +### Round Robin Configuration + +The `roundrobin` transport allows you to distribute your mailing workload across multiple mailers. To get started, define a mailer within your application's `mail` configuration file that uses the `roundrobin` transport. The configuration array for your application's `roundrobin` mailer should contain an array of `mailers` that reference which configured mailers should be used for delivery: + +```php +'mailers' => [ + 'roundrobin' => [ + 'transport' => 'roundrobin', + 'mailers' => [ + 'ses', + 'postmark', + ], + 'retry_after' => 60, + ], + + // ... +], +``` + +Once your round robin mailer has been defined, you should set this mailer as the default mailer used by your application by specifying its name as the value of the `default` configuration key within your application's `mail` configuration file: + +```php +'default' => env('MAIL_MAILER', 'roundrobin'), +``` + +The round robin transport selects a random mailer from the list of configured mailers and then switches to the next available mailer for each subsequent email. In contrast to `failover` transport, which helps to achieve *[high availability](https://en.wikipedia.org/wiki/High_availability)*, the `roundrobin` transport provides *[load balancing](https://en.wikipedia.org/wiki/Load_balancing_(computing))*. ## Generating Mailables @@ -168,72 +277,113 @@ php artisan make:mail OrderShipped ## Writing Mailables -Once you have generated a mailable class, open it up so we can explore its contents. First, note that all of a mailable class' configuration is done in the `build` method. Within this method, you may call various methods such as `from`, `subject`, `view`, and `attach` to configure the email's presentation and delivery. +Once you have generated a mailable class, open it up so we can explore its contents. Mailable class configuration is done in several methods, including the `envelope`, `content`, and `attachments` methods. -> {tip} You may type-hint dependencies on the mailable's `build` method. The Laravel [service container](/docs/{{version}}/container) automatically injects these dependencies. +The `envelope` method returns an `Illuminate\Mail\Mailables\Envelope` object that defines the subject and, sometimes, the recipients of the message. The `content` method returns an `Illuminate\Mail\Mailables\Content` object that defines the [Blade template](/docs/{{version}}/blade) that will be used to generate the message content. -### Configuring The Sender +### Configuring the Sender - -#### Using The `from` Method + +#### Using the Envelope -First, let's explore configuring the sender of the email. Or, in other words, who the email is going to be "from". There are two ways to configure the sender. First, you may use the `from` method within your mailable class' `build` method: +First, let's explore configuring the sender of the email. Or, in other words, who the email is going to be "from". There are two ways to configure the sender. First, you may specify the "from" address on your message's envelope: - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->from('example@example.com', 'Example') - ->view('emails.orders.shipped'); - } +```php +use Illuminate\Mail\Mailables\Address; +use Illuminate\Mail\Mailables\Envelope; + +/** + * Get the message envelope. + */ +public function envelope(): Envelope +{ + return new Envelope( + from: new Address('jeffrey@example.com', 'Jeffrey Way'), + subject: 'Order Shipped', + ); +} +``` + +If you would like, you may also specify a `replyTo` address: + +```php +return new Envelope( + from: new Address('jeffrey@example.com', 'Jeffrey Way'), + replyTo: [ + new Address('taylor@example.com', 'Taylor Otwell'), + ], + subject: 'Order Shipped', +); +``` -#### Using A Global `from` Address +#### Using a Global `from` Address -However, if your application uses the same "from" address for all of its emails, it can become cumbersome to call the `from` method in each mailable class you generate. Instead, you may specify a global "from" address in your `config/mail.php` configuration file. This address will be used if no other "from" address is specified within the mailable class: +However, if your application uses the same "from" address for all of its emails, it can become cumbersome to add it to each mailable class you generate. Instead, you may specify a global "from" address in your `config/mail.php` configuration file. This address will be used if no other "from" address is specified within the mailable class: - 'from' => ['address' => 'example@example.com', 'name' => 'App Name'], +```php +'from' => [ + 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), + 'name' => env('MAIL_FROM_NAME', 'Example'), +], +``` In addition, you may define a global "reply_to" address within your `config/mail.php` configuration file: - 'reply_to' => ['address' => 'example@example.com', 'name' => 'App Name'], +```php +'reply_to' => [ + 'address' => 'example@example.com', + 'name' => 'App Name', +], +``` -### Configuring The View - -Within a mailable class' `build` method, you may use the `view` method to specify which template should be used when rendering the email's contents. Since each email typically uses a [Blade template](/docs/{{version}}/blade) to render its contents, you have the full power and convenience of the Blade templating engine when building your email's HTML: - - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped'); - } +### Configuring the View + +Within a mailable class's `content` method, you may define the `view`, or which template should be used when rendering the email's contents. Since each email typically uses a [Blade template](/docs/{{version}}/blade) to render its contents, you have the full power and convenience of the Blade templating engine when building your email's HTML: + +```php +/** + * Get the message content definition. + */ +public function content(): Content +{ + return new Content( + view: 'mail.orders.shipped', + ); +} +``` -> {tip} You may wish to create a `resources/views/emails` directory to house all of your email templates; however, you are free to place them wherever you wish within your `resources/views` directory. +> [!NOTE] +> You may wish to create a `resources/views/mail` directory to house all of your email templates; however, you are free to place them wherever you wish within your `resources/views` directory. #### Plain Text Emails -If you would like to define a plain-text version of your email, you may use the `text` method. Like the `view` method, the `text` method accepts a template name which will be used to render the contents of the email. You are free to define both an HTML and plain-text version of your message: +If you would like to define a plain-text version of your email, you may specify the plain-text template when creating the message's `Content` definition. Like the `view` parameter, the `text` parameter should be a template name which will be used to render the contents of the email. You are free to define both an HTML and plain-text version of your message: + +```php +/** + * Get the message content definition. + */ +public function content(): Content +{ + return new Content( + view: 'mail.orders.shipped', + text: 'mail.orders.shipped-text' + ); +} +``` + +For clarity, the `html` parameter may be used as an alias of the `view` parameter: - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped') - ->text('emails.orders.shipped_plain'); - } +```php +return new Content( + html: 'mail.orders.shipped', + text: 'mail.orders.shipped-text' +); +``` ### View Data @@ -241,206 +391,214 @@ If you would like to define a plain-text version of your email, you may use the #### Via Public Properties -Typically, you will want to pass some data to your view that you can utilize when rendering the email's HTML. There are two ways you may make data available to your view. First, any public property defined on your mailable class will automatically be made available to the view. So, for example, you may pass data into your mailable class' constructor and set that data to public properties defined on the class: +Typically, you will want to pass some data to your view that you can utilize when rendering the email's HTML. There are two ways you may make data available to your view. First, any public property defined on your mailable class will automatically be made available to the view. So, for example, you may pass data into your mailable class's constructor and set that data to public properties defined on the class: + +```php +order = $order; - } - - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped'); - } + return new Content( + view: 'mail.orders.shipped', + ); } +} +``` Once the data has been set to a public property, it will automatically be available in your view, so you may access it like you would access any other data in your Blade templates: -
- Price: {{ $order->price }} -
+```blade +
+ Price: {{ $order->price }} +
+``` + + +#### Via the `with` Parameter: - -#### Via The `with` Method: +If you would like to customize the format of your email's data before it is sent to the template, you may manually pass your data to the view via the `Content` definition's `with` parameter. Typically, you will still pass data via the mailable class's constructor; however, you should set this data to `protected` or `private` properties so the data is not automatically made available to the template: -If you would like to customize the format of your email's data before it is sent to the template, you may manually pass your data to the view via the `with` method. Typically, you will still pass data via the mailable class' constructor; however, you should set this data to `protected` or `private` properties so the data is not automatically made available to the template. Then, when calling the `with` method, pass an array of data that you wish to make available to the template: +```php +order = $order; - } - - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped') - ->with([ - 'orderName' => $this->order->name, - 'orderPrice' => $this->order->price, - ]); - } + return new Content( + view: 'mail.orders.shipped', + with: [ + 'orderName' => $this->order->name, + 'orderPrice' => $this->order->price, + ], + ); } +} +``` -Once the data has been passed to the `with` method, it will automatically be available in your view, so you may access it like you would access any other data in your Blade templates: +Once the data has been passed via the `with` parameter, it will automatically be available in your view, so you may access it like you would access any other data in your Blade templates: -
- Price: {{ $orderPrice }} -
+```blade +
+ Price: {{ $orderPrice }} +
+``` ### Attachments -To add attachments to an email, use the `attach` method within the mailable class' `build` method. The `attach` method accepts the full path to the file as its first argument: +To add attachments to an email, you will add attachments to the array returned by the message's `attachments` method. First, you may add an attachment by providing a file path to the `fromPath` method provided by the `Attachment` class: - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped') - ->attach('/path/to/file'); - } +```php +use Illuminate\Mail\Mailables\Attachment; -When attaching files to a message, you may also specify the display name and / or MIME type by passing an `array` as the second argument to the `attach` method: +/** + * Get the attachments for the message. + * + * @return array + */ +public function attachments(): array +{ + return [ + Attachment::fromPath('/path/to/file'), + ]; +} +``` - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped') - ->attach('/path/to/file', [ - 'as' => 'name.pdf', - 'mime' => 'application/pdf', - ]); - } +When attaching files to a message, you may also specify the display name and / or MIME type for the attachment using the `as` and `withMime` methods: + +```php +/** + * Get the attachments for the message. + * + * @return array + */ +public function attachments(): array +{ + return [ + Attachment::fromPath('/path/to/file') + ->as('name.pdf') + ->withMime('application/pdf'), + ]; +} +``` #### Attaching Files From Disk -If you have stored a file on one of your [filesystem disks](/docs/{{version}}/filesystem), you may attach it to the email using the `attachFromStorage` method: - - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped') - ->attachFromStorage('/path/to/file'); - } - -If necessary, you may specify the file's attachment name and additional options using the second and third arguments to the `attachFromStorage` method: - - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped') - ->attachFromStorage('/path/to/file', 'name.pdf', [ - 'mime' => 'application/pdf' - ]); - } +If you have stored a file on one of your [filesystem disks](/docs/{{version}}/filesystem), you may attach it to the email using the `fromStorage` attachment method: + +```php +/** + * Get the attachments for the message. + * + * @return array + */ +public function attachments(): array +{ + return [ + Attachment::fromStorage('/path/to/file'), + ]; +} +``` -The `attachFromStorageDisk` method may be used if you need to specify a storage disk other than your default disk: +Of course, you may also specify the attachment's name and MIME type: + +```php +/** + * Get the attachments for the message. + * + * @return array + */ +public function attachments(): array +{ + return [ + Attachment::fromStorage('/path/to/file') + ->as('name.pdf') + ->withMime('application/pdf'), + ]; +} +``` - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped') - ->attachFromStorageDisk('s3', '/path/to/file'); - } +The `fromStorageDisk` method may be used if you need to specify a storage disk other than your default disk: + +```php +/** + * Get the attachments for the message. + * + * @return array + */ +public function attachments(): array +{ + return [ + Attachment::fromStorageDisk('s3', '/path/to/file') + ->as('name.pdf') + ->withMime('application/pdf'), + ]; +} +``` #### Raw Data Attachments -The `attachData` method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The `attachData` method accepts the raw data bytes as its first argument, the name of the file as its second argument, and an array of options as its third argument: - - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->view('emails.orders.shipped') - ->attachData($this->pdf, 'name.pdf', [ - 'mime' => 'application/pdf', - ]); - } +The `fromData` attachment method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The `fromData` method accepts a closure which resolves the raw data bytes as well as the name that the attachment should be assigned: + +```php +/** + * Get the attachments for the message. + * + * @return array + */ +public function attachments(): array +{ + return [ + Attachment::fromData(fn () => $this->pdf, 'Report.pdf') + ->withMime('application/pdf'), + ]; +} +``` ### Inline Attachments @@ -455,7 +613,8 @@ Embedding inline images into your emails is typically cumbersome; however, Larav ``` -> {note} The `$message` variable is not available in plain-text message templates since plain-text messages do not utilize inline attachments. +> [!WARNING] +> The `$message` variable is not available in plain-text message templates since plain-text messages do not utilize inline attachments. #### Embedding Raw Data Attachments @@ -470,30 +629,150 @@ If you already have a raw image data string you wish to embed into an email temp ``` - -### Customizing The Symfony Message + +### Attachable Objects + +While attaching files to messages via simple string paths is often sufficient, in many cases the attachable entities within your application are represented by classes. For example, if your application is attaching a photo to a message, your application may also have a `Photo` model that represents that photo. When that is the case, wouldn't it be convenient to simply pass the `Photo` model to the `attach` method? Attachable objects allow you to do just that. -The `withSymfonyMessage` method of the `Mailable` base class allows you to register a closure which will be invoked with the Symfony Message instance before sending the message. This gives you an opportunity to deeply customize the message before it is delivered: +To get started, implement the `Illuminate\Contracts\Mail\Attachable` interface on the object that will be attachable to messages. This interface dictates that your class defines a `toMailAttachment` method that returns an `Illuminate\Mail\Attachment` instance: - use Symfony\Component\Mime\Email; - +```php +view('emails.orders.shipped'); + return Attachment::fromPath('/path/to/file'); + } +} +``` - $this->withSymfonyMessage(function (Email $message) { - $message->getHeaders()->addTextHeader( - 'Custom-Header', 'Header Value' - ); - }); +Once you have defined your attachable object, you may return an instance of that object from the `attachments` method when building an email message: + +```php +/** + * Get the attachments for the message. + * + * @return array + */ +public function attachments(): array +{ + return [$this->photo]; +} +``` - return $this; - } +Of course, attachment data may be stored on a remote file storage service such as Amazon S3. So, Laravel also allows you to generate attachment instances from data that is stored on one of your application's [filesystem disks](/docs/{{version}}/filesystem): + +```php +// Create an attachment from a file on your default disk... +return Attachment::fromStorage($this->path); + +// Create an attachment from a file on a specific disk... +return Attachment::fromStorageDisk('backblaze', $this->path); +``` + +In addition, you may create attachment instances via data that you have in memory. To accomplish this, provide a closure to the `fromData` method. The closure should return the raw data that represents the attachment: + +```php +return Attachment::fromData(fn () => $this->content, 'Photo Name'); +``` + +Laravel also provides additional methods that you may use to customize your attachments. For example, you may use the `as` and `withMime` methods to customize the file's name and MIME type: + +```php +return Attachment::fromPath('/path/to/file') + ->as('Photo Name') + ->withMime('image/jpeg'); +``` + + +### Headers + +Sometimes you may need to attach additional headers to the outgoing message. For instance, you may need to set a custom `Message-Id` or other arbitrary text headers. + +To accomplish this, define a `headers` method on your mailable. The `headers` method should return an `Illuminate\Mail\Mailables\Headers` instance. This class accepts `messageId`, `references`, and `text` parameters. Of course, you may provide only the parameters you need for your particular message: + +```php +use Illuminate\Mail\Mailables\Headers; + +/** + * Get the message headers. + */ +public function headers(): Headers +{ + return new Headers( + messageId: 'custom-message-id@example.com', + references: ['previous-message@example.com'], + text: [ + 'X-Custom-Header' => 'Custom Value', + ], + ); +} +``` + + +### Tags and Metadata + +Some third-party email providers such as Mailgun and Postmark support message "tags" and "metadata", which may be used to group and track emails sent by your application. You may add tags and metadata to an email message via your `Envelope` definition: + +```php +use Illuminate\Mail\Mailables\Envelope; + +/** + * Get the message envelope. + * + * @return \Illuminate\Mail\Mailables\Envelope + */ +public function envelope(): Envelope +{ + return new Envelope( + subject: 'Order Shipped', + tags: ['shipment'], + metadata: [ + 'order_id' => $this->order->id, + ], + ); +} +``` + +If your application is using the Mailgun driver, you may consult Mailgun's documentation for more information on [tags](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/#tags) and [metadata](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/#attaching-metadata-to-messages). Likewise, the Postmark documentation may also be consulted for more information on their support for [tags](https://postmarkapp.com/blog/tags-support-for-smtp) and [metadata](https://postmarkapp.com/support/article/1125-custom-metadata-faq). + +If your application is using Amazon SES to send emails, you should use the `metadata` method to attach [SES "tags"](https://docs.aws.amazon.com/ses/latest/APIReference/API_MessageTag.html) to the message. + + +### Customizing the Symfony Message + +Laravel's mail capabilities are powered by Symfony Mailer. Laravel allows you to register custom callbacks that will be invoked with the Symfony Message instance before sending the message. This gives you an opportunity to deeply customize the message before it is sent. To accomplish this, define a `using` parameter on your `Envelope` definition: + +```php +use Illuminate\Mail\Mailables\Envelope; +use Symfony\Component\Mime\Email; + +/** + * Get the message envelope. + */ +public function envelope(): Envelope +{ + return new Envelope( + subject: 'Order Shipped', + using: [ + function (Email $message) { + // ... + }, + ] + ); +} +``` ## Markdown Mailables @@ -506,23 +785,27 @@ Markdown mailable messages allow you to take advantage of the pre-built template To generate a mailable with a corresponding Markdown template, you may use the `--markdown` option of the `make:mail` Artisan command: ```shell -php artisan make:mail OrderShipped --markdown=emails.orders.shipped +php artisan make:mail OrderShipped --markdown=mail.orders.shipped ``` -Then, when configuring the mailable within its `build` method, call the `markdown` method instead of the `view` method. The `markdown` method accepts the name of the Markdown template and an optional array of data to make available to the template: +Then, when configuring the mailable `Content` definition within its `content` method, use the `markdown` parameter instead of the `view` parameter: - /** - * Build the message. - * - * @return $this - */ - public function build() - { - return $this->from('example@example.com') - ->markdown('emails.orders.shipped', [ - 'url' => $this->orderUrl, - ]); - } +```php +use Illuminate\Mail\Mailables\Content; + +/** + * Get the message content definition. + */ +public function content(): Content +{ + return new Content( + markdown: 'mail.orders.shipped', + with: [ + 'url' => $this->orderUrl, + ], + ); +} +``` ### Writing Markdown Messages @@ -530,21 +813,22 @@ Then, when configuring the mailable within its `build` method, call the `markdow Markdown mailables use a combination of Blade components and Markdown syntax which allow you to easily construct mail messages while leveraging Laravel's pre-built email UI components: ```blade -@component('mail::message') + # Order Shipped Your order has been shipped! -@component('mail::button', ['url' => $url]) + View Order -@endcomponent + Thanks,
{{ config('app.name') }} -@endcomponent +
``` -> {tip} Do not use excess indentation when writing Markdown emails. Per Markdown standards, Markdown parsers will render indented content as code blocks. +> [!NOTE] +> Do not use excess indentation when writing Markdown emails. Per Markdown standards, Markdown parsers will render indented content as code blocks. #### Button Component @@ -552,9 +836,9 @@ Thanks,
The button component renders a centered button link. The component accepts two arguments, a `url` and an optional `color`. Supported colors are `primary`, `success`, and `error`. You may add as many button components to a message as you wish: ```blade -@component('mail::button', ['url' => $url, 'color' => 'success']) + View Order -@endcomponent + ``` @@ -563,9 +847,9 @@ View Order The panel component renders the given block of text in a panel that has a slightly different background color than the rest of the message. This allows you to draw attention to a given block of text: ```blade -@component('mail::panel') + This is the panel content. -@endcomponent + ``` @@ -574,16 +858,16 @@ This is the panel content. The table component allows you to transform a Markdown table into an HTML table. The component accepts the Markdown table as its content. Table column alignment is supported using the default Markdown table alignment syntax: ```blade -@component('mail::table') -| Laravel | Table | Example | -| ------------- |:-------------:| --------:| -| Col 2 is | Centered | $10 | -| Col 3 is | Right-Aligned | $20 | -@endcomponent + +| Laravel | Table | Example | +| ------------- | :-----------: | ------------: | +| Col 2 is | Centered | $10 | +| Col 3 is | Right-Aligned | $20 | + ``` -### Customizing The Components +### Customizing the Components You may export all of the Markdown mail components to your own application for customization. To export the components, use the `vendor:publish` Artisan command to publish the `laravel-mail` asset tag: @@ -594,7 +878,7 @@ php artisan vendor:publish --tag=laravel-mail This command will publish the Markdown mail components to the `resources/views/vendor/mail` directory. The `mail` directory will contain an `html` and a `text` directory, each containing their respective representations of every available component. You are free to customize these components however you like. -#### Customizing The CSS +#### Customizing the CSS After exporting the components, the `resources/views/vendor/mail/html/themes` directory will contain a `default.css` file. You may customize the CSS in this file and your styles will automatically be converted to inline CSS styles within the HTML representations of your Markdown mail messages. @@ -607,71 +891,80 @@ To customize the theme for an individual mailable, you may set the `$theme` prop To send a message, use the `to` method on the `Mail` [facade](/docs/{{version}}/facades). The `to` method accepts an email address, a user instance, or a collection of users. If you pass an object or collection of objects, the mailer will automatically use their `email` and `name` properties when determining the email's recipients, so make sure these attributes are available on your objects. Once you have specified your recipients, you may pass an instance of your mailable class to the `send` method: - order_id); - - // Ship the order... - - Mail::to($request->user())->send(new OrderShipped($order)); - } + $order = Order::findOrFail($request->order_id); + + // Ship the order... + + Mail::to($request->user())->send(new OrderShipped($order)); + + return redirect('/orders'); } +} +``` You are not limited to just specifying the "to" recipients when sending a message. You are free to set "to", "cc", and "bcc" recipients by chaining their respective methods together: - Mail::to($request->user()) - ->cc($moreUsers) - ->bcc($evenMoreUsers) - ->send(new OrderShipped($order)); +```php +Mail::to($request->user()) + ->cc($moreUsers) + ->bcc($evenMoreUsers) + ->send(new OrderShipped($order)); +``` #### Looping Over Recipients Occasionally, you may need to send a mailable to a list of recipients by iterating over an array of recipients / email addresses. However, since the `to` method appends email addresses to the mailable's list of recipients, each iteration through the loop will send another email to every previous recipient. Therefore, you should always re-create the mailable instance for each recipient: - foreach (['taylor@example.com', 'dries@example.com'] as $recipient) { - Mail::to($recipient)->send(new OrderShipped($order)); - } +```php +foreach (['taylor@example.com', 'dries@example.com'] as $recipient) { + Mail::to($recipient)->send(new OrderShipped($order)); +} +``` -#### Sending Mail Via A Specific Mailer +#### Sending Mail via a Specific Mailer By default, Laravel will send email using the mailer configured as the `default` mailer in your application's `mail` configuration file. However, you may use the `mailer` method to send a message using a specific mailer configuration: - Mail::mailer('postmark') - ->to($request->user()) - ->send(new OrderShipped($order)); +```php +Mail::mailer('postmark') + ->to($request->user()) + ->send(new OrderShipped($order)); +``` ### Queueing Mail -#### Queueing A Mail Message +#### Queueing a Mail Message Since sending email messages can negatively impact the response time of your application, many developers choose to queue email messages for background sending. Laravel makes this easy using its built-in [unified queue API](/docs/{{version}}/queues). To queue a mail message, use the `queue` method on the `Mail` facade after specifying the message's recipients: - Mail::to($request->user()) - ->cc($moreUsers) - ->bcc($evenMoreUsers) - ->queue(new OrderShipped($order)); +```php +Mail::to($request->user()) + ->cc($moreUsers) + ->bcc($evenMoreUsers) + ->queue(new OrderShipped($order)); +``` This method will automatically take care of pushing a job onto the queue so the message is sent in the background. You will need to [configure your queues](/docs/{{version}}/queues) before using this feature. @@ -680,100 +973,140 @@ This method will automatically take care of pushing a job onto the queue so the If you wish to delay the delivery of a queued email message, you may use the `later` method. As its first argument, the `later` method accepts a `DateTime` instance indicating when the message should be sent: - Mail::to($request->user()) - ->cc($moreUsers) - ->bcc($evenMoreUsers) - ->later(now()->addMinutes(10), new OrderShipped($order)); +```php +Mail::to($request->user()) + ->cc($moreUsers) + ->bcc($evenMoreUsers) + ->later(now()->addMinutes(10), new OrderShipped($order)); +``` -#### Pushing To Specific Queues +#### Pushing to Specific Queues Since all mailable classes generated using the `make:mail` command make use of the `Illuminate\Bus\Queueable` trait, you may call the `onQueue` and `onConnection` methods on any mailable class instance, allowing you to specify the connection and queue name for the message: - $message = (new OrderShipped($order)) - ->onConnection('sqs') - ->onQueue('emails'); +```php +$message = (new OrderShipped($order)) + ->onConnection('sqs') + ->onQueue('emails'); - Mail::to($request->user()) - ->cc($moreUsers) - ->bcc($evenMoreUsers) - ->queue($message); +Mail::to($request->user()) + ->cc($moreUsers) + ->bcc($evenMoreUsers) + ->queue($message); +``` -#### Queueing By Default +#### Queueing by Default If you have mailable classes that you want to always be queued, you may implement the `ShouldQueue` contract on the class. Now, even if you call the `send` method when mailing, the mailable will still be queued since it implements the contract: - use Illuminate\Contracts\Queue\ShouldQueue; +```php +use Illuminate\Contracts\Queue\ShouldQueue; - class OrderShipped extends Mailable implements ShouldQueue - { - // - } +class OrderShipped extends Mailable implements ShouldQueue +{ + // ... +} +``` -#### Queued Mailables & Database Transactions +#### Queued Mailables and Database Transactions When queued mailables are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your mailable depends on these models, unexpected errors can occur when the job that sends the queued mailable is processed. If your queue connection's `after_commit` configuration option is set to `false`, you may still indicate that a particular queued mailable should be dispatched after all open database transactions have been committed by calling the `afterCommit` method when sending the mail message: - Mail::to($request->user())->send( - (new OrderShipped($order))->afterCommit() - ); +```php +Mail::to($request->user())->send( + (new OrderShipped($order))->afterCommit() +); +``` Alternatively, you may call the `afterCommit` method from your mailable's constructor: - afterCommit(); - } + $this->afterCommit(); } +} +``` + +> [!NOTE] +> To learn more about working around these issues, please review the documentation regarding [queued jobs and database transactions](/docs/{{version}}/queues#jobs-and-database-transactions). + + +#### Queued Email Failures -> {tip} To learn more about working around these issues, please review the documentation regarding [queued jobs and database transactions](/docs/{{version}}/queues#jobs-and-database-transactions). +When a queued email fails, the `failed` method on the queued mailable class will be invoked if it has been defined. The `Throwable` instance that caused the queued email to fail will be passed to the `failed` method: + +```php + ## Rendering Mailables Sometimes you may wish to capture the HTML content of a mailable without sending it. To accomplish this, you may call the `render` method of the mailable. This method will return the evaluated HTML content of the mailable as a string: - use App\Mail\InvoicePaid; - use App\Models\Invoice; +```php +use App\Mail\InvoicePaid; +use App\Models\Invoice; - $invoice = Invoice::find(1); +$invoice = Invoice::find(1); - return (new InvoicePaid($invoice))->render(); +return (new InvoicePaid($invoice))->render(); +``` -### Previewing Mailables In The Browser +### Previewing Mailables in the Browser When designing a mailable's template, it is convenient to quickly preview the rendered mailable in your browser like a typical Blade template. For this reason, Laravel allows you to return any mailable directly from a route closure or controller. When a mailable is returned, it will be rendered and displayed in the browser, allowing you to quickly preview its design without needing to send it to an actual email address: - Route::get('/mailable', function () { - $invoice = App\Models\Invoice::find(1); - - return new App\Mail\InvoicePaid($invoice); - }); +```php +Route::get('/mailable', function () { + $invoice = App\Models\Invoice::find(1); -> {note} [Inline attachments](#inline-attachments) will not be rendered when a mailable is previewed in your browser. To preview these mailables, you should send them to an email testing application such as [MailHog](https://github.com/mailhog/MailHog) or [HELO](https://usehelo.com). + return new App\Mail\InvoicePaid($invoice); +}); +``` ## Localizing Mailables @@ -782,65 +1115,274 @@ Laravel allows you to send mailables in a locale other than the request's curren To accomplish this, the `Mail` facade offers a `locale` method to set the desired language. The application will change into this locale when the mailable's template is being evaluated and then revert back to the previous locale when evaluation is complete: - Mail::to($request->user())->locale('es')->send( - new OrderShipped($order) - ); +```php +Mail::to($request->user())->locale('es')->send( + new OrderShipped($order) +); +``` -### User Preferred Locales +#### User Preferred Locales Sometimes, applications store each user's preferred locale. By implementing the `HasLocalePreference` contract on one or more of your models, you may instruct Laravel to use this stored locale when sending mail: - use Illuminate\Contracts\Translation\HasLocalePreference; +```php +use Illuminate\Contracts\Translation\HasLocalePreference; - class User extends Model implements HasLocalePreference +class User extends Model implements HasLocalePreference +{ + /** + * Get the user's preferred locale. + */ + public function preferredLocale(): string { - /** - * Get the user's preferred locale. - * - * @return string - */ - public function preferredLocale() - { - return $this->locale; - } + return $this->locale; } +} +``` Once you have implemented the interface, Laravel will automatically use the preferred locale when sending mailables and notifications to the model. Therefore, there is no need to call the `locale` method when using this interface: - Mail::to($request->user())->send(new OrderShipped($order)); +```php +Mail::to($request->user())->send(new OrderShipped($order)); +``` -## Testing Mailables +## Testing + + +### Testing Mailable Content + +Laravel provides a variety of methods for inspecting your mailable's structure. In addition, Laravel provides several convenient methods for testing that your mailable contains the content that you expect: + +```php tab=Pest +use App\Mail\InvoicePaid; +use App\Models\User; + +test('mailable content', function () { + $user = User::factory()->create(); + + $mailable = new InvoicePaid($user); + + $mailable->assertFrom('jeffrey@example.com'); + $mailable->assertTo('taylor@example.com'); + $mailable->assertHasCc('abigail@example.com'); + $mailable->assertHasBcc('victoria@example.com'); + $mailable->assertHasReplyTo('tyler@example.com'); + $mailable->assertHasSubject('Invoice Paid'); + $mailable->assertHasTag('example-tag'); + $mailable->assertHasMetadata('key', 'value'); + + $mailable->assertSeeInHtml($user->email); + $mailable->assertDontSeeInHtml('Invoice Not Paid'); + $mailable->assertSeeInOrderInHtml(['Invoice Paid', 'Thanks']); + + $mailable->assertSeeInText($user->email); + $mailable->assertDontSeeInText('Invoice Not Paid'); + $mailable->assertSeeInOrderInText(['Invoice Paid', 'Thanks']); + + $mailable->assertHasAttachment('/path/to/file'); + $mailable->assertHasAttachment(Attachment::fromPath('/path/to/file')); + $mailable->assertHasAttachedData($pdfData, 'name.pdf', ['mime' => 'application/pdf']); + $mailable->assertHasAttachmentFromStorage('/path/to/file', 'name.pdf', ['mime' => 'application/pdf']); + $mailable->assertHasAttachmentFromStorageDisk('s3', '/path/to/file', 'name.pdf', ['mime' => 'application/pdf']); +}); +``` + +```php tab=PHPUnit +use App\Mail\InvoicePaid; +use App\Models\User; + +public function test_mailable_content(): void +{ + $user = User::factory()->create(); + + $mailable = new InvoicePaid($user); + + $mailable->assertFrom('jeffrey@example.com'); + $mailable->assertTo('taylor@example.com'); + $mailable->assertHasCc('abigail@example.com'); + $mailable->assertHasBcc('victoria@example.com'); + $mailable->assertHasReplyTo('tyler@example.com'); + $mailable->assertHasSubject('Invoice Paid'); + $mailable->assertHasTag('example-tag'); + $mailable->assertHasMetadata('key', 'value'); + + $mailable->assertSeeInHtml($user->email); + $mailable->assertDontSeeInHtml('Invoice Not Paid'); + $mailable->assertSeeInOrderInHtml(['Invoice Paid', 'Thanks']); + + $mailable->assertSeeInText($user->email); + $mailable->assertDontSeeInText('Invoice Not Paid'); + $mailable->assertSeeInOrderInText(['Invoice Paid', 'Thanks']); + + $mailable->assertHasAttachment('/path/to/file'); + $mailable->assertHasAttachment(Attachment::fromPath('/path/to/file')); + $mailable->assertHasAttachedData($pdfData, 'name.pdf', ['mime' => 'application/pdf']); + $mailable->assertHasAttachmentFromStorage('/path/to/file', 'name.pdf', ['mime' => 'application/pdf']); + $mailable->assertHasAttachmentFromStorageDisk('s3', '/path/to/file', 'name.pdf', ['mime' => 'application/pdf']); +} +``` + +As you might expect, the "HTML" assertions assert that the HTML version of your mailable contains a given string, while the "text" assertions assert that the plain-text version of your mailable contains a given string. + + +### Testing Mailable Sending + +We suggest testing the content of your mailables separately from your tests that assert that a given mailable was "sent" to a specific user. Typically, the content of mailables is not relevant to the code you are testing, and it is sufficient to simply assert that Laravel was instructed to send a given mailable. + +You may use the `Mail` facade's `fake` method to prevent mail from being sent. After calling the `Mail` facade's `fake` method, you may then assert that mailables were instructed to be sent to users and even inspect the data the mailables received: + +```php tab=Pest +create(); + Mail::fake(); + + // Perform order shipping... - $mailable = new InvoicePaid($user); + // Assert that no mailables were sent... + Mail::assertNothingSent(); - $mailable->assertSeeInHtml($user->email); - $mailable->assertSeeInHtml('Invoice Paid'); - $mailable->assertSeeInOrderInHtml(['Invoice Paid', 'Thanks']); + // Assert that a mailable was sent... + Mail::assertSent(OrderShipped::class); - $mailable->assertSeeInText($user->email); - $mailable->assertSeeInOrderInText(['Invoice Paid', 'Thanks']); + // Assert a mailable was sent twice... + Mail::assertSent(OrderShipped::class, 2); + + // Assert a mailable was sent to an email address... + Mail::assertSent(OrderShipped::class, 'example@laravel.com'); + + // Assert a mailable was sent to multiple email addresses... + Mail::assertSent(OrderShipped::class, ['example@laravel.com', '...']); + + // Assert a mailable was not sent... + Mail::assertNotSent(AnotherMailable::class); + + // Assert a mailable was sent twice... + Mail::assertSentTimes(OrderShipped::class, 2); + + // Assert 3 total mailables were sent... + Mail::assertSentCount(3); } +} +``` - -#### Testing Mailable Sending +If you are queueing mailables for delivery in the background, you should use the `assertQueued` method instead of `assertSent`: -We suggest testing the content of your mailables separately from your tests that assert that a given mailable was "sent" to a specific user. To learn how to test that mailables were sent, check out our documentation on the [Mail fake](/docs/{{version}}/mocking#mail-fake). +```php +Mail::assertQueued(OrderShipped::class); +Mail::assertNotQueued(OrderShipped::class); +Mail::assertNothingQueued(); +Mail::assertQueuedCount(3); +``` + +You may pass a closure to the `assertSent`, `assertNotSent`, `assertQueued`, or `assertNotQueued` methods in order to assert that a mailable was sent that passes a given "truth test". If at least one mailable was sent that passes the given truth test then the assertion will be successful: + +```php +Mail::assertSent(function (OrderShipped $mail) use ($order) { + return $mail->order->id === $order->id; +}); +``` + +When calling the `Mail` facade's assertion methods, the mailable instance accepted by the provided closure exposes helpful methods for examining the mailable: + +```php +Mail::assertSent(OrderShipped::class, function (OrderShipped $mail) use ($user) { + return $mail->hasTo($user->email) && + $mail->hasCc('...') && + $mail->hasBcc('...') && + $mail->hasReplyTo('...') && + $mail->hasFrom('...') && + $mail->hasSubject('...') && + $mail->usesMailer('ses'); +}); +``` + +The mailable instance also includes several helpful methods for examining the attachments on a mailable: + +```php +use Illuminate\Mail\Mailables\Attachment; + +Mail::assertSent(OrderShipped::class, function (OrderShipped $mail) { + return $mail->hasAttachment( + Attachment::fromPath('/path/to/file') + ->as('name.pdf') + ->withMime('application/pdf') + ); +}); + +Mail::assertSent(OrderShipped::class, function (OrderShipped $mail) { + return $mail->hasAttachment( + Attachment::fromStorageDisk('s3', '/path/to/file') + ); +}); + +Mail::assertSent(OrderShipped::class, function (OrderShipped $mail) use ($pdfData) { + return $mail->hasAttachment( + Attachment::fromData(fn () => $pdfData, 'name.pdf') + ); +}); +``` + +You may have noticed that there are two methods for asserting that mail was not sent: `assertNotSent` and `assertNotQueued`. Sometimes you may wish to assert that no mail was sent **or** queued. To accomplish this, you may use the `assertNothingOutgoing` and `assertNotOutgoing` methods: + +```php +Mail::assertNothingOutgoing(); + +Mail::assertNotOutgoing(function (OrderShipped $mail) use ($order) { + return $mail->order->id === $order->id; +}); +``` -## Mail & Local Development +## Mail and Local Development When developing an application that sends email, you probably don't want to actually send emails to live email addresses. Laravel provides several ways to "disable" the actual sending of emails during local development. @@ -850,167 +1392,186 @@ When developing an application that sends email, you probably don't want to actu Instead of sending your emails, the `log` mail driver will write all email messages to your log files for inspection. Typically, this driver would only be used during local development. For more information on configuring your application per environment, check out the [configuration documentation](/docs/{{version}}/configuration#environment-configuration). -#### HELO / Mailtrap / MailHog +#### HELO / Mailtrap / Mailpit Alternatively, you may use a service like [HELO](https://usehelo.com) or [Mailtrap](https://mailtrap.io) and the `smtp` driver to send your email messages to a "dummy" mailbox where you may view them in a true email client. This approach has the benefit of allowing you to actually inspect the final emails in Mailtrap's message viewer. -If you are using [Laravel Sail](/docs/{{version}}/sail), you may preview your messages using [MailHog](https://github.com/mailhog/MailHog). When Sail is running, you may access the MailHog interface at: `http://localhost:8025`. +If you are using [Laravel Sail](/docs/{{version}}/sail), you may preview your messages using [Mailpit](https://github.com/axllent/mailpit). When Sail is running, you may access the Mailpit interface at: `http://localhost:8025`. -#### Using A Global `to` Address +#### Using a Global `to` Address Finally, you may specify a global "to" address by invoking the `alwaysTo` method offered by the `Mail` facade. Typically, this method should be called from the `boot` method of one of your application's service providers: - use Illuminate\Support\Facades\Mail; +```php +use Illuminate\Support\Facades\Mail; - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - if ($this->app->environment('local')) { - Mail::alwaysTo('taylor@example.com'); - } +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + if ($this->app->environment('local')) { + Mail::alwaysTo('taylor@example.com'); } +} +``` + +When using the `alwaysTo` method, any additional "cc" or "bcc" addresses on mail messages will be removed. ## Events -Laravel fires two events during the process of sending mail messages. The `MessageSending` event is fired prior to a message being sent, while the `MessageSent` event is fired after a message has been sent. Remember, these events are fired when the mail is being *sent*, not when it is queued. You may register event listeners for this event in your `App\Providers\EventServiceProvider` service provider: +Laravel dispatches two events while sending mail messages. The `MessageSending` event is dispatched prior to a message being sent, while the `MessageSent` event is dispatched after a message has been sent. Remember, these events are dispatched when the mail is being *sent*, not when it is queued. You may create [event listeners](/docs/{{version}}/events) for these events within your application: + +```php +use Illuminate\Mail\Events\MessageSending; +// use Illuminate\Mail\Events\MessageSent; +class LogMessage +{ /** - * The event listener mappings for the application. - * - * @var array + * Handle the event. */ - protected $listen = [ - 'Illuminate\Mail\Events\MessageSending' => [ - 'App\Listeners\LogSendingMessage', - ], - 'Illuminate\Mail\Events\MessageSent' => [ - 'App\Listeners\LogSentMessage', - ], - ]; + public function handle(MessageSending $event): void + { + // ... + } +} +``` ## Custom Transports -Laravel includes a variety of mail transports; however, you may wish to write your own transports to deliver email via other services that Laravel does not support out of the box. To get started, define a class that extends the `Symfony\Component\Mailer\Transport\AbstractTransport` class. Then, implement the `doSend` and `__toString()` methods on your transport: +Laravel includes a variety of mail transports; however, you may wish to write your own transports to deliver email via other services that Laravel does not support out of the box. To get started, define a class that extends the `Symfony\Component\Mailer\Transport\AbstractTransport` class. Then, implement the `doSend` and `__toString` methods on your transport: - use MailchimpTransactional\ApiClient; - use Symfony\Component\Mailer\SentMessage; - use Symfony\Component\Mailer\Transport\AbstractTransport; - use Symfony\Component\Mime\MessageConverter; +```php +client = $client - } - - /** - * {@inheritDoc} - */ - protected function doSend(SentMessage $message): void - { - $email = MessageConverter::toEmail($message->getOriginalMessage()); - - $this->client->messages->send(['message' => [ - 'from_email' => $email->getFrom(), - 'to' => collect($email->getTo())->map(function ($email) { - return ['email' => $email->getAddress(), 'type' => 'to']; - })->all(), - 'subject' => $email->getSubject(), - 'text' => $email->getTextBody(), - ]]); - } - - /** - * Get the string representation of the transport. - * - * @return string - */ - public function __toString(): string - { - return 'mailchimp'; - } - } +namespace App\Mail; + +use MailchimpTransactional\ApiClient; +use Symfony\Component\Mailer\SentMessage; +use Symfony\Component\Mailer\Transport\AbstractTransport; +use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\MessageConverter; -Once you've defined your custom transport, you may register it via the `extend` method provided by the `Mail` facade. Typically, this should be done within the `boot` method of your application's `AppServiceProvider` service provider. A `$config` argument will be passed to the closure provided to the `extend` method. This argument will contain the configuration array defined for the mailer in the application's `config/mail.php` configuration file: +class MailchimpTransport extends AbstractTransport +{ + /** + * Create a new Mailchimp transport instance. + */ + public function __construct( + protected ApiClient $client, + ) { + parent::__construct(); + } - use App\Mail\MailchimpTransport; - use Illuminate\Support\Facades\Mail; + /** + * {@inheritDoc} + */ + protected function doSend(SentMessage $message): void + { + $email = MessageConverter::toEmail($message->getOriginalMessage()); + + $this->client->messages->send(['message' => [ + 'from_email' => $email->getFrom(), + 'to' => collect($email->getTo())->map(function (Address $email) { + return ['email' => $email->getAddress(), 'type' => 'to']; + })->all(), + 'subject' => $email->getSubject(), + 'text' => $email->getTextBody(), + ]]); + } /** - * Bootstrap any application services. - * - * @return void + * Get the string representation of the transport. */ - public function boot() + public function __toString(): string { - Mail::extend('mailchimp', function (array $config = []) { - return new MailchimpTransport(...); - }) + return 'mailchimp'; } +} +``` + +Once you've defined your custom transport, you may register it via the `extend` method provided by the `Mail` facade. Typically, this should be done within the `boot` method of your application's `AppServiceProvider`. A `$config` argument will be passed to the closure provided to the `extend` method. This argument will contain the configuration array defined for the mailer in the application's `config/mail.php` configuration file: + +```php +use App\Mail\MailchimpTransport; +use Illuminate\Support\Facades\Mail; +use MailchimpTransactional\ApiClient; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Mail::extend('mailchimp', function (array $config = []) { + $client = new ApiClient; + + $client->setApiKey($config['key']); + + return new MailchimpTransport($client); + }); +} +``` Once your custom transport has been defined and registered, you may create a mailer definition within your application's `config/mail.php` configuration file that utilizes the new transport: - 'mailchimp' => [ - 'transport' => 'mailchimp', - // ... - ], +```php +'mailchimp' => [ + 'transport' => 'mailchimp', + 'key' => env('MAILCHIMP_API_KEY'), + // ... +], +``` ### Additional Symfony Transports -Laravel includes support for some existing Symfony maintained mail transports like Mailgun and Postmark. However, you may wish to extend Laravel with support for additional Symfony maintained transports. You can do so by requiring the necessary Symfony mailer via Composer and registering the transport with Laravel. For example, you may install and register the "Sendinblue" Symfony mailer: +Laravel includes support for some existing Symfony maintained mail transports like Mailgun and Postmark. However, you may wish to extend Laravel with support for additional Symfony maintained transports. You can do so by requiring the necessary Symfony mailer via Composer and registering the transport with Laravel. For example, you may install and register the "Brevo" (formerly "Sendinblue") Symfony mailer: -```none -composer require symfony/sendinblue-mailer +```shell +composer require symfony/brevo-mailer symfony/http-client ``` -Once the Sendinblue mailer package has been installed, you may add an entry for your Sendinblue API credentials to your application's `services` configuration file: +Once the Brevo mailer package has been installed, you may add an entry for your Brevo API credentials to your application's `services` configuration file: - 'sendinblue' => [ - 'key' => 'your-api-key', - ], +```php +'brevo' => [ + 'key' => env('BREVO_API_KEY'), +], +``` -Finally, you may use the `Mail` facade's `extend` method to register the transport with Laravel. Typically, this should be done within the `boot` method of a service provider: +Next, you may use the `Mail` facade's `extend` method to register the transport with Laravel. Typically, this should be done within the `boot` method of a service provider: + +```php +use Illuminate\Support\Facades\Mail; +use Symfony\Component\Mailer\Bridge\Brevo\Transport\BrevoTransportFactory; +use Symfony\Component\Mailer\Transport\Dsn; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Mail::extend('brevo', function () { + return (new BrevoTransportFactory)->create( + new Dsn( + 'brevo+api', + 'default', + config('services.brevo.key') + ) + ); + }); +} +``` - use Illuminate\Support\Facades\Mail; - use Symfony\Component\Mailer\Bridge\Sendinblue\Transport\SendinblueTransportFactory; - use Symfony\Component\Mailer\Transport\Dsn; +Once your transport has been registered, you may create a mailer definition within your application's `config/mail.php` configuration file that utilizes the new transport: - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - Mail::extend('sendinblue', function () { - return (new SendinblueTransportFactory)->create( - new Dsn( - 'sendinblue+api', - 'default', - config('services.sendinblue.key') - ) - ); - }); - } +```php +'brevo' => [ + 'transport' => 'brevo', + // ... +], +``` diff --git a/mcp.md b/mcp.md new file mode 100644 index 00000000000..a3940f03095 --- /dev/null +++ b/mcp.md @@ -0,0 +1,1359 @@ +# Laravel MCP + +- [Introduction](#introduction) +- [Installation](#installation) + - [Publishing Routes](#publishing-routes) +- [Creating Servers](#creating-servers) + - [Server Registration](#server-registration) + - [Web Servers](#web-servers) + - [Local Servers](#local-servers) +- [Tools](#tools) + - [Creating Tools](#creating-tools) + - [Tool Input Schemas](#tool-input-schemas) + - [Validating Tool Arguments](#validating-tool-arguments) + - [Tool Dependency Injection](#tool-dependency-injection) + - [Tool Annotations](#tool-annotations) + - [Conditional Tool Registration](#conditional-tool-registration) + - [Tool Responses](#tool-responses) +- [Prompts](#prompts) + - [Creating Prompts](#creating-prompts) + - [Prompt Arguments](#prompt-arguments) + - [Validating Prompt Arguments](#validating-prompt-arguments) + - [Prompt Dependency Injection](#prompt-dependency-injection) + - [Conditional Prompt Registration](#conditional-prompt-registration) + - [Prompt Responses](#prompt-responses) +- [Resources](#resources) + - [Creating Resources](#creating-resources) + - [Resource URI and MIME Type](#resource-uri-and-mime-type) + - [Resource Request](#resource-request) + - [Resource Dependency Injection](#resource-dependency-injection) + - [Conditional Resource Registration](#conditional-resource-registration) + - [Resource Responses](#resource-responses) +- [Authentication](#authentication) + - [OAuth 2.1](#oauth) + - [Sanctum](#sanctum) +- [Authorization](#authorization) +- [Testing Servers](#testing-servers) + - [MCP Inspector](#mcp-inspector) + - [Unit Tests](#unit-tests) + + +## Introduction + +[Laravel MCP](https://github.com/laravel/mcp) provides a simple and elegant way for AI clients to interact with your Laravel application through the [Model Context Protocol](https://modelcontextprotocol.io/docs/getting-started/intro). It offers an expressive, fluent interface for defining servers, tools, resources, and prompts that enable AI-powered interactions with your application. + + +## Installation + +To get started, install Laravel MCP into your project using the Composer package manager: + +```shell +composer require laravel/mcp +``` + + +### Publishing Routes + +After installing Laravel MCP, execute the `vendor:publish` Artisan command to publish the `routes/ai.php` file where you will define your MCP servers: + +```shell +php artisan vendor:publish --tag=ai-routes +``` + +This command creates the `routes/ai.php` file in your application's `routes` directory, which you will use to register your MCP servers. + + +## Creating Servers + +You can create an MCP server using the `make:mcp-server` Artisan command. Servers act as the central communication point that exposes MCP capabilities like tools, resources, and prompts to AI clients: + +```shell +php artisan make:mcp-server WeatherServer +``` + +This command will create a new server class in the `app/Mcp/Servers` directory. The generated server class extends Laravel MCP's base `Laravel\Mcp\Server` class and provides properties for registering tools, resources, and prompts: + +```php +> + */ + protected array $tools = [ + // GetCurrentWeatherTool::class, + ]; + + /** + * The resources registered with this MCP server. + * + * @var array> + */ + protected array $resources = [ + // WeatherGuidelinesResource::class, + ]; + + /** + * The prompts registered with this MCP server. + * + * @var array> + */ + protected array $prompts = [ + // DescribeWeatherPrompt::class, + ]; +} +``` + + +### Server Registration + +Once you've created a server, you must register it in your `routes/ai.php` file to make it accessible. Laravel MCP provides two methods for registering servers: `web` for HTTP-accessible servers and `local` for command-line servers. + + +### Web Servers + +Web servers are the most common types of servers and are accessible via HTTP POST requests, making them ideal for remote AI clients or web-based integrations. Register a web server using the `web` method: + +```php +use App\Mcp\Servers\WeatherServer; +use Laravel\Mcp\Facades\Mcp; + +Mcp::web('/mcp/weather', WeatherServer::class); +``` + +Just like normal routes, you may apply middleware to protect your web servers: + +```php +Mcp::web('/mcp/weather', WeatherServer::class) + ->middleware(['throttle:mcp']); +``` + + +### Local Servers + +Local servers run as Artisan commands, perfect for building local AI assistant integrations like [Laravel Boost](/docs/{{version}}/installation#installing-laravel-boost). Register a local server using the `local` method: + +```php +use App\Mcp\Servers\WeatherServer; +use Laravel\Mcp\Facades\Mcp; + +Mcp::local('weather', WeatherServer::class); +``` + +Once registered, you should not typically need to manually run the `mcp:start` Artisan command yourself. Instead, configure your MCP client (AI agent) to start the server or use the [MCP Inspector](#mcp-inspector). + + +## Tools + +Tools enable your server to expose functionality that AI clients can call. They allow language models to perform actions, run code, or interact with external systems: + +```php +get('location'); + + // Get weather... + + return Response::text('The weather is...'); + } + + /** + * Get the tool's input schema. + * + * @return array + */ + public function schema(JsonSchema $schema): array + { + return [ + 'location' => $schema->string() + ->description('The location to get the weather for.') + ->required(), + ]; + } +} +``` + + +### Creating Tools + +To create a tool, run the `make:mcp-tool` Artisan command: + +```shell +php artisan make:mcp-tool CurrentWeatherTool +``` + +After creating a tool, register it in your server's `$tools` property: + +```php +> + */ + protected array $tools = [ + CurrentWeatherTool::class, + ]; +} +``` + + +#### Tool Name, Title, and Description + +By default, the tool's name and title are derived from the class name. For example, `CurrentWeatherTool` will have a name of `current-weather` and a title of `Current Weather Tool`. You may customize these values by defining the tool's `$name` and `$title` properties: + +```php +class CurrentWeatherTool extends Tool +{ + /** + * The tool's name. + */ + protected string $name = 'get-optimistic-weather'; + + /** + * The tool's title. + */ + protected string $title = 'Get Optimistic Weather Forecast'; + + // ... +} +``` + +Tool descriptions are not automatically generated. You should always provide a meaningful description by defining a `$description` property on your tool: + +```php +class CurrentWeatherTool extends Tool +{ + /** + * The tool's description. + */ + protected string $description = 'Fetches the current weather forecast for a specified location.'; + + // +} +``` + +> [!NOTE] +> The description is a critical part of the tool's metadata, as it helps AI models understand when and how to use the tool effectively. + + +### Tool Input Schemas + +Tools can define input schemas to specify what arguments they accept from AI clients. Use Laravel's `Illuminate\JsonSchema\JsonSchema` builder to define your tool's input requirements: + +```php + + */ + public function schema(JsonSchema $schema): array + { + return [ + 'location' => $schema->string() + ->description('The location to get the weather for.') + ->required(), + + 'units' => $schema->string() + ->enum(['celsius', 'fahrenheit']) + ->description('The temperature units to use.') + ->default('celsius'), + ]; + } +} +``` + + +### Validating Tool Arguments + +JSON Schema definitions provide a basic structure for tool arguments, but you may also want to enforce more complex validation rules. + +Laravel MCP integrates seamlessly with Laravel's [validation features](/docs/{{version}}/validation). You may validate incoming tool arguments within your tool's `handle` method: + +```php +validate([ + 'location' => 'required|string|max:100', + 'units' => 'in:celsius,fahrenheit', + ]); + + // Fetch weather data using the validated arguments... + } +} +``` + +On validation failure, AI clients will act based on the error messages you provide. As such, it is critical to provide clear and actionable error messages: + +```php +$validated = $request->validate([ + 'location' => ['required','string','max:100'], + 'units' => 'in:celsius,fahrenheit', +],[ + 'location.required' => 'You must specify a location to get the weather for. For example, "New York City" or "Tokyo".', + 'units.in' => 'You must specify either "celsius" or "fahrenheit" for the units.', +]); +``` + + +#### Tool Dependency Injection + +The Laravel [service container](/docs/{{version}}/container) is used to resolve all tools. As a result, you are able to type-hint any dependencies your tool may need in its constructor. The declared dependencies will automatically be resolved and injected into the tool instance: + +```php +get('location'); + + $forecast = $weather->getForecastFor($location); + + // ... + } +} +``` + + +### Tool Annotations + +You may enhance your tools with [annotations](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations) to provide additional metadata to AI clients. These annotations help AI models understand the tool's behavior and capabilities. Annotations are added to tools via attributes: + +```php + +### Conditional Tool Registration + +You may conditionally register tools at runtime by implementing the `shouldRegister` method in your tool class. This method allows you to determine whether a tool should be available based on application state, configuration, or request parameters: + +```php +user()?->subscribed() ?? false; + } +} +``` + +When a tool's `shouldRegister` method returns `false`, it will not appear in the list of available tools and cannot be invoked by AI clients. + + +### Tool Responses + +Tools must return an instance of `Laravel\Mcp\Response`. The Response class provides several convenient methods for creating different types of responses: + +For simple text responses, use the `text` method: + +```php +use Laravel\Mcp\Request; +use Laravel\Mcp\Response; + +/** + * Handle the tool request. + */ +public function handle(Request $request): Response +{ + // ... + + return Response::text('Weather Summary: Sunny, 72°F'); +} +``` + +To indicate an error occurred during tool execution, use the `error` method: + +```php +return Response::error('Unable to fetch weather data. Please try again.'); +``` + + +#### Multiple Content Responses + +Tools can return multiple pieces of content by returning an array of `Response` instances: + +```php +use Laravel\Mcp\Request; +use Laravel\Mcp\Response; + +/** + * Handle the tool request. + * + * @return array + */ +public function handle(Request $request): array +{ + // ... + + return [ + Response::text('Weather Summary: Sunny, 72°F'), + Response::text('**Detailed Forecast**\n- Morning: 65°F\n- Afternoon: 78°F\n- Evening: 70°F') + ]; +} +``` + + +#### Streaming Responses + +For long-running operations or real-time data streaming, tools can return a [generator](https://www.php.net/manual/en/language.generators.overview.php) from their `handle` method. This enables sending intermediate updates to the client before the final response: + +```php + + */ + public function handle(Request $request): Generator + { + $locations = $request->array('locations'); + + foreach ($locations as $index => $location) { + yield Response::notification('processing/progress', [ + 'current' => $index + 1, + 'total' => count($locations), + 'location' => $location, + ]); + + yield Response::text($this->forecastFor($location)); + } + } +} +``` + +When using web-based servers, streaming responses automatically open an SSE (Server-Sent Events) stream, sending each yielded message as an event to the client. + + +## Prompts + +[Prompts](https://modelcontextprotocol.io/specification/2025-06-18/server/prompts) enable your server to share reusable prompt templates that AI clients can use to interact with language models. They provide a standardized way to structure common queries and interactions. + + +### Creating Prompts + +To create a prompt, run the `make:mcp-prompt` Artisan command: + +```shell +php artisan make:mcp-prompt DescribeWeatherPrompt +``` + +After creating a prompt, register it in your server's `$prompts` property: + +```php +> + */ + protected array $prompts = [ + DescribeWeatherPrompt::class, + ]; +} +``` + + +#### Prompt Name, Title, and Description + +By default, the prompt's name and title are derived from the class name. For example, `DescribeWeatherPrompt` will have a name of `describe-weather` and a title of `Describe Weather Prompt`. You may customize these values by defining `$name` and `$title` properties on your prompt: + +```php +class DescribeWeatherPrompt extends Prompt +{ + /** + * The prompt's name. + */ + protected string $name = 'weather-assistant'; + + /** + * The prompt's title. + */ + protected string $title = 'Weather Assistant Prompt'; + + // ... +} +``` + +Prompt descriptions are not automatically generated. You should always provide a meaningful description by defining a `$description` property on your prompts: + +```php +class DescribeWeatherPrompt extends Prompt +{ + /** + * The prompt's description. + */ + protected string $description = 'Generates a natural-language explanation of the weather for a given location.'; + + // +} +``` + +> [!NOTE] +> The description is a critical part of the prompt's metadata, as it helps AI models understand when and how to get the best use out of the prompt. + + +### Prompt Arguments + +Prompts can define arguments that allow AI clients to customize the prompt template with specific values. Use the `arguments` method to define what arguments your prompt accepts: + +```php + + */ + public function arguments(): array + { + return [ + new Argument( + name: 'tone', + description: 'The tone to use in the weather description (e.g., formal, casual, humorous).', + required: true, + ), + ]; + } +} +``` + + +### Validating Prompt Arguments + +Prompt arguments are automatically validated based on their definition, but you may also want to enforce more complex validation rules. + +Laravel MCP integrates seamlessly with Laravel's [validation features](/docs/{{version}}/validation). You may validate incoming prompt arguments within your prompt's `handle` method: + +```php +validate([ + 'tone' => 'required|string|max:50', + ]); + + $tone = $validated['tone']; + + // Generate the prompt response using the given tone... + } +} +``` + +On validation failure, AI clients will act based on the error messages you provide. As such, it is critical to provide clear and actionable error messages: + +```php +$validated = $request->validate([ + 'tone' => ['required','string','max:50'], +],[ + 'tone.*' => 'You must specify a tone for the weather description. Examples include "formal", "casual", or "humorous".', +]); +``` + + +### Prompt Dependency Injection + +The Laravel [service container](/docs/{{version}}/container) is used to resolve all prompts. As a result, you are able to type-hint any dependencies your prompt may need in its constructor. The declared dependencies will automatically be resolved and injected into the prompt instance: + +```php +isServiceAvailable(); + + // ... + } +} +``` + + +### Conditional Prompt Registration + +You may conditionally register prompts at runtime by implementing the `shouldRegister` method in your prompt class. This method allows you to determine whether a prompt should be available based on application state, configuration, or request parameters: + +```php +user()?->subscribed() ?? false; + } +} +``` + +When a prompt's `shouldRegister` method returns `false`, it will not appear in the list of available prompts and cannot be invoked by AI clients. + + +### Prompt Responses + +Prompts may return a single `Laravel\Mcp\Response` or an iterable of `Laravel\Mcp\Response` instances. These responses encapsulate the content that will be sent to the AI client: + +```php + + */ + public function handle(Request $request): array + { + $tone = $request->string('tone'); + + $systemMessage = "You are a helpful weather assistant. Please provide a weather description in a {$tone} tone."; + + $userMessage = "What is the current weather like in New York City?"; + + return [ + Response::text($systemMessage)->asAssistant(), + Response::text($userMessage), + ]; + } +} +``` + +You can use the `asAssistant()` method to indicate that a response message should be treated as coming from the AI assistant, while regular messages are treated as user input. + + +## Resources + +[Resources](https://modelcontextprotocol.io/specification/2025-06-18/server/resources) enable your server to expose data and content that AI clients can read and use as context when interacting with language models. They provide a way to share static or dynamic information like documentation, configuration, or any data that helps inform AI responses. + + +## Creating Resources + +To create a resource, run the `make:mcp-resource` Artisan command: + +```shell +php artisan make:mcp-resource WeatherGuidelinesResource +``` + +After creating a resource, register it in your server's `$resources` property: + +```php +> + */ + protected array $resources = [ + WeatherGuidelinesResource::class, + ]; +} +``` + + +#### Resource Name, Title, and Description + +By default, the resource's name and title are derived from the class name. For example, `WeatherGuidelinesResource` will have a name of `weather-guidelines` and a title of `Weather Guidelines Resource`. You may customize these values by defining the `$name` and `$title` properties on your resource: + +```php +class WeatherGuidelinesResource extends Resource +{ + /** + * The resource's name. + */ + protected string $name = 'weather-api-docs'; + + /** + * The resource's title. + */ + protected string $title = 'Weather API Documentation'; + + // ... +} +``` + +Resource descriptions are not automatically generated. You should always provide a meaningful description by defining the `$description` property on your resource: + +```php +class WeatherGuidelinesResource extends Resource +{ + /** + * The resource's description. + */ + protected string $description = 'Comprehensive guidelines for using the Weather API.'; + + // +} +``` + +> [!NOTE] +> The description is a critical part of the resource's metadata, as it helps AI models understand when and how to use the resource effectively. + + +### Resource URI and MIME Type + +Each resource is identified by a unique URI and has an associated MIME type that helps AI clients understand the resource's format. + +By default, the resource's URI is generated based on the resource's name, so `WeatherGuidelinesResource` will have a URI of `weather://resources/weather-guidelines`. The default MIME type is `text/plain`. + +You may customize these values by defining the `$uri` and `$mimeType` properties on your resource: + +```php + +### Resource Request + +Unlike tools and prompts, resources can not define input schemas or arguments. However, you can still interact with request object within your resource's `handle` method: + +```php + +### Resource Dependency Injection + +The Laravel [service container](/docs/{{version}}/container) is used to resolve all resources. As a result, you are able to type-hint any dependencies your resource may need in its constructor. The declared dependencies will automatically be resolved and injected into the resource instance: + +```php +guidelines(); + + return Response::text($guidelines); + } +} +``` + + +### Conditional Resource Registration + +You may conditionally register resources at runtime by implementing the `shouldRegister` method in your resource class. This method allows you to determine whether a resource should be available based on application state, configuration, or request parameters: + +```php +user()?->subscribed() ?? false; + } +} +``` + +When a resource's `shouldRegister` method returns `false`, it will not appear in the list of available resources and cannot be accessed by AI clients. + + +### Resource Responses + +Resources must return an instance of `Laravel\Mcp\Response`. The Response class provides several convenient methods for creating different types of responses: + +For simple text content, use the `text` method: + +```php +use Laravel\Mcp\Request; +use Laravel\Mcp\Response; + +/** + * Handle the resource request. + */ +public function handle(Request $request): Response +{ + // ... + + return Response::text($weatherData); +} +``` + + +#### Blob Responses + +To return blob content, use the `blob` method, providing the blob content: + +```php +return Response::blob(file_get_contents(storage_path('weather/radar.png'))); +``` + +When returning blob content, the MIME type will be determined by the value of the `$mimeType` property on the resource class: + +```php + +#### Error Responses + +To indicate an error occurred during resource retrieval, use the `error()` method: + +```php +return Response::error('Unable to fetch weather data for the specified location.'); +``` + + +## Authentication + +You can authenticate web MCP servers with middleware just like you would for routes. This will require a user to authenticate before using any capability of the server. + +There are two ways to authenticate access to your MCP server: simple, token based authentication via [Laravel Sanctum](/docs/{{version}}/sanctum), or any other arbitrary API tokens which are passed via the `Authorization` HTTP header. Or, you may authenticate via OAuth using [Laravel Passport](/docs/{{version}}/passport). + + +### OAuth 2.1 + +The most robust way to protect your web-based MCP servers is with OAuth through [Laravel Passport](/docs/{{version}}/passport). + +When authenticating your MCP server via OAuth, you will invoke the `Mcp::oauthRoutes` method in your `routes/ai.php` file to register the required OAuth2 discovery and client registration routes. Then, apply Passport's `auth:api` middleware to your `Mcp::web` route in your `routes/ai.php` file: + +```php +use App\Mcp\Servers\WeatherExample; +use Laravel\Mcp\Facades\Mcp; + +Mcp::oauthRoutes(); + +Mcp::web('/mcp/weather', WeatherExample::class) + ->middleware('auth:api'); +``` + +#### New Passport Installation + +If your application is not already using Laravel Passport, start by following Passport's [installation and deployment steps](/docs/{{version}}/passport#installation). You should have an `OAuthenticatable` model, new authentication guard, and passport keys before moving on. + +Next, you should publish Laravel MCP's provided Passport authorization view: + +```shell +php artisan vendor:publish --tag=mcp-views +``` + +Then, instruct Passport to use this view using the `Passport::authorizationView` method. Typically, this method should be invoked in the `boot` method of your application's `AppServiceProvider`: + +```php +use Laravel\Passport\Passport; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Passport::authorizationView(function ($parameters) { + return view('mcp.authorize', $parameters); + }); +} +``` + +This view will be displayed to the end-user during authentication to reject or approve the AI agent's authentication attempt. + +![Authorization screen example](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABOAAAAROCAMAAABKc73cAAAA81BMVEX////7+/v4+PgXFxfl5eUKCgr9/f1zc3P29vby8vLs7Ozj4+Pp6env7++RkZF5eXlRUVF9fX2Li4uEhISOjo4bGxt0dHS0tLTd3d12dnbLy8vW1tapqanFxcVMTEygoKDDw8PIyMgODg7BwcGwsLASEhKbm5uBgYFGRkbh4eHf398gICCXl5fS0tLR0dG6urolJSXPz8+Tk5MVFRVbW1va2tq4uLijo6NnZ2eZmZnNzc02NjZWVlaIiIhAQEClpaUuLi6enp6Hh4e2trZsbGzY2NjU1NStra28vLwyMjJjY2MpKSmVlZVfX187Ozu+vr5OTk7PbglOAABlU0lEQVR42uzBgQAAAACAoP2pF6kCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGB27Ci3QRiIoqiNkGWQvf/tFlNKE5VG+R1yjncwUq5eAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwilAKIn325Y8zwv1VO7NuplvEFEqSeNeOeKWgYDKJkncy7zlwwSEkQ8S958zb3Xprc1AIK31peaNb3FXyjCG27LOQEjrMknclZKOvLX9SjW7DwRSct23SdsTp3DPjvlW2zhQTkBAeQyUVhXucr9NfeQtAWGNxPVJ4f7ut2ndLuMmEFrp87wq3IOSfvpmvkF4i8I9OfdbTUB49btwArcrafSt6xvcxFa4rnCP+23x/xRuY/yeFe53wNU29wTcRJ9bFbhzwG3n+PhLwH18sW8HNw4CURQEsYXQgMb5p7uGFQ6iqQrBh9b7jLxNR+pvwL3HdKBCyb7O8Ra4a8CNzzoXIGSuH0eqAQdNJtzpfkL1/1NIef0/pD47cPeFeixAyuFGvRbcexwuVKjZ1+PxN+p2Bm6f/sQANWOdu8C9XsMnOOg5P8KNh3+EuwP35N8AkjaB2+7ALUDMN3APf2XYFoGDKIG73hgEDoq+gXv4M+q2CBxECZwFB1kCZ8FBlsBZcJAlcBYcZAmcBQdZAmfBQZbAWXCQJXAWHGQJnAUHWQJnwUGWwFlwkCVwFhxkCZwFB1kCZ8FBlsBZcJAlcBYcZAmcBQdZAmfBQZbAWXCQJXAWHGQJnAUHWQJnwUGWwFlwkCVwFhxkCZwFB1kCZ8FBlsBZcJAlcBYcZAmcBQdZAmfBQZbAWXCQJXAWHGQJnAUHWQJnwUGWwFlwkCVwFhz8sXcHOWoDURRFLXkDX39e+99mQMhtKRBIRUSCV+eMuxlevbILEUvgLDiIJXAWHMQSOAtuNWP0xiIEzoJby6j9QuIWIXAW3FLGpW4Ktw6Bs+BW0pe2SdxCBM6CW8f1eKpwSxE4C24Z1+Opwq1F4Cy4VVyPpxK3GIGz4NZwPZ4q3HIEzoJbwS1vErccgbPg8t3yJnELEjgLLt1d3uoucRqXSuAsuGgPxltt437F9dgIJHAWXKoxqv50Iu39XolcHoGz4LKMm67aH6lx3Bl5qLp7XGldBoGz4GKM2l/p36/FefuQTeAsuBSvi1Vj7u/3jS8ncBZcitd5m05ibXw3gbPgQvRM3g5twmUTOAsuRM/k7dRP/8+7hi8ncBZciJqs26kFLpbAWXAh5ut2Gl0ewkUSOAsuw3hQp6mru90lcHEEzoLL0GfW6nZd958y2RdV5S1DCIGz4DL0W6/nlodwGQTOgstwJunzPo0JAmfB8SRJ2zsMX9fKIHAWXIZd4BA4Cy7VUaQSOATOgksjcAicBRfrzYFzES6DwFlwGX6K9JEfx98SuM2C48mZUuAQOAsuzLDgEDgLLpaXDAicBRdL4BA4Cy6Wi74InAUXq44kfeBX95khcBYc/ztwvmyfQeAsuAz1kySBQ+AsuDAtcAicBZfqTNLnHXiZIHAWHM9u+n7eO1kmCNxmwfEgcAcvURE4Cy7N+ZZB4BA4Cy7MOwPnh59TCJwFF+J8COcRHAJnwYUZ+8EJ9Rf7dpCbQAwEUXTRF7B63/e/ZqREgEiIgBlW5feWHOCrbDMInAWX5nZGFTgEzoILcw3ccgWHwFlwYeZTXWpXcDEEzoJLMfWhCVdOqDEEzoKLsT6zvFrgcgicBRdj6mIMOATOggtze2Yw4BA4Cy7M1MV4YkDgLLgwtwlnwCFwFlyYOV+nMuCSCJwFl6SuxoBD4Cy4LH3yv3BtwGUROAsuyjq3wMqAyyJwFlyUqas5NwBJIHAWXJYzjerymX0YgbPgwqzDhWsH1DgCZ8GFmTpYuCkH1DgCZ8GlOTjEphxQ8wicBRdnHSpcOaAGEjgLLs4cadVyQE0kcBZcnn67cLMcUCMJnAUX6N3CTelbJoGz4BL1W8VqfUslcBZcpK7XR9wqDwypBM6Cy/RytUbfggmcBRfqrlur/596+hZM4Cy4VOs+XfP4dUHfogmcBRern9Vrlr6FEzgLLlfXvf6bN++n2QTOggvW9Uv3tW4/efP9QjaBs+CSzaoHjZvvnx1PNyBwFly2rkf0bRMCZ8GF63puuX4LJXAWXLyWt20JnAW3gfvEeTzdh8BZcFtol29bEjgLbg/d8rYhgbPgdjHt7m07AmfBbWRa3fYicBbcXqa/6yZvexA4Cw5iCZwFB7EEzoKDWAJnwUEsgbPgIJbAWXAQS+AsOIglcBYcxBI4C44vduuABAAAAEDQ/9f9CB0RsSVwDg62BM7BwZbAOTjYEjgHB1sC5+BgS+AcHGwJnIODLYFzcLAlcA4OtgTOwcGWwDk42BI4BwdbAufgYEvgHBxsCZyDgy2Bc3CwJXAODrYEzsHBlsA5ONgSOAcHWwLn4GBL4BwcbAmcg4MtgXNwsCVwsVu3LQlDYRzGb8t7PaeVUVmtmkIPRlpKBor1IiSh7/95ysUEdVOnFoe76/dWlJ3juPiz4ACzCBwLDjCLwLHgALMIHAsOMIvAseAAswgcCw4wi8Cx4ACzCBwLDjCLwLHgALMIHAsOMIvAseAAswgcCw4wi8Cx4ACzCBwLDjCLwLHgALMIHAsOMIvAseAAswgcCw4wi8Cx4ACzCJyrC67/VOv9/2YJvxSSZcnlQ2VZypN9HzITQxyS/gK9zEDaT29LZ0/Xu2elYy/pWxFPZuGdVpuF68/yVXbSsR7zoYZYQ+BcXXD7+sOXRRU09CBL0tHQrizM10Qb4o689q3Od7CsjLnRgWMZcrXX00jtpDjlsiot/+TckwlWjt5rGmnt3yW+F1UN1cUaAufqgove9CBL4FJzKHD3MmozSAjcZUeHvZWnX1Yll3hVXrOmw266BO6/cXTBFTVSkDlsfRA4NwLny6imxgbutq3jGtvTL6tWlViXPR0THKz8ReAyz9viBgLn6IJb00hL0lp/9bVB4NwIXLAjI9qxgStWNM5haYbLepIYF4HGaWV/PXDdXEW74gYC5+aCyxzqwKOkUnqpqxK4L/bOtC11HAzDL8tbKYK4VRBxoYCDLHPAgiIoouKCiMf//2tmSE3atClQcK7p0dwfZjxasAnN7dNsDYrg8BJ41JJIcM8lFGNk51cWpsGJkkIPRvH/VHDx83dElIILDMFMcGm02PcX3xDxDxPcfs1NkIZRVxPcNfAUUSC4Aotbg5vnbuLp+WaTZbhH7j13apT7175OLXgGDu6RUn5LPyWyt1s9/KSv/peC20KUggsSwUxwLZwyIv+thoIluPtXwsWXCS4DwWZZwZlKKcWAY2Jqhyv6epXKJ81a4mEfTcYxz8qql9EkBTwX+Mmk6R5yaLmvi6dXwlAK7tsRyARnDrSVnpDwECzBUaTg5hTsw1RUEeyEIuRPV8de9BB12WsILJQ3NNmdUVkTJGi8Rc80JOhX3KUxQZO853UhBfftCGSCu/q8uSnjlIkUnG8CIbhd01rAYDeDf3GCO0aTHeDZR0Ik6V1ZyYaoF+4VCSVHyg73kVCWgvs5BDLBmRdi7lN0JVUKzi+BEFzbfGEIbAxxStMuuNAYCZvgIHSEhNSMytoSDKS2dY9u0mgVCRdScD+GICY4s2EYMUjoOOXu6wQXbv86zTVjoopIdIu1y5dHb5uGD4q1NPhDfbq4O72oJ/8rwSXr6atcPqp4n0C9WHvg1j0lm89XFxXF6w2bxdpzNi4QnKC2frdjswQHI5zyYn8dUcwYmOCsAGesg5MKEsYzKusWCfuCAPce8pqD97qQ4GLtwm2tmI2CJ4ls7uplXZGCCzBBTHB/4ZQJu6rLNslohDWw2NcICWhO/1dCE81E4S7k9rCEhMEt8DxuVdmw27EKjKZGKADEbkjvEcCbRngCgBdNxC8ml9N39qa3Mb+CyzQ0wiUwbjRCOQyEZiuCJqVeTgETdoLTg+oT3fz5JEFvEY+QYEyi7jIqxT6a9J9DMwRX2Wmgid56UbwFZ7b2IVjkccoeJ7h372HpHhLOvCsrj65uDFVHQtercxfHLsGZdT0BRqi4qaPJYJdWHjvwfnrEbQ8JRsusysn0J8hdf9uwDFJw3zvBKQ3WrXKMhIolOCR0XDc9GIUsurELLtxBi6MMWByU0Y6RCjtWVPxiE1G5hvEwa1ZWeK+ENiKnfhPcHRIiZ+xkdPP0HmHKyQfa6V04ImsMYhPnr2/37N9RHGWsD9Bi3PUSXHQT7YwPPQXXxSlVBRgpnFKwCy6OJglws4OEnHdl5ZCw556IMgIBZSREnYIrOaa03FXRhj4MA4EeuAVQaCAjcqXQeuL5C5ZACu6bJ7gCTiEJJGk26fuvEFySt1g1DpS7Ejp4bzsEl6miT8FleuhgovoSHLvVKitAUAdIyLGWzbPhEFyyj3YuAfIa2qnxZcxqvOYfxIL7pSGPvuElODAlkAcGKYIWYoKzClIGAXWNkPKurL/c8W9IhywEXGmE9GzBqRPXBZFxCC6no517KbiAEsAE16EOY+t6Bl8guLxTOK+8R3iM31zjTw/Qp+BODHTxHvYlOGa0c66gazDlQkcnpQNOcMkRckSieYfIjXV7Ge8Mp7geRILbQDdrXoJbc8xSq9NPjwmOfVlbakQmPHKPoo4X6wbzFlxigC60DCe4nLPuH6XggknwElzMbGi/7Tklv7rg3Jffb3qhMyKWNbQze+OfoA/B/QKARJVaYjSZjHQqAmGbvc07oW3zqcRaD0DRbsmDEpVma3g9ol+H7AXaRwfsOMa1vYwjdNJQ3YL7zZp0v7M5xk+KQsHRMD5w3HKmOcGVkXC4lOC2kBBRgRFCgq4sKzilzCrgutM3kNW7dWBHQwdlRQoukAQvweXs6xdUA6cMFxGc+vAvz0goPZhwAjM6hWgoU+zRCMevErouViCWrbFJ9WHW+BlGw+AaRuLBBm0WmwpAqIwE/TxGSjGk4W6xtah9tmLcMldCM8VbsfVlYStjxrkGEp4dxta2mqr6d0pHhrGWj4cPdg0k6CFHGV9zj7G/L1lLHToFxyZaVH+Rl1bKtJ9QLLiQxoepnjk8zgluQL/0Lzh1S3evZEggoQHLCu4vNOnESQO5Muy/o4SU3tVjTM2yyq1A9uFfRkjYfiC0wT9ScN88wR1xYadFO+TmC857mohJpAuE0PWnNsg/Gkgw7mj7+ECTXb7xV8+7cQBuVJbjRUfCOAkAp86O+jQSej4FB6+0i0f54JZ1jM0GqXDTZ3GHL3Cj4lzZqzWB0NSR8MiVMUKDWI0243Wn4CZIOEo4FrXviQUHHa4PNUM/G7vgNCSoiwkufUA5Od5q0DRZAYs6Et6XFdwjEgw20P7Z/6onOMG9KkDI60h4kNNEAkngElyUv2MpIqG4uuAMdp+7XjK/odjuMgtAUTaRMFbsjT+lzp44XNGQYNRtMx8OXWuKmj4Fp5qJQO++IWELCPUIIe/od2pxBW5k2C/iFW8JpmgXnM5aJauVc05wbJqFZtkoPKZ/gdyCY27tcf13OU5woQXXuR+hNzlgsJvozWUFt4+EG2CcImHDLrhJyLGz164UXCAJXILbZXYhxCL00ltVcCeuDUHWraGviWAi/Iut8R/NWRkRe0eTWxKQ3G2sotNg6ktwcGCgjXIIxJj5bsQVuO0casQX5xSUDbvghu7pFGWH4Dbcm5DmqCoFgmMdqhXbu+oqJzhFp11mvgUn7uk6QcLRkoILa2Zgt/fqDaimmeCOQgB8eu5IwQWSwCW4kRmYHDdpenxVwRnu+RdtFklK62AjxaTHGn9ljuBe0X6rtoeErrtcA5+C4zfArUZnb7+i20+w4X4PYLy4b8MN+5t30STJC65nnkYMLOLUjkLBQcsSKSSoebhb1CoS4ssKzjgFjkckjJYUXNGmfkdIi1qCK7iWW0yk4AJJ0BJc03krd4GE2mqC41+yzwR3SI0iyAA9m+BgtuBqXMKijXE9auPdqVl22EnUSZx3J0UvgIDEyXHqGk3sJ7jHpyzeriduwZWBYWmnbhMcS1ujqB2aVsWCu6XvzWLjqUNwIyQcLCm4zTOgcMatLim4GyQUozZSSMhaglOAoUrBBZmgJbg9vimygbj3VQV3KhRcjr6foBtQsxp/b7bgDnUkNBJ0OqsnSd9rUWMj/OQGHCSLe/0IMnjB5YTT/b0F1xFt6/nCCS6KnvQ8BJfUrWUKH/SDEk0TKSwhOK18lQAeZmEMLSe4IXpSZAdWQQruDyFgCS5URULEAk0eVxRcViA49sNt4DCQEGONf3+W4NjcCT3PXu/Jk2/BwQGbf8KLb7eHFJHgmi7B3c4U3LZoo7VbTnBZ9EQTCo59fcfWiPbBIbg9JOwsJrhcltKMeiisR425lOA20ZM3duCHFNyfQsASXBq92FpRcH8LBZcSPDiAJbAz1qTPZwku3EeTK3bJe9P1L7gmqwEbSq6BboQnyASXmym4WxD0Q75xgntATwwvwV2ZcmZnsesU3AWNgAIyDULH19YrbOaKgFyDcOwtuHf0ZMM6UAruTyFgCa6FXjQUD8F1VhHchnAnCw0J4cUEN0R2UvMTXMa34JJjZAGRoVwjQx9db32B4HZFCS63aIJreAkuyvb0a9FK5wWn6t7VsI2EDV+C+80uGDcfSGguleCOpeD+PIKV4JIl9KTgIbj3VQT3LNrTP0y7qRcS3DGavMecCTAlIOxLcLzKGknnNhvY33rIhACgtbrghqI+uAInuAR6FuxNIDh+99KYQQc3ecHBkeAz4D/bui/BhQ0kXHhul6Qpc/vgOik3j1Jwfx7BSnCn6E3HQ3C4iuDyomnvBfrNRQTXLdHFq84GbnzJjr7baHGt8LM8RnkgfIngjkSjqI+iUdTNBXf0tddX6/P+9i+34NJI0OseO59iVfElOEjRp9V47UDVmj+K2gUBUnB/HsFKcH1hQkCCEaOC4y6wx5UElxTdHw1ZpJkvuHgDCfqL6P1XF1xBF+2I1HE6dXN1wUXiQGHf01XRPLhGyIfg6P7MYfOcm27Bwbt4B17WubkH/gSXKHlkwrMqEoqegmO6PZWC+x4EKsG1ac82z5bVPkOuWZwdXnBKiYaMhQQHLXckXDeQkF9AcKEyCsYg/0bCZFXBsQHaQbzHdcONnBbH1QWHe+5T+wBecOdIuPMhOHqyaY2kKhAILs0/VIvRoeb1KTjYR6Gl1B6d9egpODaOPw4vJ7htOmYfDKTgApXg/qKrmnnqttZWNQ9h2eUGqeD4FQOLCu43mvxyrUXtwQKCS6FJy6PviKG2Nqdk/QiOPVBPz8JTyVrKDzHnuq/CVwhObzuXH+GleC1qIwaMLinXtSoQHPepDqhEOcHx3YxHKlgoN2z6n1/BsXGZLcVuIvprDj0Fx48fM/ZJGY8XEdwzHZIOBlJwQUpwythjFaHZOPQoUwfrjbpCp+CukfCyoOCUARKMNJjEWmhytYDgcmgyUoV9PT2mDOXVbOUhf4Lbpx5iv/ba1qbeFTB51L5CcKg9gMlxCQl60mM3kZbq2A1gOCPBddGiIBIcJAdoMrhjwemlh0ht6ldwrGMUy+wPV+i0iiathXYT0S6AH0bSK4sIromEckCMIgUXpAR34nUDtIOEDVtk6h+qoJ5MkBecdUD1VAVQunMFx7a70SdNBUC9G9A0ocwX3JOBJsd5Gxlrz0TjWCGNq3tEN2wTCG7t3I3p52d2KtZbbtiHac3d5nYiuJrgGJ3ndugg1+JWsXOCS1S5BzGoFwO6ltdbcNBASjUkFBzUS+yIrdvD9Xpu54hZ9wD8Cw7ukNLbfu5G88epEX7yrnoLjhuh3jPN2t5HlpfnC05Fk+snBSD+vz8RUgouSAmuQ2ODk0frpvEAGYZ5+BovuF9I0Ro6KnMFBxtIKQ2qSGkkYL7gjlBExyYCNPqdvX6JWlnhPTBnyLhtmOUwi1b5LG/WClJYvV6b9A1kqCsIboxORuEZO/pq5b1ODz9JwSzB7XHFEgkODjUUY+SXe8ZiTUcxg/jCO/rqo0nqQ2M7vi8kOOgjfXUjInf0/f8JUIKLRTwnIfSsi3GCPKk7XnBwjRaLCA5e0U3kEBYQXN9bTgXRMxni4Edw6ggJDyyVsG64glMDu0iorCC4LadjSlnRMxl2RWerzBScdbZpL8FBZoAiIi/LPkT2whD77WzJZzJ0YTHBdeWW5YEiQAmONUM3u1ZQUMe83xSn4Coln4KDWknwEKUVBQftHjroJ8GX4CbOBzlsWt1w92hHfy4i4XAFwZ3n+Wqo5sVP1XrQ0MFQgZmCC2nUwzFPwUFyqKOLVnT5p2QflNGF/lcY5gsO1JbLb3VYUHAwlIILEgFKcB9mI1DBTcXWhbP+jozSOYBTcPB74FNw0ORlVNoPw8qCgxjfYo19FXwJ7goJvTBQEhrrhlOGaBEpwBM9zxUEBw8RtOhlQCw4OOPN0agpMFtw0KG+AoHgGAebyDMu+hiREfAwQp5yfd5ie0pN40XbhoUFp67pUnDBITgJLqrTRiCgb1t9E94dIyGylQCX4MgBEWqVOYJjZIcRlt5qSYBVBUeIb7AWpt0nAXwJLquzZwEyntHqhnuiOmjcJwDC5tGvKwkOkmy44uNCmfFk+8dUlfXTXYYA5gkujSY5seAYT9t9y5v7WYDVBAehwv7ANtpQAVhUcBDLMY2XOu2F5sEx6uylu7AEUnDfNMEtjpLPbe8WmzHvA6KHl/e7d4UwLEz48eX4fuM5/7UVcXaY293O5aMKfD3xbO7mvNgNwUrwEo/V0xs3t4eJuepoFy5vNorNJHwxicNibef8+TDzVTWWKeQ2dq7S2aj/+u0W3+6PC5UlKjh2kN7YecudwXJIwX3HBCf5n2CCk3w7pOD+yAQnkYKTSMHJBCeRgvvRSMHJBPfjkYL7vkjByQT345GC+75IwckE9+ORgvu+SMHJBPfjkYL7vkjByQT345GC+75IwckE9+ORgvu+SMHJBPfjeeoRgrIJrUQKTiY4iUQiBScTnETyg5GCkwlOIvm2SMHJBCeRfFuk4GSC+4e9821NHIvC+EkJeUxqDEkkMVbpSEVRasWCioKIFmtfFPr9v82ae73XZE2z3e0fdpzze2Mnc3NyTpn8eK4ahmEuFhYcJziGuVhYcJzgGOZiYcFxgmOYi4UFxwmOYS4WFhwnOIa5WFhwnOAY5mJhwXGCY5iLhQXHCY5hLhYWHCc4hrlYWHCc4BjmYmHBcYJjmIuFBccJjmEuFhYcJziGuVhYcJzgGOZiYcFxgiunYv6dCtGVaRpn/5Kq9LU4pitexLX+FbZo8tPoqcS8qiWBOviJ0fJYacuMgAXHCe7n6ODvLIluAJPyJNjS11LDLR1YAC79O16AJn0ePZWYV7UkUAc/MVoeA/hFjIAFxwmujD9XcO5FC84lhgXHCe6LsQxJDa+GxCq8tzeLFtF3CO5psbDpIwzvE5JMFospfRI91f9EcM1gQQwLjhPcN1HD/Sfv7c9boJwxEvoG/ieCuwcLjgXHCS4LC44F96fDguMEx4JjwV0sLDhOcP9VcE438Pzai0GCbu+FBNPNNvFr4yvKYse1frJdTEhw3etZ1Jgf1j02DRI0e10ylvf9KNxM8xZo9uYkqbzUfX/xZNIRc133veD2WrxT1+sB6B14E/UdEljPaTf1J5dUl02yJotDL7eijD48O67f9I7HR721nKpccEM9hcR46IWHC77YlMP49Rom/ccX4zTa1V3NT1atal5wxRU2erobOnDVfuxH/cf2FTEsOE5w3yO4TgLBys6FkhYkvkkn1Fr0rOPphlpXl6fHqNl1SNZGtmIMnwRVH4JkSSmWqhCNxWetinkmWxnqcHKjpojtGgTRHWme4FuUsgNiEmywlj2UCi7OT0FOAEnfoQzXfUhC/cuqhhBEv7Tg3q+QQNEmIjfML6mF4ZAYFhwnuC8UXBd+q2k+b4BNLm8B+xu78eSjXzktjxDEO7dxC7SPp7cQ3k0H7UdgaxwFF+C1M5i+hcC6SHBuH/3uztn1gDt5HPdvA2dUR2QS7TqdEOgcaJx8ZG2A1sgZtkN4jWPN7hav48bwzkc0IMUAGCg9b0mc6mFSJrjiKRwfUevZOVRXKtOt7yfOIE4wP7ax6KO1NJ9jD+gowb1fodnpQE5XJbK38GY7ZzfzsBVL+sCUGBYcJ7gvFBxCGR/mgJO59zfHW3gCNEnxippx/CFQp/eE/6wYiI+6wpMlNqL3wM254OwVfJfkAc8gMhJ0Saz3sc+9B6d9ZM3hjeSaHryBrAk8UYoZYU0Kq4+xePVxVFkDyVWJ4IqnsGrwbqTSVggMUszgO8cfYMs6qjMzhGdrwRVXyL8HVwmwrcpIu0VQYcGx4DjBfYfgHBIMgVHm3g/QIkG87tARI1iNSNBGYsnTvQoJrDo8QwrukSSuh8W54J6QNEhghak7B6uVS4I57osFNwVmRMqCj7ImuiRZICBNS/71FKtbKcAZFlQmuIIpxJExSZ6BESnWq5gEVaAh6gjNCkbAixZccYW84GZKZ3rA6c0NP+bFguME95WC03awgV+Ze38Or1r6aaQrX2Z0usGfpeB0CukiquQFJ6z2qKvMJpQhxrZYcGv4OgO9IHKkWVR7e/jZxsQl95hNZLUa2qWCK5xinrngFms6wwCaoo5QoyRAXQmuuIIWnNJ7jxQLhMSw4DjBfbngdAK5ygtuECFZPxcFCsNsxh7gyNN3dMSVCSZGpO/sJjDMC054tEvnVIadLtAvFtwq03IDmEjBkUDW1RgensUOtWp46bmVCG6p4AqnWME3FUrIGqs6Gt8CHVmnlgmPiRJcSQUtOFtlPL3lZVhwnOC+XHDDYsHR0gMQvTavKMswrkcQCMGJF4mVCHPFwlLZXW9ecIPzx0uth1YIwTuC87AnhQ3ciZqLQsHRJl3bQEA0T909Qp1KBVc4hYcsWzrhvNwnSFGCm5NiDFSU4EoqKMENpKklS+CaGBYcJ7hv+B5cseDInW2FdBqksTcAvNp6vNeCs0mgNKT2meoefsgLTkhvQjmGAQD/tXVXf09wCVqkcIE3WbNYcM30+vs0HD1gJfaq5YIrnCIBwhOvpLC6CZAEt09NJbhMZ2+ijBBccYW84IbAMtM1BsSw4DjB/ZTgBE5zkyCp0hGjBm9mWkQ01YJT+lNbrhiJRUcmBVtUF4gpi+MjbLvi44f3BLdFnRQjYFkmODuCY/XT7sQeNcR1ueAKp9iiR0V0Ea0bBhFZWnD3pNiLyYXgiivkBecC3VNh3qKy4DjB/bDgBFX/9OeRNsFOC65DAuG8idANtBBniOyzDxl8LLRNTIeoi75NVCq4DRKDSC2CWSY4ekS7IYU4x8xBSOWCK5xig9Cicyr6bTNDC66vF75iRUpwokK54Cwfr5mm/T/3zmXBcYL7ccE1g5qlwkWohaV/7GrBrSyS9JBUpOBaqqKP2vnXRPbwXJIs8ET0iDVJTlvUyDq1l/8u3tUKAZUK7g2bLt6kj1dt7D8iuPwUuQsak4lsV+VWwbUWnF44AGItuOIKgnv1+9+fPqc2E+yJYcFxgvspwZnARLksOLnDs1SUUYLDWKe7tdQNounxDSugcy44M0HdkDEwitxUKT0SmDgKrgnscu0ZdSRDWXOD6KFccFV4flpX7FG32H1EcPkpxAX7rrzgHH7l7DkJmp8EF8qFV49IqlpwxRUELaHQA1X9jIMdwnfSI6bJT6Wy4DjB/cQW9RFe0yKqLD20Ml/RaJkWWTf1BKjK00PMTcOqxhF8W+gm9cvYsYzrHvBqnQuOxsDi2SCr7WEt89qdS2S0/ei4wJQPFli6PfH0wy+HjJu5aLJUcLQCaiRYA57xIcEt/jaFvYU/uSJr0NLbV2nMWsMgMm8jqK/XLeAvbarsVsCMtOCKKwjugJklpht6qB/OtZd1eAN+VIsFxwnuBwVnh4BfDyLI5yS1MeCvPCRLoCFPn66AxAPQHyjdDD3ASwDUbCoQnBUDSIIEaBnpdQMAYRghvFNb01sg2W7XmfbcMF2UQFqkXHCxkiA9A3P6kODc/BTiqVNEq/TIHZ1oAvACH5gFGMs68R0APwLQspTgiipojBDwVv3Uj7sEiLYRkOyIBceC4wT3g4KjyszHAa9rk8Z4S49F9wPLQ+d4ut310mV7V+tGJhz0Xww6E5zg5jWtUm+TwG6lq5O1PQAceeluAmCebc/dezhQW9I/Cq6ByNaJq/kxwRnZKQROS1ywN6QsDyscCJrUw/woOHqu40BddKYFV1xB4GyAYwAcbiIA0WZILDgWHCe4H8ZyGw3HoByGMx3aOT+mx9QyrZsrs+Fa9D72YKjOEKt3uTefRMlB/ggZ1enApu9DTJG/oOiq4HdyPk2us/IKYt6paZGgYu74vxlkwXGC+3+SCYBZwTEMEQuOiBPc7w0LjnkXFhwnuN8dFhzzLiw4TnC/Oyw45l1YcJzgfndYcMy7sOA4wf3u2KNRhfKYoxtiGCIWHCc4hmFYcJzgGObPhgXHCY5hLhYWHCc4hrlYWHB/sXfHrYkjYRzHn0iYX0yNISqjsUorikHRioIVBREt1v5R6Pt/N3edccakpluv3YM79/n+sXdkNU5m8cMTt9vyBMdxVxsDxxMcx11tDBxPcBx3tTFwPMFx3NXGwPEEx3FXGwPHExzHXW0MHE9wHHe1MXA8wXHc1cbA8QTHcVcbA8cTHMddbQwcT3A5Cdct0ql/dXcc1w3o73z1n2z5xwuu6/x68a5PmYruhwsat7uroSCT5x7zBZ3n7dtvw99zoT/4A/H0ZrgOcQwcT3A/ygEmdKqHmP61hkDL/Ei+s3KP3wIufV4RQOxRui2ARzI1yhLvJXXzqBVMYfkwpmydCMDmN13o97I/VXAJBMQxcDzB/dnAoZ05EqeAc+oSkEklBpDMDXDp6oJSzQG5fGrStwv+FeBEkTgGjie4/zxwpeWy+7uBS1CmVPdYSwNcUAbKU4dI+D2JuGGAGzjvee60DCwEnVoiDn7i9yhOXehPgXtaLjVsveiFOAaOJ7j/PHCq3wxcHSjRqRpeLHDL1M2qmyAqKuDSZ2wBYzqVYEs/aPLjvbPApZNg4Bg4nuD+UOCGEepkcyEDA9wUeCPbXOJwBlwhwl2WEgbufxsDxxPcFQI36CERqeWP6AhcIUFZ0KkWYs8AZ3tFhYG7khg4nuAuB050XhNZHa0EHRtu1mFYObiUSTxv12FUPhTVc/sHMt33N0qgejmJd8spqZx+/zkDmXP/Wo2T2YtzAq7QLUfxulX6CJzz0K/GUe2l+BG4G2Bvl5OgaYDrAo0PVj6fAbdAlXSlfr8P4O9fB0SP/brdkL7ipdnvEQ0XuzgZPZDJe6lF0fJJne/JPL3/pi/UbtAujmpPgT1dk8R0mcS7O5coZxcscM3+Ir2qflDYqqXoWv034hg4nuC+B1yhBl3N0/dyC+jkM6XyytCFe0WKtcOJ0COiTgxdX5j3bhq4mwS6atEAV6pCJe+zwPkV6BL/A3BUweKEWFgwwG30ZGdztv3mGXAVzAzgMN0SLTH6MFXWUXZa0N2Jo4kRVPGKiJYwLVJTmGMOx7fmdPViGSrZpZxdsM+tI0qvCiVaIPRId/OuNcfA8QT3PeA2CF+GxfFBoq8eVAZGq5LbrCFukE3MEC/aJbcdoeoQeSF6pBtD+kS3EpX6PmjcAe0c4IIEyWHqD+rxkagylglaK/e5HgKdNHB+BNl69ofdSDGQAa6L2LMDWYsMcDVs6LwscANpV1zsdDrA7u9fg0+A22Dde75ZVYAumeX39v6+rw7sO50q0Pm7xulCxRZojf1hu4qwcTxdb4fXSeP9SuTgbBeywKVX1fFocPpQ8YDqn/s+ZuB4gvshcCLSItEB8NWbDRM9g90hLJGpYeaIOTAlohYih1R9LNUnXGXHfNSVA9wjIp/0/6CojyMcqyNuFWHxBJwoI7zVqqxRcbLAFSXapPJiNAxwIsTTV8C5a8jS+add+cABI0ddRBVV9dprRAHp3wud9Gdw9kLFwlyP10c4OF7icV2uxOZ8F7LAZVdFM8NaIeTP5Rg4nuC+DZwHNPUbc7MZKjhGhhQ9penu16+kS9RJBsCDfpR8l8+prMekaiMW58Bt1nVSlYCGPm5RGgMvJ+BuT4t8BsZZ4GiLsnmZqjDA+UD7E+Dqzfc6T1up2LwQOIM1vQAeET3ZYVZU0cwFbg48ks6LMNOns/u3ROVsF34N3IO59g5i/uJfBo4nuO8CRxFqHtk6yhFdCwmdVzb/RKGvDVDSmBRQwRlwmTU09fHQvmoFtRNwCzUa6nbYfADuASgdV/FEBrgA6OYDlyq5ocuB65yYcZVqM3t5j9Nc4DapZb9A+hq4kr3NjHJ2IR84K+nouKgFcQwcT3DfBe4NiHoNx6IG19SCdChTsO+2oNVpQgYKodQ5HbdZDwH/E+BEaTy5Azr6eDn9VR0n4NaIXJOFxQLnRKgfRyDfAkch6p8Bt3uv8rpoenQ5cBomu6Yi0KNTucCtMUrfzk81cKQygmV34ZfA2b/GcYEhcQwcT3BfJwwEmQFN9CSAcHEr9CdqmQKyee27CCoFnBMp2Rr2DmpYr0mocoHzX0YxVJ2Pg8kE8CxwIdLtPgBHByRC3TTOyABnT5b/GZztcuBikQFuADS/Ai7EIb3Urjrd8gw4swtfA1fQZ+yhQhwDxxPcJVWMNqoRXkk1OCi5yoF6v6Oaqpj57huy2u+1j8BRDztB1DraUtwCCMubySEXONGLgbhy99S0wLXI9AYULXBxZgGvWeAUNnt1A9dJAddC6FAqZ1ed/AS4iDLADYHpV8DFqesJgDdzOgtcdhe+AE4fDD1yIrSJY+B4grukLWp0qoqW3S63OwN2jrJCUE5jYDZWt3mzI3C+xJwKIRrHLy4JH11BRPNc4HqQG3UbLCxwIzIdEAsL3A59Os8Cp78Ubo7YSwHXBMaUag88/HPgBD4BLgDqXwG3Qy29V6sz4LK7cAFwgUSXmggLxDFwPMFdUh2xTyZX4u0DYfdEXcDPH/6WgsgCp2nYUAcV8+SGwSUHOA+YGA8McImgY69YkwVui6r4FXBvCD3aYEEp4ERN4WxrIfQuB85MiTefASciLO0yXD8XuC1iu4InwD0DLrsLFwBHC+zEDAfiGDie4C6qJLFJjXNhQES9ysEatiEqytNct5/e0DFHomPmHHOOZ4Te7HgH9Ygq6Xp5wM0tmzcWODRJNwDqJ+Cmp99wptPgDLiiRKcQ4jYNHA0lWiJNdY8uBW5jVz75DDg66K3SHj7px0pxAi677MIaFcoDLrsL+cBNyDYA3oAScQwcT3CXdYC8J5V4g8bh3n5jtBoO+iFzUrWBod3P0Ix7HQucqKJn7qDezJ2thzzgBsDAjCUWuGqgPZghLp0wcWpIAn3+BSLvDDjqo9xEIjLAUQu4c0j3HCIpXgxcB1I/aCo/Bc6NUXO0+VIGx5vi/Qk4vexY75bYQj7kAJfdhXzgdijTqRlwHC9Lrst3qgwcT3Bf5UVA/9l3Sg+vQNVRcERYN4goeARWx/fnpEhU6kosyDZCNPaIinV5OjwBzB1UA2i5gsRtLQZKZ8A5IcoNh8i9k0BbH18iWhXJ26+VtBYTKu4QTQskBi2lwBlwUyBBj7LAFVpA9HjjOaXxCAhduhg4H6gMSNxM4qifD5y+0uWzQ6IdHnV3gb5HJPSFmn/tcO+Tc7tQB/KAy+5CHnBb5aYQdhLFlN5LgDlxDBxPcF8UvAKABIBt8WhTDCSzKoCtUCPJCECSQM1ENjcEZCWRGB0wMubEJ0E2AKJ1iHgFNM6AoyaAsBIBjxVM9PF6F0AkAbREGhMKEkCuQwBdygHOiQC4KeB008heWc2ly4GjtgTCCIiGm0+BE3UAcSUGWg6p7oB4t9ucLpSCKoBqDOV1LnDZXcgDzpVAVIlKpBIAHAaOgeMJ7vJEtxYCCMtNMvkbxULSdUhVmCQAUFkJSnWzBIDo0XlDQscWmNEx5y0CIEcDEaJzDhw9rNU5m9TH4ggcPdcUR6sUJiq/FQJAf0h5wNEBqNEZcBQcEkXcrCPoQuB0q4oE4lZAnwCnun0FIGttOwv34tN3EzELUMsurygPuLNdyAOO5hXAfu5WeLeSgWPgeIL7Rwl/7gtK5/jzYSAyjxgW6WPeYF9y6NMc86T8RNBo+PSh4mBQzD1Xae8WvnFhw73r0T/Pm1/wasXB0Mleb2NQ+LjsubqeS3ch/2XsA+4h+YdtMXA8wXFXmdhhSxwDxxMcd43d8n0pA8cTHHetLbH+c9/ADBxPcNxVV5LoEsfA8QTHXWMHhB5xDBxPcNw1th83iGPgeILjuD8sBo4nOI672hg4nuA47mpj4HiC47irjYHjCY7jrjYGjic4jrvaGDie4DjuamPgeILjuKuNgeMJjuOutr/YrQMSAAAAAEH/X/cjdEQkcA4OtgTOwcGWwDk42BI4BwdbAufgYEvgHBxsCZyDgy2Bc3CwJXAODrYEzsHBlsA5ONgSOAcHWwLn4GBL4BwcbAmcg4MtgXNwsCVwDg62BM7BwZbAOTjYEjgHB1sC5+BgS+AcHGwJnIODLYFzcLAlcA4OtgTOwcGWwDk42BI4BwdbAufgYEvgHBxsCZyDgy2Bc3CwJXAODrYEzsHBlsA5ONgSOAcHWwLn4GBL4BwcbAmcg4MtgXNwsCVwDg62BM7BwZbAOTjYEjgHB1sC5+BgS+AcHGwJnIODLYFzcLAlcA4OYtcMUhyIYSCIRDNIRv7/d5d1Qg65jo2GUNVPMBQF8s+C4LYW3BU5SgBwixoZF4J7WMHFFABsYgaCe1DBRUmqmeEGADfwyFmSKhDcQwrOhlTTbeGMsRv7x2dJwxDcEwouJOVbbhQcwB0+lktJgeD6Cy6l4etdKDjG7u6jOR9SIrjugpuvfKPgAPYV3CKlieB6Cy6l/GQbBcfYnoJbSykRXGfBxfIbBQewv+BWwwWC6ys4e/UbBcfYrn2fGgzBtRXc0DCj4AB28W25oYHgugouJH+/CFdUxvYXnLkUCK6p4EppFBzAuYKzVCG4noILlZlTcIydKzgrBYJrKbipaRQcwMmCs6mJ4DoK7pKcgmPsbMG5dCG4hoILlVFwAGcLzkqB4BoKLjXXG/APjrGDBTeVCK6h4IaSggM4XXCpgeAaCq4UFBxjhwvOQoXgGgpOcgoO4GzBubmE4BoKTjJzrqiMnS04Q3BNBWcUHMDZgjNHcBQcY78yCo6C+2O3jk0QCoIoirImi/J/ESIIEwn2X5zBilawwTzOfQVMNhwpNYIjOLPcERzBSakRHMGZ5Y7gCE5KjeAIzix3BEdwUmoER3BmuSM4gpNSIziCM8sdwRGclBrBEZxZ7giO4KTUCI7gzHJHcAQnpUZwBGeWO4IjOCk1giM4s9wRHMFJqREcwZnljuAITkqN4AjOLHcE10twl6pz7O6oY/w6q65DahnBNRPcbc7HbtiN93z+b7zmvKOk9RzBNRPcenB7Ww/u23pw0oe9s+tNFIjCcA4heUHRCWD4Kk3XaCSaukaTLdGEbLCx9qJJ//+/WeEgWNfutjdVm/OcC5EZhrl6+9Bx9CoRgxODe8fg9m+i5fJGDE7qOksMTgzupMHJCq7wHRCDE4P7t8Fpspgrdb0lBicGJwYnfFvE4K7f4LSfIze0e36r7m++dhPlxBZtljnxSNawZ9vdB5MGy8f6lGOHbv5UXbXvMzPfGBxNlkuLdgyXfdJW90m4zsdvZ2AMXtwwWcyMamDT79m7Xr9IBFBKuwSFE4O7YoMz7sGEU2ICGyXeKoKikh8hSmw9xohKZh6YITG3VZ9E54CrmAJj2tGF3+lWA7/SARMbjNuigrECE9OOres+kyB8FDG4S+U8BqflwO+5HgxcqA0HTggvjsZzPwyHVcANAPU4nUQpkrQKry3g/gj0eQ7MON8ANVwFP3IkTm1wbwJuu8biYRO82vCCZg6WDTuOrMAPcVdO2UU2aFv9JVAk2x3gi8NJicFdPWcxOC2FmlOBuYQKijMO1BOrlOtxwFkKGQ+/Cj2MqtjKTSp4BvrFwArrNiedh9MGB/hU0PaQUs0jbKs6QKe4K6ATz8PdB5wgfBgxuAvlLAZ3AzwS07Gx4EB6qLOJA24I/CJmWIVXF7ZJTA8OEfnADTExThsctsQs4TRzSNdDKtH5LnOgRQVBmnaIJtOpLgYnJQZ39ZzF4FLYBlXM4FlEv6HqMz0OOBf3VGGGGHEYPVNFVCrXGov6Ht47BqcTs4VNf2OwCraBWJZghctADO6qDY4owwv327EBVkWodeszcRlwJuDzmfKCEYfaYFzRB57IAIb1Zet3DI5qDbTp6E+kPn/IgVvaMQKyWVu+DEXqAkoM7soNTiE+bHslSpDur6dnKNa1W9ozwoiKhjf0Sa+Cs+T+tMEteVAOuAP0h5cQBXybzj12JNsxCcJnEYO7WM5icCFi7sYB90xkI611bQbFD4239aklRmUDVNLws+jTrw1udNrg8pMGp21DIMxyv7/PUW2el4EXG+JwUmJw34WzGJyLHu2ZAxGRgy4xR4+oDD9+9oGADunw0gTjnDa4/KTBbeH9/mUUTQeiaGz8NZCSIHwWMbgL5SwGN0JoUIVfRtEdlNkklaIdCe7rIOMFhAmHUYOmmjgy1EcNbodZJ6PxdkxtC7RF4aQuQOHE4K7W4CKgT4yZwSGiVfXBET5ULHLY1L7FdpZhbRAziaZElCJsEfOKTxjcDWDxEYem1s1u91kqXyQnfBoxuEvlCw2uwegh/MVdR/BWfEZNqWCcVAGn28h0zsOwCq+ojsGJwgMH1R3f07LxCYML6ofdlA0uh2Nw4HpYEbXa7Y54nJQY3NXzVQaXBjVjok4Ge6CT8XQHDLiLCy9etX/6oUqhqGATFlu1xlEKp4vRXtPuLKJWlFQulwLdwKBOX3nd9w2OtCODMxS6G4NonHs8gScPoyKsxzm8luxkED6JGNyl8kUGd4hT5FkCwA3RPJm2FUpU4ENRSeRVF3TqjfQ+ALUGkLVYuO4BhAng9eP6Nxn+t4rK6xVQjgIeHZ7BDPDWCxvAq+xFlRKD+y58kcEdBxxZW4Udvajp5DvK7j12DlRr/DtTyaJvUK/Oqb6DHfbMJEZ7dbHjZUPxv/4Hp3HANawy7Mj6tETKvrhAQW9FshdV+CxicJfKlxgcncLQb4JO070hx4KOsA92NbSCjaXxdfxi8Thvbs1o9cvf7Vprs7HosKPZfppUE5IdDVIkn4P7Dnz5L9sfJxofmAcjZYjLINNbVNEBItLeDM5HR+NodOIdX3fcftTxrwnJlwMLH0YM7nI5xy/bMxoXHzTLmrQCItrx3OzIjxFaTaZxNQZXHxy1UnMDOtFetx6PzC9icFJicNfPhRgc9eBOqGBqY8napvDCT4zPHmb0b4PTxOCEb4MY3LczuD/s1jFKQ0EYhVFmmiEwxEJIDL5CCWhnEZD0Bnzuf0XywiOkyArunO82w7+A4ZT+3Np2ukzb1j57ufZ7aIePeX/+ae1UC8HZKCO4PMGVft61pd28KWvfp3bt6VgLwWmYCC5OcMuxv1+mv69+/3G9vO3n4+tmuRCcjTKCCxRcLY9wtkZwGiiCixRcvW093N4EZyON4MYRXCU4jRbBERzBWewIjuAITrERHMERnMWO4AiO4BQbwREcwVnsCI7gCE6xERzBEZzFjuAIjuAUG8ERHMFZ7AiO4AhOsREcwRGcxY7gCI7gFBvBERzBWewIjuAITrERHMERnMWO4AiO4BQbwREcwVnsCI7gCE6xERzBEZz9s3c2XGkjURg+NzCHhA/RbhEKaiVABSmK4idQoBY/AEH//6/ZubmTmTTNsXp2z9aw952zdZhMZpLUPPuEBLq2hQ2ODY4NjrO2YYNjg2OD47K2hQ2ODY4NjrO2YYNjg2OD47K2hQ2ODY4NjrO2YYNjg2OD47K2hQ2ODY4NjrO2YYNjg2OD47K2hQ2ODY4NjrO2YYNjg/uXDA7Y4Li8u8IGxwbHBsdZ27DBscG9aHDwSoMz+XMGB6yKXEKFDY4N7kWDux+Pn35vcK3Lv1Jny08f686fM7jKeDxOAofDBueHDe63BlcQYg9eNrjswUz46S1rf8rgNuT0++xwXNjg/LDB/d7gEHAvGpyz1SO0LbquV5mm4Y8YHAGOw2GD88MG948N7nwghJgc1BxsaX15lq8WGX8hGxyXf6Owwb2L/C8MLrS8Kpc3bmzQqU2EWOXY4DjvI2xwbHD/wOBKbSGat9hiO0DJrYSYAr8Hx+V9FDa4tTY4eLPBUaINLmx49kCIK/y58ZwQ3QMHLorFUqYtGsnXqBsbHOfXsMG92/x3BgfZ/kU5iYsjsKNfOZXjahbCV4v27XFH2RbWT5zQ9SmkyxcdR7cFDS4wL/13LUQ3B5BsCi/PLfnHD7gR4kAP6dwd77aMyoWhrDb7sFY7tCC8561aNQdesL6bDq6qxi7LxiiDA7tUezp3og4gLrmzg0sAkuWLkzSENwCy1acM1ajOfhi/wgYXO4NLnw4EZvDowanU7vXah+DFWcl6xWPXmDol8nTiQqfX6xUhuVWQje4ZnreH2wmsD0vg5avskIN7D1bu/CRgcFHzYpy2EBcAyQXOM5I9z+SaOci6/irW/Z7AtLdagMnLKfJAuZT1KWD2N13s1BjeAqWLvezrCbauyjjRxsKbuAYYtSvlpbdasxhhcLvzHi7rXZUhlNKnAi4pTM3hzvzVVfvl43TZ640AfniHojvGlp2Rtx/f+UMZMQsbXNwMDqoL4Wdw7p18eJpT95SsfsdKcqY7FfqAOZHVeqcrKIk7eCqoeq+qAZGeChV3HAJceF6cmC5Qr2TvDRtsb90RAkpMAJNsmo248IiIhHwAzLmE6wyBYi2FnvO7nnM7rde9hMOBXz81u/LZFSopKwQ4e9sM+fHnYzhuCJVFXx3gekLoNsXDoQSrlRcqU3D0Np6xxMWrsMHFzeAeXORFc7qHfGp7ZoRk+YiVoqzM1Tv9MrOrsy7iyPapcF3A1q4HopqL9YXXz/EBMcWxBwSB+wDgouddCnEE0JevHz2u4GAHstIUDc+McKLG6mroTeIR7lbCpJvGviO5qKM2XrYt5wNEbcmfMzVC3kxcZLFH5e4M642KvytTfDUgRqd+BpzlaeNMDunSBlGoD2bSbOPadRJXQptswrYHDbgtcyiKm7gZgx7hlhOnsMHFzOCSbTyjkUgOnuN7vhg1TgBwGcHqVC76lMRFc1n77FOhISb1LPju1h4nlZfdm5MfL1jt2gQXp4OAC89Ly7oAIGdY2OCz6gkARmLhc6aZAZnrhhwu6dvmEgAO/M06wk6eED4SnWnOhuhdlwBKK+VhFYAWjpeiXcHMdi2A802huGYA9xcCy7PSGqKxZo7iLhLv5lw2jOUcbRu9FJvmWXTKpsCtVIBzXZHvW5CbCy9XVRucTzgrK1y8ChtcvAwOIfIBKFd0+gJUetLTHNiUDtQBjGTBCrykG0EqLFrgs0S0qWsdLUcD7hOANsBvGnDR8+YkDgFgoNfakmBCBLbFpmLZptqDSwSL3v4x7Ls+zG4kS7LgZSR3ggBnXKrj8W0HMK2GZKHelVGODpLCrQFcyyU4Y25dXKgzMEaHAovD4o5uqOONMJsS4PzdB6drHNGS67s2cGIUNrh4GZyTkJRygFJqqBMSxsimU3MFVXt4qABlRqc4UeEOgLSJXAuTJaciQLT9oWsCEakBFzlvxfvTli++UPsZ9c0h8TzIuh2gWHIrJuDbZqKz8FUTjh4eqobdDcsH3FfAUP3A8Kmtd6UMlLTs4aYDgPuG1+JgxhQt/zCW8U6vBZQh0tJrWvlNWTlUwlGAOzP98EjotzgrrHBxKmxw8TK4ohEp0o+ZPpExV7+slnOpD1EBDNSEDZSGOpk30FpofdIpkdWAi5y3KkQe4FZj1VrQAF88N0ojTcAPXt0lQdkmhlTTAhNnSFMS1M4Nn4VPwGcNuOCzK3m6xibA0cb17ODx2qEq9bzWv+ZHRx2zMg5FF851BbXvAahtAeWDrHeAE6OwwcXL4NDSEnM/+AK0GJEV6Vj9r6m9rtdsqGAAN6HRfwZc3V8XcOwjDbjIeQ899ctpAFyqK+aVmNnKEoNriD5o2yQmaryVLvPDiSsCgHNpKwhwdgTgPuFiPe1pAHCF4Lx0BaoO55BgaempqelWv9zB3qq1EgDcjyDg2ODiVNjg4mVweRGOYloZ63fm77J/VhAqBnB/BQCXggiD6+hpb+SrYw24yHkt13tLrK3e8rprk3htECd/iFA0JpBkA9C/cJnUQqgYwDV96My8vmCFAfeoj1ANCWsA54hw8oAhK3UdAI040j3XVkPRDeFtApxLbQS4NBtcXMMGFy+DC4HG6M2ZIPug2FcC486GW0HA3QQAt02DBwFntMXybkU+aMBFzzsRvRwRYDKufSsgUWvONWEvDDg1HBBFCIkWPV8sMIvn7TYBTs/pA24FEQZ3rVYnwB28BDj6WIUGnMEbNYmcfvmEaqgBZwwuxwYX18IGFy+De8TrscNAWtR+SkCrBkRvcN2x6RSOBlyUwRX1tHMlKwibyHlplq/01jymsS8J5SaE2Mz59z+Hh8EQitPka8PAm2Ttm10Uq60Q4CwNuAiDy+sj9JluSQQvUQuHweQAzP8EqtrgdNOTHuqjf4kaMrgcG1xcwwYXL4NDL/oAJtTHe+wCH+pdpAFTwjujlnKUtxjcRz3kCs9rDZvIeaHkions058ImV4d6h5kU7a+u7EZ8euGz7JM6RoTI3E3SVN16y0GZ4bOE5g14EZ0kyE8r+p57ePNSeIR36KdtgwBi2xw61TY4OJlcE6BHqulpLNZB2SSXbzB8KQfbrgP3HoUbzG4rgPmYq0ZgE30vGf0pFtuJz89RTSVP6TqaVCRJHPvQCWXzRIlvuENBqspha9MW2KoOnqDwSFoqDmdkGM5GnD087s+XtksDmnep9yzgDL3Bj4S8ocDlBbKn8MGt05hg4uXwcF24K22r+qNLRt50aFnMb76rCrrG4NvMDhxEHjQ99HAJnpeyE6kKWajf6k8nxta1FLtqaEf6Anfw4Lw5A9ODOBuxVsMTuwpLE0J6wZwSZe+4wSTnXmczlzKOD896HvSkKBVVF2qncbFKWCDW6fCBhcvg4NsF9+AsnHxGE9z/9rui/+RrT5iBM9aB9H3pfEWg8PVkqg6M1mbOBo2UfMSlOTiNqJDJXmdBwgonHhOenO3pRql0ZHaCmxjxRXHlQ0ZkDleCJnkaw1ONqNLZYaC4G4ABx9x48kPR/TkypMaetdFnrYAoNhWTzX3G0g13LbSMypsFtjg1ilscPEyOAv28Yxsb25vJvB8rABAXV+aHjWIHznvw+TN1LAr3D3Z69UGt4ljjgpCxq1BEHAR82LuRjjTcGP8VK2f5psSIHf6lyqLyOo1U8suDlf3P2LfB8xSQRlnFIPpmQQZAub8dQZHnQujrsB8CH3YfojzrebTGT0kYgCH7MPpNhe41TtaR0VvNFy52FYDNri1KmxwMTM4gP5C+FkgD84TdHPBl5clXQlS3Gv8gKj9WoOrzYVK4hg04KLnVQTe6Ilg2vWAbe7p5kbRh8UpeEl36QsCMm2hMi/iBkQbnAVWCHA33wWG+Bb+uqR88BmRIODgsiFUulWgBL8uqQ/ABrdWYYOLm8FZkN6Y0On46NB1qXk8xGqqd9jLxJbmMSAI7l5rcPv2Z7olmipBGHCheTXinPulj4j2/MI2Gy0rO02iZT7jvx84BJUHQV8I15p6MJ5cwzm+hfhag7uBJ29sd7gf8YWX+8uGt3DZh58BB5WpB+TePKN/5Q+3CLKzjTQAG9x6FTa42BkcprV/v58JdQ51z1bvay3Qie6m6wYQVqt2XHH0/GYtPW/Ev/OQPDq+3y/ZekiTbLn+ULJf3IbcSf24ohtCc4brBnA49o+TXHixqjqdYtF88zpFL6mXvSW6zT5/ut9tRc9q6vxtvjEMG1z8DM6caMF+5oduDLeYRrOyqSvAhVcMt5jhzPqhTi9uqhXehuCq0XOG1yDAhfuY0cODRm9t8F8Ze83M9JP9LV6FDS6OBvfr355uCJPR0MgU00vXtcGFV6RXoXpgVFMN88K0hTuYbYgaP7LNrGEMzrQHF1NVl+Ci8JIwkbH2Yp01LnZhg2OD+8cGR1U2OC7vr7DBscH9SwZnscFx3l3Y4Njg2ODY4Na2sMGxwbHBscGtbdjg2OBUPbO7u5uLhcE5cktbbHBc2OBeDhucqavEwuC8sMFx2OB+Eza4X60kBganChscFza4l8IGxwb3N7t2tNo4DIRhVDZDkIz8/q+70a0ppstayDucbyBQWkIo5OcQQnC5IziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpIziCIziCS3sER3AER3BpI7j3CG6/6IDgCM49LrjdwC0RXI9KcASnbaLgxkONbuAWCO6IRnAE52YLrsVh4BYIrsVJcASnbbLgzmgGboHganSCIzg3W3A9qoFbILhPxE5wBKeJghuPER8Dt0Bw5Yxz8z04gnNTBXfGWQzcAsGVGp3gCE5zBdejGrglgis92uYzOIJzEwXXohcDt0RwpUbsBEdwmie4PaIauEWCK0ccm8/gCM5NE9wRRzFwiwRXtohGcASnWYJrEZuBWya4UsfCERzBuSmCaxG1GLhFghu1iEZwBKcJghv71oqBWya40TkWjuAIzj0uuBZxFgO3QHAXwx07wRGcnhXcfgy/GbilghvVGIjzPTiCcw8KrkVELQZuueBK2Y6Ifu4ER3B6BnD72SOOrRi4FwjuW+0xNm78P28Bd/nxVnCXLn91ee4bwd2b6V5wox9e728Ed/dKf3iOX/3q7wW3Edz/ddt4Q451i/7lm4F7heBG9QxJD3XWUgzcawQ3+tR29JD0T/Wj1e8mGbhXCU7SuzJwn2LgpKQZOIKT0mbgCE5Km4EjOCltBo7gpLQZOIKT0mbgCO4Pu3VAAgAAACDo/+t+hI6IYEvgHBxsCZyDgy2Bc3CwJXAODrYEzsHBlsA5ONgSOAcHWwLn4GBL4BwcbAmcg4MtgXNwsCVwDg62BM7BwZbAOTjYEjgHB1sC5+BgS+AcHGwJnIODLYFzcLAlcA4OtgTOwcGWwDk42BI4BwdbAufgIHbrgAQAAABA0P/X/QgdEW0JnIODLYFzcLAlcA4OtgTOwcGWwDk42BI4BwdbAufgYEvgHBxsCZyDgy2Bc3CwJXAODrYEzsHBlsDFfh31pgnFUQA/KCcToxVUqtHWZSqTlnV1wy0uNlSndVGs9ft/ml2UVB5NxMTU/+/J6JF7n04OsuCE+LCk4I5dcPfzWFPXcKzOZHJzYEoIIQV38gW34V5wpeEor2T/wJQQQgru5Atuw6SNIQUnxNmQgkthwQWVSG85IjnSpeCEOBdScCksuBJiXYcc4gj1RuP7gSkhhBTcyRdcsuBQJZ0chBDnQQouzQWHOskmhBDnQQou1QWXIdmBUrgKvLYXfCtiyzLNBjotz3kBTNPMYb4ct8OnBgBjFdj+2jIQuTHNCiKZr25f/b+Xx86jOXayo+FLMqVo/6LvF7MGEucUy2v1xOsidvKWukroTjIQ4tJIwaW64JokfwF49rkT6oi45LRK5QEgadS4s8I8TAYrpAlFD7njT6FoJmO9ZArGmrGB8X7Orc0t7wcib+9XuQdQcxynCiEuhBRcqguuRGYzQJlkf2ANPHJciIunxH3BffHpux5J5zFLhm6bpJmsroAcz/7MxqT/AMAi7ddVaU3ycyJlBFS5QcsmuTDic8oOudj0SY4yAHSbDKzV9ioq0qVKQIgLIQWX4oLTfpK8Bm7b5DAHoPhEjqIPLpXB252hASRtv5aBNnWotOpAYUZS31fXnYoUo7u55CcAYfzi2yMXcSruN+83AO1vm1wC8TlWAdBUhtFvz6QLJW+TXSk4cWGk4P6zb7+9SUNRAMYPyCNUBw63CSoif5yCiJK1yCYMa4Q5QZjf/9OY21tajDVG0nc9v1fLcrKONHly4NIUNjiKxuJ4BPhlkSb0JOAMoGHDE3UFoCXGAuiZ/knpHG7jdH2EphhLz3skUgLXjq08z4mmKtC5kUAFGIfXeWNflg+ndqe8FuOV501E7nzffy1KZYQGLt0nGbZ1kYdAW6wT8MLw5MQC/DBL8aAPn+PALYFJTiIDKJbFiqd8KIqV86EaXie8lZtgmZTXMGqJUtmkgUvxWVT3Z1ClGlALbWBqwzOXELZFNj7kJTBlP3D358Doaa0sVhVwV5P+b4FzgK8SWkDTXmcb/8YE7ugM2J509QxVZZEGLoUNzntr9B2xrmDfwIanKiHgRRS4rSQFTurfMTrHNTHyMwLbH/k4cPbENnQBvr3Oye+Bkw9nGO6lPvygskcDl+YpqnWRGLiKhIBPUeDmyYGT0uPvBC5zYjR6BOaFaGq4H7hKFLjKfuCMwpMBRuedKJUxGri0TlFj34BC7OiAwBnLL6vB3tnEUaPoA81oqgw0JORBLyFwVq59OjsHXohS2aKBS3+DWwJ9iR0SOCt3Cvck1j2H99HUCJ5KaA3FhMDFHA9molS2aODS3+BkCwuxahcXN/8fuO3aL9vCDaAgxfX6NlrUGtFUFc7GEvgCPEsK3Hi9Dov5HHxRKls0cOlvcNKATmP3k/vg/wO3gaoYpXt0SiZfvbwYTehGU30XfPPX5a4DPUnc4EZg49gORrrT6fSlKJURGrh0NzhrBXgvW69XHagc8Ba11YHjynB4NQ+q9GAUfNOj3tiA60RT0gDc2dXJHDh7mBy4x+CuJvXW4xG80ScZVMZo4NLd4Kz8gp3rgz6Dm7AzeCsiw3vs1KIpM3ZOyB9KcuDkkp1eXgOnMkYDl/YGZ31tYhy3DjxkGG46AG6xL8bRI5u4WVuiKWO5cAHW1478LXD3a3OM0akjGjiVMRq4eINLV3l4e+PI4XL1buttLv43C+27cUn+kB/ftR/+4+45z2+fFbJ7h3+xd8c0AAAACMP8u8bHaEUsfHBM4DzbQ5bAebaHLIGz4CBL4Cw4yBI4Cw6yBM6CgyyBs+AgS+AsOMgSOAsOsgTOgoMsgbPgIEvgLDjGbh2cMAwEQRAUwhidUP7xmgM/HMCBRauKjWAfQ5Nl4BQcZBk4BQdZBk7BQZaBU3CQZeAUHGQZOAUHWQZOwUGWgVNwkGXgFBxkGTgFB1kGTsFBloFTcJBl4BQcZBk4BQdZBk7BQZaBU3CQZeAUHGQZOAUHWQZOwUGWgVNwkGXgFBxkGbhVBbeP85rOsW/ALRi4JQX3Htev8dx3wp0YuBUFd1zT63vTsQF/92HvjlvaBsI4jj+px/2SmDY0LVdTM2ppMSi6sqEWBSl1qx0o9P2/mzXLXS7G6iyZMMjzYQztRP8YfPkluW4cuH+w4Dydt4z50CPG2P44cP/bgmvruon8l/6wTbtJITyy9vvBgRBCUpkjhPDJaq3Gm+F1q/TjtMAhxpqGA2cXXJ39Vl1wb284B5iRNUVMH3cP4JjKJgCebWtHMTLhPKCcB0NFi5Pm/jWzZuLA1V1wbhBUF5z+xP2cwM2prF8O3F0IoBuFAOKJDZx1y094WaNw4GouOGnzVhD6E/kJgUsRu2QJqHsTOGcB9CbZn3onXWBjAjdxMq1gNVKI+N4gaxIOXM0F59mL0uTq6eDpKrHXqd4nBG6g8IWsKW4vTOB+AadmobnPUMc6cCdkDIEpMdYcHLiaC85ut58HuZ92z31C4DZLdKggU9yZwLVDLKUNb4pI2sBpt+gSY83Bgau34FpBxvTNFE4EudYnBO4SsOF8ROiYwC3R9ci6A45fBe4G4BN6rEE4cHbB1ToClxxYibkP5308cO5Npxvfj87JOF/ch2G0FtXAOV0MyBghIR24Q+CGStwY01eB+wL4xFhjcODqLTjfXI1eHVhXgeZ/OHCii1yil+EcOfVYCRxNkUobsSMTuDEQUNn0dPAqcFMoPg7HGoQDV2/BFQ8Ung6sp+Iu3EcDJx8QfRHt4al++Ol0gIu7QAz7iI8qgTsEVsUg60kTuCl6VFUNnNtDnxhrDg5cvQVXPGI4KMtf3SNwQs8vGeWZGgAzSVvOCGHwMnAUYU65Dm7IBO4W3/8WOG8JjImx5uDA1V9w4nXgMmKPwF0CbX3nbeESuTEuTJRCTCuBm5ijcAGUXwQuxfyNwHWGf/xKQmBGjDUIB67mgjOql6j7LbgASCQVxsAZaQnSSuA8cxRugO9UBO4ByzcCZ6khMdYkHLh6C87XW636kEFkL+/xkOEUiDbCRg3CSKCcl4EjfRROphjrwJkXdwfuIXPfWW74CSprGA5cvQXn5S2rHBN5799MkiEGpNmB5t1iK10L0rkra1cC9zW/Y7dC6NrADZDKt+7BMdZQHDhJ9Q/6ispBX6NFO0QYkWbzRPJyGWMrcYjoFuiVeJXA6aNwC8xL3+EOOKeyee+UA8cajgNXb8FRkKu8VUvk0aNdluiT1UNCmnP04wFYEFGCUFKVDRytkUpqhViVAucrTKmkFWPNgWMNx4GzC67ONaoov9ne8GiXAWKfDKGwIUtOAUE0Afz3AncGrGiMVJY34BqxIGsIHHPgWMNx4GouOKkvUS074CTtEigsSnMubBPJTjTWvVQYZr/bXbf6dlgNXH4U7hkDKgfOTdF3yfC76PA9ONZ0HLiaC45c2zTzkebSbmso3Ry50W8gHaHvUMZV+JZ/yXXx7tHz14HbIDxUEDZwerNFPuVEhPiIA8eajgNXZ8HZi1RD2Np5byaxC5w++k7w9RnoObS1Ulj6RFIsodpEJJdQM48omCjM6XXgPIUUfSoCl5vEiJMjT7ZXawUM+SkqazwOXI0Fp7WLponSgmvTm9rP2FLYWuoMbgD18L0LYEIZ5wJAmgIYOdXAmYMkJzZwmoiKb9y95GMijHHg6iw4u+EMYffbO+SkHwIIO0Myrp+R6XylXGuWYiu6k7QrcN+A2LOBM5xZhMz9zONzcIxx4GosOMs1WSu49BfSv/YllbXE6tB7+RXnHu3NOzs+4/944Td7d4wCIBAEQVAMhBP//14xOoxNjrbqCRs0ky0I3NcFNx3j/fX5v+eElQjcXHDf7OO8Hufwmg8WIXBzwQExAndsAgdRAmfBQZbAWXCQJXAWHGQJnAUHWQJnwUGWwFlwkCVwFhxkCZwFB1kCZ8FBlsBZcJAlcBYcZAmcBQdZAmfBQZbAWXCQJXAWHGQJnAUHWQJnwUGWwFlwkCVwFhxkCZwFBzd7dpCaMBBAYXiSDMGERKTQfcGlGzeu2h7A+1+o1AuoUMj0+X1HmJA/j0wsgbPgIJbAWXAQS+AsOIglcBYcxBI4Cw5iCZwFB7EEzoKDWAJnwUEsgbPgIJbAWXAQS+AsOIglcBYcxBI4Cw5iCZwFB7EEzoKDWAJnwUEsgbPgIJbAWXAQS+AsOIglcBYcxBI4Cw5iCZwFB7EEzoKDWAJnwUEsgbPgIJbAWXAQS+AsOIglcBYcxBI4Cw5iCZwFB7EEzoKDWAJnwUEsgbPgIJbAWXAQS+AsOIglcBYcxBI4Cw5iCZwFB7EEzoKDWAJnwUEsgfu7BddP81JpwzJPfXnax/fX52mgBafPr+8PgWtlwY2TuLVmmcbyhPntOtCW69sscC0suOn2Pu261z3Htozd7vbFmcrD9qZbi057gdt8wXVzrXNfaEv/+1i68pDLYaBNh4vAbbvg+lqXXaE9u6XWvjzgeB5o1fkocFsuuL7W9XXPr23j+lDhju8D7Xo/Ctx2C66rdS20aq21K3dc7Le2nS8Ct9mCm/WtaWudyx3+v7XuIHBbLbipLq97eP/BuNy7S93/sHcHKw0DURiFZ7w3aRJikaxddOFCDIq4KrSN4qKgSPH9n0bpAwxtKMzc2/M9QkNPf5JpKyjdksDlWXC1Ks8Xytao1iGh43xI+caOwGVZcK12AWXr0hNuEJRvIHBZFlyvnH8r3Y32IYHvL1jwReAyLLjjewelS34KrQQWrAhchgXXahtQuuRV2gks2BG4DAuu4xGDAU3qRulWYMGWwGVYcL3GgNLF1I2EjcCCDYHLsOBUr/eVs6NOXV0OidgwErgMC44fAjYhdZkENhC4mQuOwLlH4BwgcCw4EDi3CBwLDgTOLQLHggOBc4vAseBA4NwicCw4EDi3CBwLDgTOLQLHggOBc4vAseBA4NwicCw4EDi3CBwLDgTOLQLHggOBc4vAseBA4NwicCy4mZ7v334eXsJlPe33xfwfj8XATevvg5xonKaDnGO9WPyKMQSOBTdHHF6ro4/PJlzQY1UtQyEMBm6K/06t1l2Mt3IOjfFdjCFwf+zdb1MSURTH8fvjcGNREApWSAETJDfI2hQRgVYcQQQEff+vpsPd5Z8hkvRgs/uZqbuul21snO+cdWPSE5ywEmJRISFWO3fkVOtQB84vTsF2aDWrQUwHTgfuP5ngElImnp6wxCoXZxw252cmc2zxwdmeDpw/mEGwbZNW2L1FhZgOnA7cfzLBFeRi4RLq4xVO8lK2vKrdtaQ0IzpwvlABrrNAhVZI49WBcyzrn/u/KHTg9AS3WDT1kbXyi3ekHG0JT9qUMqQD5wtHQC4EHNEKTwL31unA6QnOK9x6fWPXUhbPxVRXynxEB84HBgbSZBswbHqODpwO3P83wXmFW6tvrCxlTMwESMquYDjItYrmqF0SSiYePxC4ssr51rAjPMaFZRdH7QsIT2THKefLzteoDtzGYsAHohTwkVyJarVNrstqNU5UrVbBeDmdBC5+lDZKdxWaaCTrEaNU2LVJcarVr2Qn98NXRDvV6pCIMtWZBo3FM/vh8P5VjvxHB05PcNPCrde3CG/5Jubs9npJXr7Z0lW8nFwyFhxJJX8glK2edFkRoVydSdcgqAO3qTowIhoCdXKlgCS5fgA1Ikxl3cCZV3BdkKsWgCviNo831QdpqPveAvCeiLYxYxHR4AGeBPmODpye4GaFe7lv7EFKW/zuS5k75sTaA172vSuGWrw3Po7aWVqwaIMPyxWryKfPBfsg+ajyvsKvbUV04DbjAHu8mFuAQ2xJ4DqdDhgvXTdwGf51d2gA6BNTfYtmuycGEGgTuYErYCFw2Y4LgNHgvpV4b/byMgsgRn6jA6cnOMVt24t9Y6dSOuJ3MU5VmNcAR63vXpA9jjv2Pe/e1IYdzludv2u2R+6eLH+iZozL15SyYejAbeTeC8wBcE9sSeBo8WdwLJ0ziRp88pBY3wAyNh+MvgHh0WRTcNexy17gptoAjnn9DgTjxIZRoEY+owOnJ7hZ4V7uG2tL2RS/i7daN5PrjLxV5ozJS+K8JKUs7omxOh9tCZGb/nnhspQZHbhNmEEYA2KPQNAktkbgSj0aq7nPG8wI0CWlvA1kvE3b6rJPAueEgRtecwAeSTkG9slndOD0BDdhSSZeVFO1et6elDQJ3K1QPkvZ4KUn5a5w7QyHBbHNOw5nea3owG2iAnwnpQQMia0RuBgpIwA2UR8I98jV5mPb3dQmZSFwdgdI26Tmxe/kKocBh/xFB05PcAsTXEK8JKYmtOWi2euPtpTFyfW875CMClyYT1yJOSk+kfIMeYsO3CZSbsJYEkgRWyNwDiktN3D3wB55BgBy7qYGKQuB6wKGRawOZCseAEPyFx04PcHN+matUzgexwgLfxlMsL1QTyrTwFliPnD7aqSbcykXlHXgNjAAUNpXAHWzukbgDJPYNHBdIEMTW0DfDZy7aSFwMUz+MUoQC3bJX3Tg9AQ36xv//nLh0rznu5hTkbIthDGULN9qNmeBiy8E7ht/Pi3mnOrA/T0xLOASLQTuZGngoqS4gVP7uzQRBWrzm+YDZxnTnVs6cG/Qm5vg3L6JtQrXkLIiZgJn6vlAX0ozdAge1J4L3BZf+0jM6fKJ4ExEB24D3wCkPQBOiOYDZ2KdwF0C5+QZAXh8JnB2GujYpNwCO62ZMvmLDpye4GZ9W69wn3hLdeGdW2db4pxPZsXYj+cCJ8pSHgvXSbfbER1+zRf9Vq2/wlGPTj2tAGCRCtwOKbm1AhcCArwobcAYPBO4GyDskKsLXJB/6cDpCW7at3ULV5Oy/EN46kXOlmpYTyjvnw1cTEo7Isai3Dq+wkjd3Cqp09NbHbjX+wrc09Qd8JmXa+CIlKtp4E6AELFlgbPD7uuYfQtUaXngjgG0yVMBjB4pg1gsRD6jA6cnuEnf1i7clslD26UhGE75uBVWT0TzahpLy2cDV+KsWfASabnn85nJjrMtHbhXMyOARVNtIGIS1QBjROwe08ClgAdiywLHmfQaZt4BgTgtDdyjMT+0mbdAYUCsvAckyWd04PQEN+nb+oWrt9RbrmLvm/b4oDT+mvIcsZ93mVBxfOrdksCxH8S7axc7DoetKlif91YOPn3u5zls+hb19YbAPs2Uw0Cfu2UA0fuPB2kEP00CdwwELtq19tLAlU8A3J62M0EAp0TLAmdvA7i+dz0SjcLAdqLSTJ4AJZt8RgdOT3BcImvJiVWMkJzKfRFjP6WreFOUMrIscOzwTLrMBzEWaMuJn/pncBtIAQmak3FvMPsGlKCVmgSunMZYdmngaFCAJ5A0iZYFznn6sDa3Dc95j/xGB05PcIWE9TR5VkG84K6pWpVvHgnXu2tbMutQtKQsLA0c+zHM8yZ7WBKem5wci3/SDxk2MDAQWIhLBTBavA7rBhA+6JEKnNLrrggcmaE6mJGKE1srcDRIBsGCCd/NbzpweoJ7NaNTKJwbYgalwuHLX1n49mFxU/Tk7jYsfOgfCtwKdtwp06Ky08ytaNHAavJL/ojZe3xskR/pwOkJTnvLgfvP6cDpCU7TgXuzdOD0BKf9Yu+OcRSGoSiKvsRfUWw5CCFNj0RJQ0MFLID9b2hE2hkIVP753LOERFyeiFEIXFgEjgUHAhcWgWPBgcCFReBYcCBwYRE4FhwIXFgEjgUHAhcWgWPBgcCFReBYcCBwYRE4FhwIXFgEjgUHAhcWgWPBgcCFReBYcCBwYRE4FhwIXFgEjgUHAhcWgWuy4L73yq3H8Oruenv9J/53JHANFly1TvCus6qnLglrcCFwDRZcsVHwbrSip64Ja3AlcA0WXDaX7yDA+3fplrAGNwLXYMH1VgXvqvV6ap+wBnsC12DBzZ8d+LbwLeTvDaD46y4C12DBKVsRfCuW9cIuwb8dgWuy4AbjMYNz48JZnsJBEf+OhcA1WXDKVr/34q3BUJceBG0SvNuIwDVZcFKxSfBrsqIF2wTftiJwjRacOqNwjk22fBb7fErw7HQmcM0WnHqz6Xuvn2/DZNZr0eEnwa+fgwhcswU3F67ypMGjsc59W3Zgw/l1OojAtVpws66YFc7DedM/bkunt5z5Hc6r7VkEruGCm2Uzq3nsvvc6+jJ0Y65mlvW2DadFPDpuJALXdMHNhlwNvtQ86ANlx38avLnvigicgwX30OdC5LyoJff62P52vTDkfDherre9JALnYsEB8IfADSJwQFAEjgUHhEXgWHBAWASOBQeEReBYcEBYBI4FB4RF4FhwQFgEjgUHhEXgWHBAWASOBQeEReBYcEBYBI4FB4RF4FhwQFgEjgUHhEXgWHBAWASOBQeEReBYcEBYBI4F98u+veU4DkJRFDURQsHA/KfbIXai6keq+pfrtZiBP7aOQwxhCZwFB2EJnAUHYQmcBQdhCZwFB2EJnAUHYQmcBQdhCZwFB2EJnAUHYQmcBQdhCZwFB2EJnAUHYQmcBQdhCZwFB2EJnAUHYQmcBQdhCdx7wV33EUBQReDeCy5tQChJ4OaCSzNw9w0I5T4Dl64duO0ZuJ7rBoRSc7964LZjwe1534BQ9rzPwF25b2fghh/hIJiU8xC4eY1aR/aOCrHUGbhr3zG8r1F77hsQSM/96peor2tUEw6CmQPu8ncMx49wtzp67pd+DBBL6bmPerv4T3Dvbxn2nMcGBDFy3r2hvv8JN7qXVAij5ty9of424XzOAEHcswH3dcLd6lA4COLZt1FvBtyXi9SevaVCADV7Qf1zwp2FG54HLK2Ms28G3KGUL4XrRhwsrHZ9+1y4NhPnu1RYUpp5a/r2qXB7b+24f0keDSykpOO/EK31/eybwJ3Kq3B177m1DCyptdz3qm+fNtwccbNxKgdraQ+5933o24cNdybu2biHBiwiP8y6HXnTt7+8Cnevz8YBi5l1q3d9+6fyStxs3DQcx1nmTLNu8vZJmdLROGA5z7qlom/fjLiSTjdgGelB3n5O3JSABR1107dvEwesa+MHReZgRcbb/yqO4yx1AAAAAH6xBwcCAAAAAED+r42gqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqirtwSEBAAAAgKD/r81+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYALG6vVOk3uGfAAAAABJRU5ErkJggg==) + +> [!NOTE] +> In this scenario, we're simply using OAuth as a translation layer to the underlying authenticatable model. We are ignoring many aspects of OAuth, such as scopes. + +#### Using an Existing Passport Installation + +If your application is already using Laravel Passport, Laravel MCP should work seamlessly within your existing Passport installation, but custom scopes aren't currently supported as OAuth is primarily used as a translation layer to the underlying authenticatable model. + +Laravel MCP, via the `Mcp::oauthRoutes()` method discussed above, adds, advertises, and uses a single `mcp:use` scope. + +#### Passport vs. Sanctum + +OAuth2.1 is the documented authentication mechanism in the Model Context Protocol specification, and is the most widely supported among MCP clients. For that reason, we recommend using Passport when possible. + +If your application is already using [Sanctum](/docs/{{version}}/sanctum) then adding Passport may be cumbersome. In this instance, we recommend using Sanctum without Passport until you have a clear, necessary requirement to use an MCP client that only supports OAuth. + + +### Sanctum + +If you would like to protect your MCP server using [Sanctum](/docs/{{version}}/sanctum), simply add Sanctum's authentication middleware to your server in your `routes/ai.php` file. Then, ensure your MCP clients provide a `Authorization: Bearer ` header to ensure successful authentication: + +```php +use App\Mcp\Servers\WeatherExample; +use Laravel\Mcp\Facades\Mcp; + +Mcp::web('/mcp/demo', WeatherExample::class) + ->middleware('auth:sanctum'); +``` + + +#### Custom MCP Authentication + +If your application issues its own custom API tokens, you may authenticate your MCP server by assigning any middleware you wish to your `Mcp::web` routes. Your custom middleware can inspect the `Authorization` header manually to authenticate the incoming MCP request. + + +## Authorization + +You may access the currently authenticated user via the `$request->user()` method, allowing you to perform [authorization checks](/docs/{{version}}/authorization) within your MCP tools and resources: + +```php +use Laravel\Mcp\Request; +use Laravel\Mcp\Response; + +/** + * Handle the tool request. + */ +public function handle(Request $request): Response +{ + if (! $request->user()->can('read-weather')) { + return Response::error('Permission denied.'); + } + + // ... +} +``` + + +## Testing Servers + +You may test your MCP servers using the built-in MCP Inspector or by writing unit tests. + + +### MCP Inspector + +The [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector) is an interactive tool for testing and debugging your MCP servers. Use it to connect to your server, verify authentication, and try out tools, resources, and prompts. + +You may run the inspector for any registered server: + +```shell +# Web server... +php artisan mcp:inspector mcp/weather + +# Local server named "weather"... +php artisan mcp:inspector weather +``` + +This command launches the MCP Inspector and provides the client settings that you may copy into your MCP client to ensure everything is configured correctly. If your web server is protected by an authentication middleware, make sure to include the required headers, such as an `Authorization` bearer token, when connecting. + + +### Unit Tests + +You may write unit tests for your MCP servers, tools, resources, and prompts. + +To get started, create a new test case and invoke the desired primitive on the server that registers it. For example, to test a tool on the `WeatherServer`: + +```php tab=Pest +test('tool', function () { + $response = WeatherServer::tool(CurrentWeatherTool::class, [ + 'location' => 'New York City', + 'units' => 'fahrenheit', + ]); + + $response + ->assertOk() + ->assertSee('The current weather in New York City is 72°F and sunny.'); +}); +``` + +```php tab=PHPUnit +/** + * Test a tool. + */ +public function test_tool(): void +{ + $response = WeatherServer::tool(CurrentWeatherTool::class, [ + 'location' => 'New York City', + 'units' => 'fahrenheit', + ]); + + $response + ->assertOk() + ->assertSee('The current weather in New York City is 72°F and sunny.'); +} +``` + +Similarly, you may test prompts and resources: + +```php +$response = WeatherServer::prompt(...); +$response = WeatherServer::resource(...); +``` + +You may also act as an authenticated user by chaining the `actingAs` method before invoking the primitive: + +```php +$response = WeatherServer::actingAs($user)->tool(...); +``` + +Once you receive the response, you may use various assertion methods to verify the content and status of the response. + +You may assert that a response is successful using the `assertOk` method. This checks that the response does not have any errors: + +```php +$response->assertOk(); +``` + +You may assert that a response contains specific text using the `assertSee` method: + +```php +$response->assertSee('The current weather in New York City is 72°F and sunny.'); +``` + +You may assert that a response contains an error using the `assertHasErrors` method: + +```php +$response->assertHasErrors(); + +$response->assertHasErrors([ + 'Something went wrong.', +]); +``` + +You may assert that a response does not contain an error using the `assertHasNoErrors` method: + +```php +$response->assertHasNoErrors(); +``` + +You may assert that a response contains specific metadata using the `assertName()`, `assertTitle()`, and `assertDescription()` methods: + +```php +$response->assertName('current-weather'); +$response->assertTitle('Current Weather Tool'); +$response->assertDescription('Fetches the current weather forecast for a specified location.'); +``` + +You may assert that notifications were sent using the `assertSentNotification` and `assertNotificationCount` methods: + +```php +$response->assertSentNotification('processing/progress', [ + 'step' => 1, + 'total' => 5, +]); + +$response->assertSentNotification('processing/progress', [ + 'step' => 2, + 'total' => 5, +]); + +$response->assertNotificationCount(5); +``` + +Finally, if you wish to inspect the raw response content, you may use the `dd` or `dump` methods to output the response for debugging purposes: + +```php +$response->dd(); +$response->dump(); +``` diff --git a/middleware.md b/middleware.md index 28c7f128e09..26627a2e522 100644 --- a/middleware.md +++ b/middleware.md @@ -4,8 +4,9 @@ - [Defining Middleware](#defining-middleware) - [Registering Middleware](#registering-middleware) - [Global Middleware](#global-middleware) - - [Assigning Middleware To Routes](#assigning-middleware-to-routes) + - [Assigning Middleware to Routes](#assigning-middleware-to-routes) - [Middleware Groups](#middleware-groups) + - [Middleware Aliases](#middleware-aliases) - [Sorting Middleware](#sorting-middleware) - [Middleware Parameters](#middleware-parameters) - [Terminable Middleware](#terminable-middleware) @@ -15,7 +16,7 @@ Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. -Additional middleware can be written to perform a variety of tasks besides authentication. For example, a logging middleware might log all incoming requests to your application. There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the `app/Http/Middleware` directory. +Additional middleware can be written to perform a variety of tasks besides authentication. For example, a logging middleware might log all incoming requests to your application. A variety of middleware are included in Laravel, including middleware for authentication and CSRF protection; however, all user-defined middleware are typically located in your application's `app/Http/Middleware` directory. ## Defining Middleware @@ -26,80 +27,90 @@ To create a new middleware, use the `make:middleware` Artisan command: php artisan make:middleware EnsureTokenIsValid ``` -This command will place a new `EnsureTokenIsValid` class within your `app/Http/Middleware` directory. In this middleware, we will only allow access to the route if the supplied `token` input matches a specified value. Otherwise, we will redirect the users back to the `home` URI: +This command will place a new `EnsureTokenIsValid` class within your `app/Http/Middleware` directory. In this middleware, we will only allow access to the route if the supplied `token` input matches a specified value. Otherwise, we will redirect the users back to the `/home` URI: - input('token') !== 'my-secret-token') { - return redirect('home'); - } - - return $next($request); + if ($request->input('token') !== 'my-secret-token') { + return redirect('/home'); } + + return $next($request); } +} +``` As you can see, if the given `token` does not match our secret token, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), you should call the `$next` callback with the `$request`. It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely. -> {tip} All middleware are resolved via the [service container](/docs/{{version}}/container), so you may type-hint any dependencies you need within a middleware's constructor. +> [!NOTE] +> All middleware are resolved via the [service container](/docs/{{version}}/container), so you may type-hint any dependencies you need within a middleware's constructor. - -#### Middleware & Responses +#### Middleware and Responses Of course, a middleware can perform tasks before or after passing the request deeper into the application. For example, the following middleware would perform some task **before** the request is handled by the application: - ## Registering Middleware @@ -107,140 +118,283 @@ However, this middleware would perform its task **after** the request is handled ### Global Middleware -If you want a middleware to run during every HTTP request to your application, list the middleware class in the `$middleware` property of your `app/Http/Kernel.php` class. - - -### Assigning Middleware To Routes +If you want a middleware to run during every HTTP request to your application, you may append it to the global middleware stack in your application's `bootstrap/app.php` file: -If you would like to assign middleware to specific routes, you should first assign the middleware a key in your application's `app/Http/Kernel.php` file. By default, the `$routeMiddleware` property of this class contains entries for the middleware included with Laravel. You may add your own middleware to this list and assign it a key of your choosing: +```php +use App\Http\Middleware\EnsureTokenIsValid; - // Within App\Http\Kernel class... - - protected $routeMiddleware = [ - 'auth' => \App\Http\Middleware\Authenticate::class, - 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, - 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, - 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, - 'can' => \Illuminate\Auth\Middleware\Authorize::class, - 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, - 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, - 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, - 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, - ]; +->withMiddleware(function (Middleware $middleware): void { + $middleware->append(EnsureTokenIsValid::class); +}) +``` -Once the middleware has been defined in the HTTP kernel, you may use the `middleware` method to assign middleware to a route: +The `$middleware` object provided to the `withMiddleware` closure is an instance of `Illuminate\Foundation\Configuration\Middleware` and is responsible for managing the middleware assigned to your application's routes. The `append` method adds the middleware to the end of the list of global middleware. If you would like to add a middleware to the beginning of the list, you should use the `prepend` method. + + +#### Manually Managing Laravel's Default Global Middleware + +If you would like to manage Laravel's global middleware stack manually, you may provide Laravel's default stack of global middleware to the `use` method. Then, you may adjust the default middleware stack as necessary: + +```php +->withMiddleware(function (Middleware $middleware): void { + $middleware->use([ + \Illuminate\Foundation\Http\Middleware\InvokeDeferredCallbacks::class, + // \Illuminate\Http\Middleware\TrustHosts::class, + \Illuminate\Http\Middleware\TrustProxies::class, + \Illuminate\Http\Middleware\HandleCors::class, + \Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class, + \Illuminate\Http\Middleware\ValidatePostSize::class, + \Illuminate\Foundation\Http\Middleware\TrimStrings::class, + \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, + ]); +}) +``` - Route::get('/profile', function () { - // - })->middleware('auth'); + +### Assigning Middleware to Routes -You may assign multiple middleware to the route by passing an array of middleware names to the `middleware` method: +If you would like to assign middleware to specific routes, you may invoke the `middleware` method when defining the route: - Route::get('/', function () { - // - })->middleware(['first', 'second']); +```php +use App\Http\Middleware\EnsureTokenIsValid; -When assigning middleware, you may also pass the fully qualified class name: +Route::get('/profile', function () { + // ... +})->middleware(EnsureTokenIsValid::class); +``` - use App\Http\Middleware\EnsureTokenIsValid; +You may assign multiple middleware to the route by passing an array of middleware names to the `middleware` method: - Route::get('/profile', function () { - // - })->middleware(EnsureTokenIsValid::class); +```php +Route::get('/', function () { + // ... +})->middleware([First::class, Second::class]); +``` #### Excluding Middleware When assigning middleware to a group of routes, you may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the `withoutMiddleware` method: - use App\Http\Middleware\EnsureTokenIsValid; - - Route::middleware([EnsureTokenIsValid::class])->group(function () { - Route::get('/', function () { - // - }); +```php +use App\Http\Middleware\EnsureTokenIsValid; - Route::get('/profile', function () { - // - })->withoutMiddleware([EnsureTokenIsValid::class]); +Route::middleware([EnsureTokenIsValid::class])->group(function () { + Route::get('/', function () { + // ... }); + Route::get('/profile', function () { + // ... + })->withoutMiddleware([EnsureTokenIsValid::class]); +}); +``` + You may also exclude a given set of middleware from an entire [group](/docs/{{version}}/routing#route-groups) of route definitions: - use App\Http\Middleware\EnsureTokenIsValid; +```php +use App\Http\Middleware\EnsureTokenIsValid; - Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () { - Route::get('/profile', function () { - // - }); +Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () { + Route::get('/profile', function () { + // ... }); +}); +``` The `withoutMiddleware` method can only remove route middleware and does not apply to [global middleware](#global-middleware). ### Middleware Groups -Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this using the `$middlewareGroups` property of your HTTP kernel. +Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this using the `appendToGroup` method within your application's `bootstrap/app.php` file: -Out of the box, Laravel comes with `web` and `api` middleware groups that contain common middleware you may want to apply to your web and API routes. Remember, these middleware groups are automatically applied by your application's `App\Providers\RouteServiceProvider` service provider to routes within your corresponding `web` and `api` route files: +```php +use App\Http\Middleware\First; +use App\Http\Middleware\Second; - /** - * The application's route middleware groups. - * - * @var array - */ - protected $middlewareGroups = [ - 'web' => [ - \App\Http\Middleware\EncryptCookies::class, - \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, - \Illuminate\Session\Middleware\StartSession::class, - // \Illuminate\Session\Middleware\AuthenticateSession::class, - \Illuminate\View\Middleware\ShareErrorsFromSession::class, - \App\Http\Middleware\VerifyCsrfToken::class, - \Illuminate\Routing\Middleware\SubstituteBindings::class, - ], - - 'api' => [ - 'throttle:api', - \Illuminate\Routing\Middleware\SubstituteBindings::class, - ], - ]; - -Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware. Again, middleware groups make it more convenient to assign many middleware to a route at once: +->withMiddleware(function (Middleware $middleware): void { + $middleware->appendToGroup('group-name', [ + First::class, + Second::class, + ]); - Route::get('/', function () { - // - })->middleware('web'); + $middleware->prependToGroup('group-name', [ + First::class, + Second::class, + ]); +}) +``` - Route::middleware(['web'])->group(function () { - // - }); +Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware: + +```php +Route::get('/', function () { + // ... +})->middleware('group-name'); + +Route::middleware(['group-name'])->group(function () { + // ... +}); +``` + + +#### Laravel's Default Middleware Groups + +Laravel includes predefined `web` and `api` middleware groups that contain common middleware you may want to apply to your web and API routes. Remember, Laravel automatically applies these middleware groups to the corresponding `routes/web.php` and `routes/api.php` files: + +
+ +| The `web` Middleware Group | +| --------------------------------------------------------- | +| `Illuminate\Cookie\Middleware\EncryptCookies` | +| `Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse` | +| `Illuminate\Session\Middleware\StartSession` | +| `Illuminate\View\Middleware\ShareErrorsFromSession` | +| `Illuminate\Foundation\Http\Middleware\ValidateCsrfToken` | +| `Illuminate\Routing\Middleware\SubstituteBindings` | + +
+ +
+ +| The `api` Middleware Group | +| -------------------------------------------------- | +| `Illuminate\Routing\Middleware\SubstituteBindings` | + +
+ +If you would like to append or prepend middleware to these groups, you may use the `web` and `api` methods within your application's `bootstrap/app.php` file. The `web` and `api` methods are convenient alternatives to the `appendToGroup` method: + +```php +use App\Http\Middleware\EnsureTokenIsValid; +use App\Http\Middleware\EnsureUserIsSubscribed; + +->withMiddleware(function (Middleware $middleware): void { + $middleware->web(append: [ + EnsureUserIsSubscribed::class, + ]); + + $middleware->api(prepend: [ + EnsureTokenIsValid::class, + ]); +}) +``` + +You may even replace one of Laravel's default middleware group entries with a custom middleware of your own: + +```php +use App\Http\Middleware\StartCustomSession; +use Illuminate\Session\Middleware\StartSession; + +$middleware->web(replace: [ + StartSession::class => StartCustomSession::class, +]); +``` + +Or, you may remove a middleware entirely: -> {tip} Out of the box, the `web` and `api` middleware groups are automatically applied to your application's corresponding `routes/web.php` and `routes/api.php` files by the `App\Providers\RouteServiceProvider`. +```php +$middleware->web(remove: [ + StartSession::class, +]); +``` + + +#### Manually Managing Laravel's Default Middleware Groups + +If you would like to manually manage all of the middleware within Laravel's default `web` and `api` middleware groups, you may redefine the groups entirely. The example below will define the `web` and `api` middleware groups with their default middleware, allowing you to customize them as necessary: + +```php +->withMiddleware(function (Middleware $middleware): void { + $middleware->group('web', [ + \Illuminate\Cookie\Middleware\EncryptCookies::class, + \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, + \Illuminate\Session\Middleware\StartSession::class, + \Illuminate\View\Middleware\ShareErrorsFromSession::class, + \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class, + \Illuminate\Routing\Middleware\SubstituteBindings::class, + // \Illuminate\Session\Middleware\AuthenticateSession::class, + ]); + + $middleware->group('api', [ + // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, + // 'throttle:api', + \Illuminate\Routing\Middleware\SubstituteBindings::class, + ]); +}) +``` + +> [!NOTE] +> By default, the `web` and `api` middleware groups are automatically applied to your application's corresponding `routes/web.php` and `routes/api.php` files by the `bootstrap/app.php` file. + + +### Middleware Aliases + +You may assign aliases to middleware in your application's `bootstrap/app.php` file. Middleware aliases allow you to define a short alias for a given middleware class, which can be especially useful for middleware with long class names: + +```php +use App\Http\Middleware\EnsureUserIsSubscribed; + +->withMiddleware(function (Middleware $middleware): void { + $middleware->alias([ + 'subscribed' => EnsureUserIsSubscribed::class + ]); +}) +``` + +Once the middleware alias has been defined in your application's `bootstrap/app.php` file, you may use the alias when assigning the middleware to routes: + +```php +Route::get('/profile', function () { + // ... +})->middleware('subscribed'); +``` + +For convenience, some of Laravel's built-in middleware are aliased by default. For example, the `auth` middleware is an alias for the `Illuminate\Auth\Middleware\Authenticate` middleware. Below is a list of the default middleware aliases: + +
+ +| Alias | Middleware | +| ------------------ | ------------------------------------------------------------------------------------------------------------- | +| `auth` | `Illuminate\Auth\Middleware\Authenticate` | +| `auth.basic` | `Illuminate\Auth\Middleware\AuthenticateWithBasicAuth` | +| `auth.session` | `Illuminate\Session\Middleware\AuthenticateSession` | +| `cache.headers` | `Illuminate\Http\Middleware\SetCacheHeaders` | +| `can` | `Illuminate\Auth\Middleware\Authorize` | +| `guest` | `Illuminate\Auth\Middleware\RedirectIfAuthenticated` | +| `password.confirm` | `Illuminate\Auth\Middleware\RequirePassword` | +| `precognitive` | `Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests` | +| `signed` | `Illuminate\Routing\Middleware\ValidateSignature` | +| `subscribed` | `\Spark\Http\Middleware\VerifyBillableIsSubscribed` | +| `throttle` | `Illuminate\Routing\Middleware\ThrottleRequests` or `Illuminate\Routing\Middleware\ThrottleRequestsWithRedis` | +| `verified` | `Illuminate\Auth\Middleware\EnsureEmailIsVerified` | + +
### Sorting Middleware -Rarely, you may need your middleware to execute in a specific order but not have control over their order when they are assigned to the route. In this case, you may specify your middleware priority using the `$middlewarePriority` property of your `app/Http/Kernel.php` file. This property may not exist in your HTTP kernel by default. If it does not exist, you may copy its default definition below: +Rarely, you may need your middleware to execute in a specific order but not have control over their order when they are assigned to the route. In these situations, you may specify your middleware priority using the `priority` method in your application's `bootstrap/app.php` file: - /** - * The priority-sorted list of middleware. - * - * This forces non-global middleware to always be in the given order. - * - * @var string[] - */ - protected $middlewarePriority = [ +```php +->withMiddleware(function (Middleware $middleware): void { + $middleware->priority([ + \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class, \Illuminate\Cookie\Middleware\EncryptCookies::class, + \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, - \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class, + \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class, + \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, \Illuminate\Routing\Middleware\ThrottleRequests::class, \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class, - \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, + \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class, \Illuminate\Auth\Middleware\Authorize::class, - ]; + ]); +}) +``` ## Middleware Parameters @@ -249,89 +403,99 @@ Middleware can also receive additional parameters. For example, if your applicat Additional middleware parameters will be passed to the middleware after the `$next` argument: - user()->hasRole($role)) { - // Redirect... - } - - return $next($request); + if (! $request->user()->hasRole($role)) { + // Redirect... } + return $next($request); } +} +``` -Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a `:`. Multiple parameters should be delimited by commas: +Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a `:`: - Route::put('/post/{id}', function ($id) { - // - })->middleware('role:editor'); +```php +use App\Http\Middleware\EnsureUserHasRole; + +Route::put('/post/{id}', function (string $id) { + // ... +})->middleware(EnsureUserHasRole::class.':editor'); +``` + +Multiple parameters may be delimited by commas: + +```php +Route::put('/post/{id}', function (string $id) { + // ... +})->middleware(EnsureUserHasRole::class.':editor,publisher'); +``` ## Terminable Middleware -Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. If you define a `terminate` method on your middleware and your web server is using FastCGI, the `terminate` method will automatically be called after the response is sent to the browser: +Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. If you define a `terminate` method on your middleware and your web server is using [FastCGI](https://www.php.net/manual/en/install.fpm.php), the `terminate` method will automatically be called after the response is sent to the browser: - app->singleton(TerminatingMiddleware::class); - } +/** + * Register any application services. + */ +public function register(): void +{ + $this->app->singleton(TerminatingMiddleware::class); +} +``` diff --git a/migrations.md b/migrations.md index 3154a90fe6d..2e4b62a37c6 100644 --- a/migrations.md +++ b/migrations.md @@ -15,6 +15,7 @@ - [Available Column Types](#available-column-types) - [Column Modifiers](#column-modifiers) - [Modifying Columns](#modifying-columns) + - [Renaming Columns](#renaming-columns) - [Dropping Columns](#dropping-columns) - [Indexes](#indexes) - [Creating Indexes](#creating-indexes) @@ -43,7 +44,8 @@ Laravel will use the name of the migration to attempt to guess the name of the t If you would like to specify a custom path for the generated migration, you may use the `--path` option when executing the `make:migration` command. The given path should be relative to your application's base path. -> {tip} Migration stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization). +> [!NOTE] +> Migration stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization). ### Squashing Migrations @@ -57,11 +59,19 @@ php artisan schema:dump php artisan schema:dump --prune ``` -When you execute this command, Laravel will write a "schema" file to your application's `database/schema` directory. Now, when you attempt to migrate your database and no other migrations have been executed, Laravel will execute the schema file's SQL statements first. After executing the schema file's statements, Laravel will execute any remaining migrations that were not part of the schema dump. +When you execute this command, Laravel will write a "schema" file to your application's `database/schema` directory. The schema file's name will correspond to the database connection. Now, when you attempt to migrate your database and no other migrations have been executed, Laravel will first execute the SQL statements in the schema file of the database connection you are using. After executing the schema file's SQL statements, Laravel will execute any remaining migrations that were not part of the schema dump. + +If your application's tests use a different database connection than the one you typically use during local development, you should ensure you have dumped a schema file using that database connection so that your tests are able to build your database. You may wish to do this after dumping the database connection you typically use during local development: + +```shell +php artisan schema:dump +php artisan schema:dump --database=testing --prune +``` You should commit your database schema file to source control so that other new developers on your team may quickly create your application's initial database structure. -> {note} Migration squashing is only available for the MySQL, PostgreSQL, and SQLite databases and utilizes the database's command-line client. Schema dumps may not be restored to in-memory SQLite databases. +> [!WARNING] +> Migration squashing is only available for the MariaDB, MySQL, PostgreSQL, and SQLite databases and utilizes the database's command-line client. ## Migration Structure @@ -70,75 +80,77 @@ A migration class contains two methods: `up` and `down`. The `up` method is used Within both of these methods, you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the `Schema` builder, [check out its documentation](#creating-tables). For example, the following migration creates a `flights` table: - id(); - $table->string('name'); - $table->string('airline'); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('flights'); - } - }; - - -#### Anonymous Migrations - -As you may have noticed in the example above, Laravel will automatically assign a class name to all of the migrations that you generate using the `make:migration` command. However, if you wish, you may return an anonymous class from your migration file. This is primarily useful if your application accumulates many migrations and two of them have a class name collision: - - id(); + $table->string('name'); + $table->string('airline'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void { - // - }; + Schema::drop('flights'); + } +}; +``` -#### Setting The Migration Connection +#### Setting the Migration Connection If your migration will be interacting with a database connection other than your application's default database connection, you should set the `$connection` property of your migration: - /** - * The database connection that should be used by the migration. - * - * @var string - */ - protected $connection = 'pgsql'; +```php +/** + * The database connection that should be used by the migration. + * + * @var string + */ +protected $connection = 'pgsql'; + +/** + * Run the migrations. + */ +public function up(): void +{ + // ... +} +``` - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - // - } + +#### Skipping Migrations + +Sometimes a migration might be meant to support a feature that is not yet active and you do not want it to run yet. In this case you may define a `shouldRun` method on the migration. If the `shouldRun` method returns `false`, the migration will be skipped: + +```php +use App\Models\Flights; +use Laravel\Pennant\Feature; + +/** + * Determine if this migration should run. + */ +public function shouldRun(): bool +{ + return Feature::active(Flights::class); +} +``` ## Running Migrations @@ -149,14 +161,33 @@ To run all of your outstanding migrations, execute the `migrate` Artisan command php artisan migrate ``` -If you would like to see which migrations have run thus far, you may use the `migrate:status` Artisan command: +If you would like to see which migrations have already run and which are still pending, you may use the `migrate:status` Artisan command: ```shell php artisan migrate:status ``` +If you would like to see the SQL statements that will be executed by the migrations without actually running them, you may provide the `--pretend` flag to the `migrate` command: + +```shell +php artisan migrate --pretend +``` + +#### Isolating Migration Execution + +If you are deploying your application across multiple servers and running migrations as part of your deployment process, you likely do not want two servers attempting to migrate the database at the same time. To avoid this, you may use the `isolated` option when invoking the `migrate` command. + +When the `isolated` option is provided, Laravel will acquire an atomic lock using your application's cache driver before attempting to run your migrations. All other attempts to run the `migrate` command while that lock is held will not execute; however, the command will still exit with a successful exit status code: + +```shell +php artisan migrate --isolated +``` + +> [!WARNING] +> To utilize this feature, your application must be using the `memcached`, `redis`, `dynamodb`, `database`, `file`, or `array` cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server. + -#### Forcing Migrations To Run In Production +#### Forcing Migrations to Run in Production Some migration operations are destructive, which means they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the `--force` flag: @@ -179,6 +210,18 @@ You may roll back a limited number of migrations by providing the `step` option php artisan migrate:rollback --step=5 ``` +You may roll back a specific "batch" of migrations by providing the `batch` option to the `rollback` command, where the `batch` option corresponds to a batch value within your application's `migrations` database table. For example, the following command will roll back all migrations in batch three: + +```shell +php artisan migrate:rollback --batch=3 +``` + +If you would like to see the SQL statements that will be executed by the migrations without actually running them, you may provide the `--pretend` flag to the `migrate:rollback` command: + +```shell +php artisan migrate:rollback --pretend +``` + The `migrate:reset` command will roll back all of your application's migrations: ```shell @@ -186,7 +229,7 @@ php artisan migrate:reset ``` -#### Roll Back & Migrate Using A Single Command +#### Roll Back and Migrate Using a Single Command The `migrate:refresh` command will roll back all of your migrations and then execute the `migrate` command. This command effectively re-creates your entire database: @@ -204,7 +247,7 @@ php artisan migrate:refresh --step=5 ``` -#### Drop All Tables & Migrate +#### Drop All Tables and Migrate The `migrate:fresh` command will drop all tables from the database and then execute the `migrate` command: @@ -214,7 +257,14 @@ php artisan migrate:fresh php artisan migrate:fresh --seed ``` -> {note} The `migrate:fresh` command will drop all database tables regardless of their prefix. This command should be used with caution when developing on a database that is shared with other applications. +By default, the `migrate:fresh` command only drops tables from the default database connection. However, you may use the `--database` option to specify the database connection that should be migrated. The database connection name should correspond to a connection defined in your application's `database` [configuration file](/docs/{{version}}/configuration): + +```shell +php artisan migrate:fresh --database=admin +``` + +> [!WARNING] +> The `migrate:fresh` command will drop all database tables regardless of their prefix. This command should be used with caution when developing on a database that is shared with other applications. ## Tables @@ -224,91 +274,123 @@ php artisan migrate:fresh --seed To create a new database table, use the `create` method on the `Schema` facade. The `create` method accepts two arguments: the first is the name of the table, while the second is a closure which receives a `Blueprint` object that may be used to define the new table: - use Illuminate\Database\Schema\Blueprint; - use Illuminate\Support\Facades\Schema; +```php +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; - Schema::create('users', function (Blueprint $table) { - $table->id(); - $table->string('name'); - $table->string('email'); - $table->timestamps(); - }); +Schema::create('users', function (Blueprint $table) { + $table->id(); + $table->string('name'); + $table->string('email'); + $table->timestamps(); +}); +``` When creating the table, you may use any of the schema builder's [column methods](#creating-columns) to define the table's columns. - -#### Checking For Table / Column Existence + +#### Determining Table / Column Existence -You may check for the existence of a table or column using the `hasTable` and `hasColumn` methods: +You may determine the existence of a table, column, or index using the `hasTable`, `hasColumn`, and `hasIndex` methods: - if (Schema::hasTable('users')) { - // The "users" table exists... - } +```php +if (Schema::hasTable('users')) { + // The "users" table exists... +} - if (Schema::hasColumn('users', 'email')) { - // The "users" table exists and has an "email" column... - } +if (Schema::hasColumn('users', 'email')) { + // The "users" table exists and has an "email" column... +} + +if (Schema::hasIndex('users', ['email'], 'unique')) { + // The "users" table exists and has a unique index on the "email" column... +} +``` -#### Database Connection & Table Options +#### Database Connection and Table Options If you want to perform a schema operation on a database connection that is not your application's default connection, use the `connection` method: - Schema::connection('sqlite')->create('users', function (Blueprint $table) { - $table->id(); - }); +```php +Schema::connection('sqlite')->create('users', function (Blueprint $table) { + $table->id(); +}); +``` -In addition, a few other properties and methods may be used to define other aspects of the table's creation. The `engine` property may be used to specify the table's storage engine when using MySQL: +In addition, a few other properties and methods may be used to define other aspects of the table's creation. The `engine` property may be used to specify the table's storage engine when using MariaDB or MySQL: - Schema::create('users', function (Blueprint $table) { - $table->engine = 'InnoDB'; +```php +Schema::create('users', function (Blueprint $table) { + $table->engine('InnoDB'); - // ... - }); + // ... +}); +``` -The `charset` and `collation` properties may be used to specify the character set and collation for the created table when using MySQL: +The `charset` and `collation` properties may be used to specify the character set and collation for the created table when using MariaDB or MySQL: - Schema::create('users', function (Blueprint $table) { - $table->charset = 'utf8mb4'; - $table->collation = 'utf8mb4_unicode_ci'; +```php +Schema::create('users', function (Blueprint $table) { + $table->charset('utf8mb4'); + $table->collation('utf8mb4_unicode_ci'); - // ... - }); + // ... +}); +``` The `temporary` method may be used to indicate that the table should be "temporary". Temporary tables are only visible to the current connection's database session and are dropped automatically when the connection is closed: - Schema::create('calculations', function (Blueprint $table) { - $table->temporary(); +```php +Schema::create('calculations', function (Blueprint $table) { + $table->temporary(); - // ... - }); + // ... +}); +``` + +If you would like to add a "comment" to a database table, you may invoke the `comment` method on the table instance. Table comments are currently only supported by MariaDB, MySQL, and PostgreSQL: + +```php +Schema::create('calculations', function (Blueprint $table) { + $table->comment('Business calculations'); + + // ... +}); +``` ### Updating Tables The `table` method on the `Schema` facade may be used to update existing tables. Like the `create` method, the `table` method accepts two arguments: the name of the table and a closure that receives a `Blueprint` instance you may use to add columns or indexes to the table: - use Illuminate\Database\Schema\Blueprint; - use Illuminate\Support\Facades\Schema; +```php +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; - Schema::table('users', function (Blueprint $table) { - $table->integer('votes'); - }); +Schema::table('users', function (Blueprint $table) { + $table->integer('votes'); +}); +``` ### Renaming / Dropping Tables To rename an existing database table, use the `rename` method: - use Illuminate\Support\Facades\Schema; +```php +use Illuminate\Support\Facades\Schema; - Schema::rename($from, $to); +Schema::rename($from, $to); +``` To drop an existing table, you may use the `drop` or `dropIfExists` methods: - Schema::drop('users'); +```php +Schema::drop('users'); - Schema::dropIfExists('users'); +Schema::dropIfExists('users'); +``` #### Renaming Tables With Foreign Keys @@ -323,12 +405,14 @@ Before renaming a table, you should verify that any foreign key constraints on t The `table` method on the `Schema` facade may be used to update existing tables. Like the `create` method, the `table` method accepts two arguments: the name of the table and a closure that receives an `Illuminate\Database\Schema\Blueprint` instance you may use to add columns to the table: - use Illuminate\Database\Schema\Blueprint; - use Illuminate\Support\Facades\Schema; +```php +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; - Schema::table('users', function (Blueprint $table) { - $table->integer('votes'); - }); +Schema::table('users', function (Blueprint $table) { + $table->integer('votes'); +}); +``` ### Available Column Types @@ -336,13 +420,15 @@ The `table` method on the `Schema` facade may be used to update existing tables. The schema builder blueprint offers a variety of methods that correspond to the different types of columns you can add to your database tables. Each of the available methods are listed in the table below: -
+ +#### Boolean Types + +
-[bigIncrements](#column-method-bigIncrements) -[bigInteger](#column-method-bigInteger) -[binary](#column-method-binary) [boolean](#column-method-boolean) + +
+ + +#### String & Text Types + +
+ [char](#column-method-char) -[dateTimeTz](#column-method-dateTimeTz) -[dateTime](#column-method-dateTime) -[date](#column-method-date) +[longText](#column-method-longText) +[mediumText](#column-method-mediumText) +[string](#column-method-string) +[text](#column-method-text) +[tinyText](#column-method-tinyText) + +
+ + +#### Numeric Types + +
+ +[bigIncrements](#column-method-bigIncrements) +[bigInteger](#column-method-bigInteger) [decimal](#column-method-decimal) [double](#column-method-double) -[enum](#column-method-enum) [float](#column-method-float) -[foreignId](#column-method-foreignId) -[foreignIdFor](#column-method-foreignIdFor) -[foreignUuid](#column-method-foreignUuid) -[geometryCollection](#column-method-geometryCollection) -[geometry](#column-method-geometry) [id](#column-method-id) [increments](#column-method-increments) [integer](#column-method-integer) -[ipAddress](#column-method-ipAddress) -[json](#column-method-json) -[jsonb](#column-method-jsonb) -[lineString](#column-method-lineString) -[longText](#column-method-longText) -[macAddress](#column-method-macAddress) [mediumIncrements](#column-method-mediumIncrements) [mediumInteger](#column-method-mediumInteger) -[mediumText](#column-method-mediumText) -[morphs](#column-method-morphs) -[multiLineString](#column-method-multiLineString) -[multiPoint](#column-method-multiPoint) -[multiPolygon](#column-method-multiPolygon) -[nullableMorphs](#column-method-nullableMorphs) -[nullableTimestamps](#column-method-nullableTimestamps) -[nullableUuidMorphs](#column-method-nullableUuidMorphs) -[point](#column-method-point) -[polygon](#column-method-polygon) -[rememberToken](#column-method-rememberToken) -[set](#column-method-set) [smallIncrements](#column-method-smallIncrements) [smallInteger](#column-method-smallInteger) -[softDeletesTz](#column-method-softDeletesTz) -[softDeletes](#column-method-softDeletes) -[string](#column-method-string) -[text](#column-method-text) -[timeTz](#column-method-timeTz) -[time](#column-method-time) -[timestampTz](#column-method-timestampTz) -[timestamp](#column-method-timestamp) -[timestampsTz](#column-method-timestampsTz) -[timestamps](#column-method-timestamps) [tinyIncrements](#column-method-tinyIncrements) [tinyInteger](#column-method-tinyInteger) -[tinyText](#column-method-tinyText) [unsignedBigInteger](#column-method-unsignedBigInteger) -[unsignedDecimal](#column-method-unsignedDecimal) [unsignedInteger](#column-method-unsignedInteger) [unsignedMediumInteger](#column-method-unsignedMediumInteger) [unsignedSmallInteger](#column-method-unsignedSmallInteger) [unsignedTinyInteger](#column-method-unsignedTinyInteger) -[uuidMorphs](#column-method-uuidMorphs) -[uuid](#column-method-uuid) + +
+ + +#### Date & Time Types + +
+ +[dateTime](#column-method-dateTime) +[dateTimeTz](#column-method-dateTimeTz) +[date](#column-method-date) +[time](#column-method-time) +[timeTz](#column-method-timeTz) +[timestamp](#column-method-timestamp) +[timestamps](#column-method-timestamps) +[timestampsTz](#column-method-timestampsTz) +[softDeletes](#column-method-softDeletes) +[softDeletesTz](#column-method-softDeletesTz) [year](#column-method-year)
+ +#### Binary Types + +
+ +[binary](#column-method-binary) + +
+ + +#### Object & Json Types + +
+ +[json](#column-method-json) +[jsonb](#column-method-jsonb) + +
+ + +#### UUID & ULID Types + +
+ +[ulid](#column-method-ulid) +[ulidMorphs](#column-method-ulidMorphs) +[uuid](#column-method-uuid) +[uuidMorphs](#column-method-uuidMorphs) +[nullableUlidMorphs](#column-method-nullableUlidMorphs) +[nullableUuidMorphs](#column-method-nullableUuidMorphs) + +
+ + +#### Spatial Types + +
+ +[geography](#column-method-geography) +[geometry](#column-method-geometry) + +
+ +#### Relationship Types + +
+ +[foreignId](#column-method-foreignId) +[foreignIdFor](#column-method-foreignIdFor) +[foreignUlid](#column-method-foreignUlid) +[foreignUuid](#column-method-foreignUuid) +[morphs](#column-method-morphs) +[nullableMorphs](#column-method-nullableMorphs) + +
+ + +#### Specialty Types + +
+ +[enum](#column-method-enum) +[set](#column-method-set) +[macAddress](#column-method-macAddress) +[ipAddress](#column-method-ipAddress) +[rememberToken](#column-method-rememberToken) +[vector](#column-method-vector) + +
+ #### `bigIncrements()` {.collection-method .first-collection-method} The `bigIncrements` method creates an auto-incrementing `UNSIGNED BIGINT` (primary key) equivalent column: - $table->bigIncrements('id'); +```php +$table->bigIncrements('id'); +``` #### `bigInteger()` {.collection-method} The `bigInteger` method creates a `BIGINT` equivalent column: - $table->bigInteger('votes'); +```php +$table->bigInteger('votes'); +``` #### `binary()` {.collection-method} The `binary` method creates a `BLOB` equivalent column: - $table->binary('photo'); +```php +$table->binary('photo'); +``` + +When utilizing MySQL, MariaDB, or SQL Server, you may pass `length` and `fixed` arguments to create `VARBINARY` or `BINARY` equivalent column: + +```php +$table->binary('data', length: 16); // VARBINARY(16) + +$table->binary('data', length: 16, fixed: true); // BINARY(16) +``` #### `boolean()` {.collection-method} The `boolean` method creates a `BOOLEAN` equivalent column: - $table->boolean('confirmed'); +```php +$table->boolean('confirmed'); +``` #### `char()` {.collection-method} The `char` method creates a `CHAR` equivalent column with of a given length: - $table->char('name', 100); +```php +$table->char('name', length: 100); +``` #### `dateTimeTz()` {.collection-method} -The `dateTimeTz` method creates a `DATETIME` (with timezone) equivalent column with an optional precision (total digits): +The `dateTimeTz` method creates a `DATETIME` (with timezone) equivalent column with an optional fractional seconds precision: - $table->dateTimeTz('created_at', $precision = 0); +```php +$table->dateTimeTz('created_at', precision: 0); +``` #### `dateTime()` {.collection-method} -The `dateTime` method creates a `DATETIME` equivalent column with an optional precision (total digits): +The `dateTime` method creates a `DATETIME` equivalent column with an optional fractional seconds precision: - $table->dateTime('created_at', $precision = 0); +```php +$table->dateTime('created_at', precision: 0); +``` #### `date()` {.collection-method} The `date` method creates a `DATE` equivalent column: - $table->date('created_at'); +```php +$table->date('created_at'); +``` #### `decimal()` {.collection-method} The `decimal` method creates a `DECIMAL` equivalent column with the given precision (total digits) and scale (decimal digits): - $table->decimal('amount', $precision = 8, $scale = 2); +```php +$table->decimal('amount', total: 8, places: 2); +``` #### `double()` {.collection-method} -The `double` method creates a `DOUBLE` equivalent column with the given precision (total digits) and scale (decimal digits): +The `double` method creates a `DOUBLE` equivalent column: - $table->double('amount', 8, 2); +```php +$table->double('amount'); +``` #### `enum()` {.collection-method} The `enum` method creates a `ENUM` equivalent column with the given valid values: - $table->enum('difficulty', ['easy', 'hard']); +```php +$table->enum('difficulty', ['easy', 'hard']); +``` + +Of course, you may use the `Enum::cases()` method instead of manually defining an array of allowed values: + +```php +use App\Enums\Difficulty; + +$table->enum('difficulty', Difficulty::cases()); +``` #### `float()` {.collection-method} -The `float` method creates a `FLOAT` equivalent column with the given precision (total digits) and scale (decimal digits): +The `float` method creates a `FLOAT` equivalent column with the given precision: - $table->float('amount', 8, 2); +```php +$table->float('amount', precision: 53); +``` #### `foreignId()` {.collection-method} The `foreignId` method creates an `UNSIGNED BIGINT` equivalent column: - $table->foreignId('user_id'); +```php +$table->foreignId('user_id'); +``` #### `foreignIdFor()` {.collection-method} -The `foreignIdFor` method adds a `{column}_id UNSIGNED BIGINT` equivalent column for a given model class: +The `foreignIdFor` method adds a `{column}_id` equivalent column for a given model class. The column type will be `UNSIGNED BIGINT`, `CHAR(36)`, or `CHAR(26)` depending on the model key type: + +```php +$table->foreignIdFor(User::class); +``` - $table->foreignIdFor(User::class); + +#### `foreignUlid()` {.collection-method} + +The `foreignUlid` method creates a `ULID` equivalent column: + +```php +$table->foreignUlid('user_id'); +``` #### `foreignUuid()` {.collection-method} The `foreignUuid` method creates a `UUID` equivalent column: - $table->foreignUuid('user_id'); +```php +$table->foreignUuid('user_id'); +``` - -#### `geometryCollection()` {.collection-method} + +#### `geography()` {.collection-method} -The `geometryCollection` method creates a `GEOMETRYCOLLECTION` equivalent column: +The `geography` method creates a `GEOGRAPHY` equivalent column with the given spatial type and SRID (Spatial Reference System Identifier): - $table->geometryCollection('positions'); +```php +$table->geography('coordinates', subtype: 'point', srid: 4326); +``` + +> [!NOTE] +> Support for spatial types depends on your database driver. Please refer to your database's documentation. If your application is utilizing a PostgreSQL database, you must install the [PostGIS](https://postgis.net) extension before the `geography` method may be used. #### `geometry()` {.collection-method} -The `geometry` method creates a `GEOMETRY` equivalent column: +The `geometry` method creates a `GEOMETRY` equivalent column with the given spatial type and SRID (Spatial Reference System Identifier): + +```php +$table->geometry('positions', subtype: 'point', srid: 0); +``` - $table->geometry('positions'); +> [!NOTE] +> Support for spatial types depends on your database driver. Please refer to your database's documentation. If your application is utilizing a PostgreSQL database, you must install the [PostGIS](https://postgis.net) extension before the `geometry` method may be used. #### `id()` {.collection-method} The `id` method is an alias of the `bigIncrements` method. By default, the method will create an `id` column; however, you may pass a column name if you would like to assign a different name to the column: - $table->id(); +```php +$table->id(); +``` #### `increments()` {.collection-method} The `increments` method creates an auto-incrementing `UNSIGNED INTEGER` equivalent column as a primary key: - $table->increments('id'); +```php +$table->increments('id'); +``` #### `integer()` {.collection-method} The `integer` method creates an `INTEGER` equivalent column: - $table->integer('votes'); +```php +$table->integer('votes'); +``` #### `ipAddress()` {.collection-method} The `ipAddress` method creates a `VARCHAR` equivalent column: - $table->ipAddress('visitor'); +```php +$table->ipAddress('visitor'); +``` + +When using PostgreSQL, an `INET` column will be created. #### `json()` {.collection-method} The `json` method creates a `JSON` equivalent column: - $table->json('options'); +```php +$table->json('options'); +``` + +When using SQLite, a `TEXT` column will be created. #### `jsonb()` {.collection-method} The `jsonb` method creates a `JSONB` equivalent column: - $table->jsonb('options'); - - -#### `lineString()` {.collection-method} - -The `lineString` method creates a `LINESTRING` equivalent column: +```php +$table->jsonb('options'); +``` - $table->lineString('positions'); +When using SQLite, a `TEXT` column will be created. #### `longText()` {.collection-method} The `longText` method creates a `LONGTEXT` equivalent column: - $table->longText('description'); +```php +$table->longText('description'); +``` + +When utilizing MySQL or MariaDB, you may apply a `binary` character set to the column in order to create a `LONGBLOB` equivalent column: + +```php +$table->longText('data')->charset('binary'); // LONGBLOB +``` #### `macAddress()` {.collection-method} The `macAddress` method creates a column that is intended to hold a MAC address. Some database systems, such as PostgreSQL, have a dedicated column type for this type of data. Other database systems will use a string equivalent column: - $table->macAddress('device'); +```php +$table->macAddress('device'); +``` #### `mediumIncrements()` {.collection-method} The `mediumIncrements` method creates an auto-incrementing `UNSIGNED MEDIUMINT` equivalent column as a primary key: - $table->mediumIncrements('id'); +```php +$table->mediumIncrements('id'); +``` #### `mediumInteger()` {.collection-method} The `mediumInteger` method creates a `MEDIUMINT` equivalent column: - $table->mediumInteger('votes'); +```php +$table->mediumInteger('votes'); +``` #### `mediumText()` {.collection-method} The `mediumText` method creates a `MEDIUMTEXT` equivalent column: - $table->mediumText('description'); +```php +$table->mediumText('description'); +``` + +When utilizing MySQL or MariaDB, you may apply a `binary` character set to the column in order to create a `MEDIUMBLOB` equivalent column: + +```php +$table->mediumText('data')->charset('binary'); // MEDIUMBLOB +``` #### `morphs()` {.collection-method} -The `morphs` method is a convenience method that adds a `{column}_id` `UNSIGNED BIGINT` equivalent column and a `{column}_type` `VARCHAR` equivalent column. +The `morphs` method is a convenience method that adds a `{column}_id` equivalent column and a `{column}_type` `VARCHAR` equivalent column. The column type for the `{column}_id` will be `UNSIGNED BIGINT`, `CHAR(36)`, or `CHAR(26)` depending on the model key type. This method is intended to be used when defining the columns necessary for a polymorphic [Eloquent relationship](/docs/{{version}}/eloquent-relationships). In the following example, `taggable_id` and `taggable_type` columns would be created: - $table->morphs('taggable'); - - -#### `multiLineString()` {.collection-method} - -The `multiLineString` method creates a `MULTILINESTRING` equivalent column: - - $table->multiLineString('positions'); - - -#### `multiPoint()` {.collection-method} - -The `multiPoint` method creates a `MULTIPOINT` equivalent column: - - $table->multiPoint('positions'); - - -#### `multiPolygon()` {.collection-method} - -The `multiPolygon` method creates a `MULTIPOLYGON` equivalent column: - - $table->multiPolygon('positions'); - - -#### `nullableTimestamps()` {.collection-method} - -The `nullableTimestamps` method is an alias of the [timestamps](#column-method-timestamps) method: - - $table->nullableTimestamps(0); +```php +$table->morphs('taggable'); +``` #### `nullableMorphs()` {.collection-method} The method is similar to the [morphs](#column-method-morphs) method; however, the columns that are created will be "nullable": - $table->nullableMorphs('taggable'); - - -#### `nullableUuidMorphs()` {.collection-method} - -The method is similar to the [uuidMorphs](#column-method-uuidMorphs) method; however, the columns that are created will be "nullable": - - $table->nullableUuidMorphs('taggable'); +```php +$table->nullableMorphs('taggable'); +``` - -#### `point()` {.collection-method} + +#### `nullableUlidMorphs()` {.collection-method} -The `point` method creates a `POINT` equivalent column: +The method is similar to the [ulidMorphs](#column-method-ulidMorphs) method; however, the columns that are created will be "nullable": - $table->point('position'); +```php +$table->nullableUlidMorphs('taggable'); +``` - -#### `polygon()` {.collection-method} + +#### `nullableUuidMorphs()` {.collection-method} -The `polygon` method creates a `POLYGON` equivalent column: +The method is similar to the [uuidMorphs](#column-method-uuidMorphs) method; however, the columns that are created will be "nullable": - $table->polygon('position'); +```php +$table->nullableUuidMorphs('taggable'); +``` #### `rememberToken()` {.collection-method} The `rememberToken` method creates a nullable, `VARCHAR(100)` equivalent column that is intended to store the current "remember me" [authentication token](/docs/{{version}}/authentication#remembering-users): - $table->rememberToken(); +```php +$table->rememberToken(); +``` #### `set()` {.collection-method} The `set` method creates a `SET` equivalent column with the given list of valid values: - $table->set('flavors', ['strawberry', 'vanilla']); +```php +$table->set('flavors', ['strawberry', 'vanilla']); +``` #### `smallIncrements()` {.collection-method} The `smallIncrements` method creates an auto-incrementing `UNSIGNED SMALLINT` equivalent column as a primary key: - $table->smallIncrements('id'); +```php +$table->smallIncrements('id'); +``` #### `smallInteger()` {.collection-method} The `smallInteger` method creates a `SMALLINT` equivalent column: - $table->smallInteger('votes'); +```php +$table->smallInteger('votes'); +``` #### `softDeletesTz()` {.collection-method} -The `softDeletesTz` method adds a nullable `deleted_at` `TIMESTAMP` (with timezone) equivalent column with an optional precision (total digits). This column is intended to store the `deleted_at` timestamp needed for Eloquent's "soft delete" functionality: +The `softDeletesTz` method adds a nullable `deleted_at` `TIMESTAMP` (with timezone) equivalent column with an optional fractional seconds precision. This column is intended to store the `deleted_at` timestamp needed for Eloquent's "soft delete" functionality: - $table->softDeletesTz($column = 'deleted_at', $precision = 0); +```php +$table->softDeletesTz('deleted_at', precision: 0); +``` #### `softDeletes()` {.collection-method} -The `softDeletes` method adds a nullable `deleted_at` `TIMESTAMP` equivalent column with an optional precision (total digits). This column is intended to store the `deleted_at` timestamp needed for Eloquent's "soft delete" functionality: +The `softDeletes` method adds a nullable `deleted_at` `TIMESTAMP` equivalent column with an optional fractional seconds precision. This column is intended to store the `deleted_at` timestamp needed for Eloquent's "soft delete" functionality: - $table->softDeletes($column = 'deleted_at', $precision = 0); +```php +$table->softDeletes('deleted_at', precision: 0); +``` #### `string()` {.collection-method} The `string` method creates a `VARCHAR` equivalent column of the given length: - $table->string('name', 100); +```php +$table->string('name', length: 100); +``` #### `text()` {.collection-method} The `text` method creates a `TEXT` equivalent column: - $table->text('description'); +```php +$table->text('description'); +``` + +When utilizing MySQL or MariaDB, you may apply a `binary` character set to the column in order to create a `BLOB` equivalent column: + +```php +$table->text('data')->charset('binary'); // BLOB +``` #### `timeTz()` {.collection-method} -The `timeTz` method creates a `TIME` (with timezone) equivalent column with an optional precision (total digits): +The `timeTz` method creates a `TIME` (with timezone) equivalent column with an optional fractional seconds precision: - $table->timeTz('sunrise', $precision = 0); +```php +$table->timeTz('sunrise', precision: 0); +``` #### `time()` {.collection-method} -The `time` method creates a `TIME` equivalent column with an optional precision (total digits): +The `time` method creates a `TIME` equivalent column with an optional fractional seconds precision: - $table->time('sunrise', $precision = 0); +```php +$table->time('sunrise', precision: 0); +``` #### `timestampTz()` {.collection-method} -The `timestampTz` method creates a `TIMESTAMP` (with timezone) equivalent column with an optional precision (total digits): +The `timestampTz` method creates a `TIMESTAMP` (with timezone) equivalent column with an optional fractional seconds precision: - $table->timestampTz('added_at', $precision = 0); +```php +$table->timestampTz('added_at', precision: 0); +``` #### `timestamp()` {.collection-method} -The `timestamp` method creates a `TIMESTAMP` equivalent column with an optional precision (total digits): +The `timestamp` method creates a `TIMESTAMP` equivalent column with an optional fractional seconds precision: - $table->timestamp('added_at', $precision = 0); +```php +$table->timestamp('added_at', precision: 0); +``` #### `timestampsTz()` {.collection-method} -The `timestampsTz` method creates `created_at` and `updated_at` `TIMESTAMP` (with timezone) equivalent columns with an optional precision (total digits): +The `timestampsTz` method creates `created_at` and `updated_at` `TIMESTAMP` (with timezone) equivalent columns with an optional fractional seconds precision: - $table->timestampsTz($precision = 0); +```php +$table->timestampsTz(precision: 0); +``` #### `timestamps()` {.collection-method} -The `timestamps` method creates `created_at` and `updated_at` `TIMESTAMP` equivalent columns with an optional precision (total digits): +The `timestamps` method creates `created_at` and `updated_at` `TIMESTAMP` equivalent columns with an optional fractional seconds precision: - $table->timestamps($precision = 0); +```php +$table->timestamps(precision: 0); +``` #### `tinyIncrements()` {.collection-method} The `tinyIncrements` method creates an auto-incrementing `UNSIGNED TINYINT` equivalent column as a primary key: - $table->tinyIncrements('id'); +```php +$table->tinyIncrements('id'); +``` #### `tinyInteger()` {.collection-method} The `tinyInteger` method creates a `TINYINT` equivalent column: - $table->tinyInteger('votes'); +```php +$table->tinyInteger('votes'); +``` #### `tinyText()` {.collection-method} The `tinyText` method creates a `TINYTEXT` equivalent column: - $table->tinyText('notes'); +```php +$table->tinyText('notes'); +``` + +When utilizing MySQL or MariaDB, you may apply a `binary` character set to the column in order to create a `TINYBLOB` equivalent column: + +```php +$table->tinyText('data')->charset('binary'); // TINYBLOB +``` #### `unsignedBigInteger()` {.collection-method} The `unsignedBigInteger` method creates an `UNSIGNED BIGINT` equivalent column: - $table->unsignedBigInteger('votes'); - - -#### `unsignedDecimal()` {.collection-method} - -The `unsignedDecimal` method creates an `UNSIGNED DECIMAL` equivalent column with an optional precision (total digits) and scale (decimal digits): - - $table->unsignedDecimal('amount', $precision = 8, $scale = 2); +```php +$table->unsignedBigInteger('votes'); +``` #### `unsignedInteger()` {.collection-method} The `unsignedInteger` method creates an `UNSIGNED INTEGER` equivalent column: - $table->unsignedInteger('votes'); +```php +$table->unsignedInteger('votes'); +``` #### `unsignedMediumInteger()` {.collection-method} The `unsignedMediumInteger` method creates an `UNSIGNED MEDIUMINT` equivalent column: - $table->unsignedMediumInteger('votes'); +```php +$table->unsignedMediumInteger('votes'); +``` #### `unsignedSmallInteger()` {.collection-method} The `unsignedSmallInteger` method creates an `UNSIGNED SMALLINT` equivalent column: - $table->unsignedSmallInteger('votes'); +```php +$table->unsignedSmallInteger('votes'); +``` #### `unsignedTinyInteger()` {.collection-method} The `unsignedTinyInteger` method creates an `UNSIGNED TINYINT` equivalent column: - $table->unsignedTinyInteger('votes'); +```php +$table->unsignedTinyInteger('votes'); +``` + + +#### `ulidMorphs()` {.collection-method} + +The `ulidMorphs` method is a convenience method that adds a `{column}_id` `CHAR(26)` equivalent column and a `{column}_type` `VARCHAR` equivalent column. + +This method is intended to be used when defining the columns necessary for a polymorphic [Eloquent relationship](/docs/{{version}}/eloquent-relationships) that use ULID identifiers. In the following example, `taggable_id` and `taggable_type` columns would be created: + +```php +$table->ulidMorphs('taggable'); +``` #### `uuidMorphs()` {.collection-method} @@ -859,181 +1146,207 @@ The `uuidMorphs` method is a convenience method that adds a `{column}_id` `CHAR( This method is intended to be used when defining the columns necessary for a polymorphic [Eloquent relationship](/docs/{{version}}/eloquent-relationships) that use UUID identifiers. In the following example, `taggable_id` and `taggable_type` columns would be created: - $table->uuidMorphs('taggable'); +```php +$table->uuidMorphs('taggable'); +``` + + +#### `ulid()` {.collection-method} + +The `ulid` method creates a `ULID` equivalent column: + +```php +$table->ulid('id'); +``` #### `uuid()` {.collection-method} The `uuid` method creates a `UUID` equivalent column: - $table->uuid('id'); +```php +$table->uuid('id'); +``` + + +#### `vector()` {.collection-method} + +The `vector` method creates a `vector` equivalent column: + +```php +$table->vector('embedding', dimensions: 100); +``` #### `year()` {.collection-method} The `year` method creates a `YEAR` equivalent column: - $table->year('birth_year'); +```php +$table->year('birth_year'); +``` ### Column Modifiers In addition to the column types listed above, there are several column "modifiers" you may use when adding a column to a database table. For example, to make the column "nullable", you may use the `nullable` method: - use Illuminate\Database\Schema\Blueprint; - use Illuminate\Support\Facades\Schema; +```php +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; - Schema::table('users', function (Blueprint $table) { - $table->string('email')->nullable(); - }); +Schema::table('users', function (Blueprint $table) { + $table->string('email')->nullable(); +}); +``` The following table contains all of the available column modifiers. This list does not include [index modifiers](#creating-indexes): -Modifier | Description --------- | ----------- -`->after('column')` | Place the column "after" another column (MySQL). -`->autoIncrement()` | Set INTEGER columns as auto-incrementing (primary key). -`->charset('utf8mb4')` | Specify a character set for the column (MySQL). -`->collation('utf8mb4_unicode_ci')` | Specify a collation for the column (MySQL/PostgreSQL/SQL Server). -`->comment('my comment')` | Add a comment to a column (MySQL/PostgreSQL). -`->default($value)` | Specify a "default" value for the column. -`->first()` | Place the column "first" in the table (MySQL). -`->from($integer)` | Set the starting value of an auto-incrementing field (MySQL / PostgreSQL). -`->invisible()` | Make the column "invisible" to `SELECT *` queries (MySQL). -`->nullable($value = true)` | Allow NULL values to be inserted into the column. -`->storedAs($expression)` | Create a stored generated column (MySQL / PostgreSQL). -`->unsigned()` | Set INTEGER columns as UNSIGNED (MySQL). -`->useCurrent()` | Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value. -`->useCurrentOnUpdate()` | Set TIMESTAMP columns to use CURRENT_TIMESTAMP when a record is updated. -`->virtualAs($expression)` | Create a virtual generated column (MySQL). -`->generatedAs($expression)` | Create an identity column with specified sequence options (PostgreSQL). -`->always()` | Defines the precedence of sequence values over input for an identity column (PostgreSQL). -`->isGeometry()` | Set spatial column type to `geometry` - the default type is `geography` (PostgreSQL). +
+ +| Modifier | Description | +| ----------------------------------- | ---------------------------------------------------------------------------------------------- | +| `->after('column')` | Place the column "after" another column (MariaDB / MySQL). | +| `->autoIncrement()` | Set `INTEGER` columns as auto-incrementing (primary key). | +| `->charset('utf8mb4')` | Specify a character set for the column (MariaDB / MySQL). | +| `->collation('utf8mb4_unicode_ci')` | Specify a collation for the column. | +| `->comment('my comment')` | Add a comment to a column (MariaDB / MySQL / PostgreSQL). | +| `->default($value)` | Specify a "default" value for the column. | +| `->first()` | Place the column "first" in the table (MariaDB / MySQL). | +| `->from($integer)` | Set the starting value of an auto-incrementing field (MariaDB / MySQL / PostgreSQL). | +| `->invisible()` | Make the column "invisible" to `SELECT *` queries (MariaDB / MySQL). | +| `->nullable($value = true)` | Allow `NULL` values to be inserted into the column. | +| `->storedAs($expression)` | Create a stored generated column (MariaDB / MySQL / PostgreSQL / SQLite). | +| `->unsigned()` | Set `INTEGER` columns as `UNSIGNED` (MariaDB / MySQL). | +| `->useCurrent()` | Set `TIMESTAMP` columns to use `CURRENT_TIMESTAMP` as default value. | +| `->useCurrentOnUpdate()` | Set `TIMESTAMP` columns to use `CURRENT_TIMESTAMP` when a record is updated (MariaDB / MySQL). | +| `->virtualAs($expression)` | Create a virtual generated column (MariaDB / MySQL / SQLite). | +| `->generatedAs($expression)` | Create an identity column with specified sequence options (PostgreSQL). | +| `->always()` | Defines the precedence of sequence values over input for an identity column (PostgreSQL). | + +
#### Default Expressions The `default` modifier accepts a value or an `Illuminate\Database\Query\Expression` instance. Using an `Expression` instance will prevent Laravel from wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is when you need to assign default values to JSON columns: - id(); - $table->json('movies')->default(new Expression('(JSON_ARRAY())')); - $table->timestamps(); - }); - } - }; - -> {note} Support for default expressions depends on your database driver, database version, and the field type. Please refer to your database's documentation. + Schema::create('flights', function (Blueprint $table) { + $table->id(); + $table->json('movies')->default(new Expression('(JSON_ARRAY())')); + $table->timestamps(); + }); + } +}; +``` + +> [!WARNING] +> Support for default expressions depends on your database driver, database version, and the field type. Please refer to your database's documentation. #### Column Order -When using the MySQL database, the `after` method may be used to add columns after an existing column in the schema: +When using the MariaDB or MySQL database, the `after` method may be used to add columns after an existing column in the schema: - $table->after('password', function ($table) { - $table->string('address_line1'); - $table->string('address_line2'); - $table->string('city'); - }); +```php +$table->after('password', function (Blueprint $table) { + $table->string('address_line1'); + $table->string('address_line2'); + $table->string('city'); +}); +``` ### Modifying Columns - -#### Prerequisites - -Before modifying a column, you must install the `doctrine/dbal` package using the Composer package manager. The Doctrine DBAL library is used to determine the current state of the column and to create the SQL queries needed to make the requested changes to your column: - - composer require doctrine/dbal - -If you plan to modify columns created using the `timestamp` method, you must also add the following configuration to your application's `config/database.php` configuration file: +The `change` method allows you to modify the type and attributes of existing columns. For example, you may wish to increase the size of a `string` column. To see the `change` method in action, let's increase the size of the `name` column from 25 to 50. To accomplish this, we simply define the new state of the column and then call the `change` method: ```php -use Illuminate\Database\DBAL\TimestampType; - -'dbal' => [ - 'types' => [ - 'timestamp' => TimestampType::class, - ], -], +Schema::table('users', function (Blueprint $table) { + $table->string('name', 50)->change(); +}); ``` -> {note} If your application is using Microsoft SQL Server, please ensure that you install `doctrine/dbal:^3.0`. +When modifying a column, you must explicitly include all the modifiers you want to keep on the column definition - any missing attribute will be dropped. For example, to retain the `unsigned`, `default`, and `comment` attributes, you must call each modifier explicitly when changing the column: - -#### Updating Column Attributes - -The `change` method allows you to modify the type and attributes of existing columns. For example, you may wish to increase the size of a `string` column. To see the `change` method in action, let's increase the size of the `name` column from 25 to 50. To accomplish this, we simply define the new state of the column and then call the `change` method: - - Schema::table('users', function (Blueprint $table) { - $table->string('name', 50)->change(); - }); +```php +Schema::table('users', function (Blueprint $table) { + $table->integer('votes')->unsigned()->default(1)->comment('my comment')->change(); +}); +``` -We could also modify a column to be nullable: +The `change` method does not change the indexes of the column. Therefore, you may use index modifiers to explicitly add or drop an index when modifying the column: - Schema::table('users', function (Blueprint $table) { - $table->string('name', 50)->nullable()->change(); - }); +```php +// Add an index... +$table->bigIncrements('id')->primary()->change(); -> {note} The following column types can be modified: `bigInteger`, `binary`, `boolean`, `date`, `dateTime`, `dateTimeTz`, `decimal`, `integer`, `json`, `longText`, `mediumText`, `smallInteger`, `string`, `text`, `time`, `unsignedBigInteger`, `unsignedInteger`, `unsignedSmallInteger`, and `uuid`. To modify a `timestamp` column type a [Doctrine type must be registered](#prerequisites). +// Drop an index... +$table->char('postal_code', 10)->unique(false)->change(); +``` -#### Renaming Columns +### Renaming Columns -To rename a column, you may use the `renameColumn` method provided by the schema builder blueprint. Before renaming a column, ensure that you have installed the `doctrine/dbal` library via the Composer package manager: +To rename a column, you may use the `renameColumn` method provided by the schema builder: - Schema::table('users', function (Blueprint $table) { - $table->renameColumn('from', 'to'); - }); - -> {note} Renaming an `enum` column is not currently supported. +```php +Schema::table('users', function (Blueprint $table) { + $table->renameColumn('from', 'to'); +}); +``` ### Dropping Columns -To drop a column, you may use the `dropColumn` method on the schema builder blueprint. If your application is utilizing an SQLite database, you must install the `doctrine/dbal` package via the Composer package manager before the `dropColumn` method may be used: +To drop a column, you may use the `dropColumn` method on the schema builder: - Schema::table('users', function (Blueprint $table) { - $table->dropColumn('votes'); - }); +```php +Schema::table('users', function (Blueprint $table) { + $table->dropColumn('votes'); +}); +``` You may drop multiple columns from a table by passing an array of column names to the `dropColumn` method: - Schema::table('users', function (Blueprint $table) { - $table->dropColumn(['votes', 'avatar', 'location']); - }); - -> {note} Dropping or modifying multiple columns within a single migration while using an SQLite database is not supported. +```php +Schema::table('users', function (Blueprint $table) { + $table->dropColumn(['votes', 'avatar', 'location']); +}); +``` #### Available Command Aliases Laravel provides several convenient methods related to dropping common types of columns. Each of these methods is described in the table below: -Command | Description -------- | ----------- -`$table->dropMorphs('morphable');` | Drop the `morphable_id` and `morphable_type` columns. -`$table->dropRememberToken();` | Drop the `remember_token` column. -`$table->dropSoftDeletes();` | Drop the `deleted_at` column. -`$table->dropSoftDeletesTz();` | Alias of `dropSoftDeletes()` method. -`$table->dropTimestamps();` | Drop the `created_at` and `updated_at` columns. -`$table->dropTimestampsTz();` | Alias of `dropTimestamps()` method. +
+ +| Command | Description | +| ----------------------------------- | ----------------------------------------------------- | +| `$table->dropMorphs('morphable');` | Drop the `morphable_id` and `morphable_type` columns. | +| `$table->dropRememberToken();` | Drop the `remember_token` column. | +| `$table->dropSoftDeletes();` | Drop the `deleted_at` column. | +| `$table->dropSoftDeletesTz();` | Alias of `dropSoftDeletes()` method. | +| `$table->dropTimestamps();` | Drop the `created_at` and `updated_at` columns. | +| `$table->dropTimestampsTz();` | Alias of `dropTimestamps()` method. | + +
## Indexes @@ -1043,164 +1356,202 @@ Command | Description The Laravel schema builder supports several types of indexes. The following example creates a new `email` column and specifies that its values should be unique. To create the index, we can chain the `unique` method onto the column definition: - use Illuminate\Database\Schema\Blueprint; - use Illuminate\Support\Facades\Schema; +```php +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; - Schema::table('users', function (Blueprint $table) { - $table->string('email')->unique(); - }); +Schema::table('users', function (Blueprint $table) { + $table->string('email')->unique(); +}); +``` Alternatively, you may create the index after defining the column. To do so, you should call the `unique` method on the schema builder blueprint. This method accepts the name of the column that should receive a unique index: - $table->unique('email'); +```php +$table->unique('email'); +``` You may even pass an array of columns to an index method to create a compound (or composite) index: - $table->index(['account_id', 'created_at']); +```php +$table->index(['account_id', 'created_at']); +``` When creating an index, Laravel will automatically generate an index name based on the table, column names, and the index type, but you may pass a second argument to the method to specify the index name yourself: - $table->unique('email', 'unique_email'); +```php +$table->unique('email', 'unique_email'); +``` #### Available Index Types Laravel's schema builder blueprint class provides methods for creating each type of index supported by Laravel. Each index method accepts an optional second argument to specify the name of the index. If omitted, the name will be derived from the names of the table and column(s) used for the index, as well as the index type. Each of the available index methods is described in the table below: -Command | Description -------- | ----------- -`$table->primary('id');` | Adds a primary key. -`$table->primary(['id', 'parent_id']);` | Adds composite keys. -`$table->unique('email');` | Adds a unique index. -`$table->index('state');` | Adds an index. -`$table->fullText('body');` | Adds a full text index (MySQL/PostgreSQL). -`$table->fullText('body')->language('english');` | Adds a full text index of the specified language (PostgreSQL). -`$table->spatialIndex('location');` | Adds a spatial index (except SQLite). - - -#### Index Lengths & MySQL / MariaDB +
-By default, Laravel uses the `utf8mb4` character set. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure the default string length by calling the `Schema::defaultStringLength` method within the `boot` method of your `App\Providers\AppServiceProvider` class: +| Command | Description | +| ------------------------------------------------ | -------------------------------------------------------------- | +| `$table->primary('id');` | Adds a primary key. | +| `$table->primary(['id', 'parent_id']);` | Adds composite keys. | +| `$table->unique('email');` | Adds a unique index. | +| `$table->index('state');` | Adds an index. | +| `$table->fullText('body');` | Adds a full text index (MariaDB / MySQL / PostgreSQL). | +| `$table->fullText('body')->language('english');` | Adds a full text index of the specified language (PostgreSQL). | +| `$table->spatialIndex('location');` | Adds a spatial index (except SQLite). | - use Illuminate\Support\Facades\Schema; - - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - Schema::defaultStringLength(191); - } - -Alternatively, you may enable the `innodb_large_prefix` option for your database. Refer to your database's documentation for instructions on how to properly enable this option. +
### Renaming Indexes To rename an index, you may use the `renameIndex` method provided by the schema builder blueprint. This method accepts the current index name as its first argument and the desired name as its second argument: - $table->renameIndex('from', 'to') +```php +$table->renameIndex('from', 'to') +``` ### Dropping Indexes To drop an index, you must specify the index's name. By default, Laravel automatically assigns an index name based on the table name, the name of the indexed column, and the index type. Here are some examples: -Command | Description -------- | ----------- -`$table->dropPrimary('users_id_primary');` | Drop a primary key from the "users" table. -`$table->dropUnique('users_email_unique');` | Drop a unique index from the "users" table. -`$table->dropIndex('geo_state_index');` | Drop a basic index from the "geo" table. -`$table->dropSpatialIndex('geo_location_spatialindex');` | Drop a spatial index from the "geo" table (except SQLite). +
+ +| Command | Description | +| -------------------------------------------------------- | ----------------------------------------------------------- | +| `$table->dropPrimary('users_id_primary');` | Drop a primary key from the "users" table. | +| `$table->dropUnique('users_email_unique');` | Drop a unique index from the "users" table. | +| `$table->dropIndex('geo_state_index');` | Drop a basic index from the "geo" table. | +| `$table->dropFullText('posts_body_fulltext');` | Drop a full text index from the "posts" table. | +| `$table->dropSpatialIndex('geo_location_spatialindex');` | Drop a spatial index from the "geo" table (except SQLite). | + +
If you pass an array of columns into a method that drops indexes, the conventional index name will be generated based on the table name, columns, and index type: - Schema::table('geo', function (Blueprint $table) { - $table->dropIndex(['state']); // Drops index 'geo_state_index' - }); +```php +Schema::table('geo', function (Blueprint $table) { + $table->dropIndex(['state']); // Drops index 'geo_state_index' +}); +``` ### Foreign Key Constraints Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a `user_id` column on the `posts` table that references the `id` column on a `users` table: - use Illuminate\Database\Schema\Blueprint; - use Illuminate\Support\Facades\Schema; +```php +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; - Schema::table('posts', function (Blueprint $table) { - $table->unsignedBigInteger('user_id'); +Schema::table('posts', function (Blueprint $table) { + $table->unsignedBigInteger('user_id'); - $table->foreign('user_id')->references('id')->on('users'); - }); + $table->foreign('user_id')->references('id')->on('users'); +}); +``` Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better developer experience. When using the `foreignId` method to create your column, the example above can be rewritten like so: - Schema::table('posts', function (Blueprint $table) { - $table->foreignId('user_id')->constrained(); - }); +```php +Schema::table('posts', function (Blueprint $table) { + $table->foreignId('user_id')->constrained(); +}); +``` -The `foreignId` method creates an `UNSIGNED BIGINT` equivalent column, while the `constrained` method will use conventions to determine the table and column name being referenced. If your table name does not match Laravel's conventions, you may specify the table name by passing it as an argument to the `constrained` method: +The `foreignId` method creates an `UNSIGNED BIGINT` equivalent column, while the `constrained` method will use conventions to determine the table and column being referenced. If your table name does not match Laravel's conventions, you may manually provide it to the `constrained` method. In addition, the name that should be assigned to the generated index may be specified as well: - Schema::table('posts', function (Blueprint $table) { - $table->foreignId('user_id')->constrained('users'); - }); +```php +Schema::table('posts', function (Blueprint $table) { + $table->foreignId('user_id')->constrained( + table: 'users', indexName: 'posts_user_id' + ); +}); +``` You may also specify the desired action for the "on delete" and "on update" properties of the constraint: - $table->foreignId('user_id') - ->constrained() - ->onUpdate('cascade') - ->onDelete('cascade'); +```php +$table->foreignId('user_id') + ->constrained() + ->onUpdate('cascade') + ->onDelete('cascade'); +``` An alternative, expressive syntax is also provided for these actions: -Method | Description -------- | ----------- -`$table->cascadeOnUpdate();` | Updates should cascade. -`$table->restrictOnUpdate();`| Updates should be restricted. -`$table->cascadeOnDelete();` | Deletes should cascade. -`$table->restrictOnDelete();`| Deletes should be restricted. -`$table->nullOnDelete();` | Deletes should set the foreign key value to null. +
+ +| Method | Description | +| ----------------------------- | ------------------------------------------------- | +| `$table->cascadeOnUpdate();` | Updates should cascade. | +| `$table->restrictOnUpdate();` | Updates should be restricted. | +| `$table->nullOnUpdate();` | Updates should set the foreign key value to null. | +| `$table->noActionOnUpdate();` | No action on updates. | +| `$table->cascadeOnDelete();` | Deletes should cascade. | +| `$table->restrictOnDelete();` | Deletes should be restricted. | +| `$table->nullOnDelete();` | Deletes should set the foreign key value to null. | +| `$table->noActionOnDelete();` | Prevents deletes if child records exist. | + +
Any additional [column modifiers](#column-modifiers) must be called before the `constrained` method: - $table->foreignId('user_id') - ->nullable() - ->constrained(); +```php +$table->foreignId('user_id') + ->nullable() + ->constrained(); +``` #### Dropping Foreign Keys To drop a foreign key, you may use the `dropForeign` method, passing the name of the foreign key constraint to be deleted as an argument. Foreign key constraints use the same naming convention as indexes. In other words, the foreign key constraint name is based on the name of the table and the columns in the constraint, followed by a "\_foreign" suffix: - $table->dropForeign('posts_user_id_foreign'); +```php +$table->dropForeign('posts_user_id_foreign'); +``` Alternatively, you may pass an array containing the column name that holds the foreign key to the `dropForeign` method. The array will be converted to a foreign key constraint name using Laravel's constraint naming conventions: - $table->dropForeign(['user_id']); +```php +$table->dropForeign(['user_id']); +``` #### Toggling Foreign Key Constraints You may enable or disable foreign key constraints within your migrations by using the following methods: - Schema::enableForeignKeyConstraints(); +```php +Schema::enableForeignKeyConstraints(); - Schema::disableForeignKeyConstraints(); +Schema::disableForeignKeyConstraints(); -> {note} SQLite disables foreign key constraints by default. When using SQLite, make sure to [enable foreign key support](/docs/{{version}}/database#configuration) in your database configuration before attempting to create them in your migrations. In addition, SQLite only supports foreign keys upon creation of the table and [not when tables are altered](https://www.sqlite.org/omitted.html). +Schema::withoutForeignKeyConstraints(function () { + // Constraints disabled within this closure... +}); +``` + +> [!WARNING] +> SQLite disables foreign key constraints by default. When using SQLite, make sure to [enable foreign key support](/docs/{{version}}/database#configuration) in your database configuration before attempting to create them in your migrations. ## Events For convenience, each migration operation will dispatch an [event](/docs/{{version}}/events). All of the following events extend the base `Illuminate\Database\Events\MigrationEvent` class: - Class | Description --------|------- -| `Illuminate\Database\Events\MigrationsStarted` | A batch of migrations is about to be executed. | -| `Illuminate\Database\Events\MigrationsEnded` | A batch of migrations has finished executing. | -| `Illuminate\Database\Events\MigrationStarted` | A single migration is about to be executed. | -| `Illuminate\Database\Events\MigrationEnded` | A single migration has finished executing. | +
+ +| Class | Description | +| ------------------------------------------------ | ------------------------------------------------ | +| `Illuminate\Database\Events\MigrationsStarted` | A batch of migrations is about to be executed. | +| `Illuminate\Database\Events\MigrationsEnded` | A batch of migrations has finished executing. | +| `Illuminate\Database\Events\MigrationStarted` | A single migration is about to be executed. | +| `Illuminate\Database\Events\MigrationEnded` | A single migration has finished executing. | +| `Illuminate\Database\Events\NoPendingMigrations` | A migration command found no pending migrations. | +| `Illuminate\Database\Events\SchemaDumped` | A database schema dump has completed. | +| `Illuminate\Database\Events\SchemaLoaded` | An existing database schema dump has loaded. | +
diff --git a/mix.md b/mix.md index fc6c7b07ab3..1d8259c51d4 100644 --- a/mix.md +++ b/mix.md @@ -1,27 +1,13 @@ -# Compiling Assets (Mix) +# Laravel Mix - [Introduction](#introduction) -- [Installation & Setup](#installation) -- [Running Mix](#running-mix) -- [Working With Stylesheets](#working-with-stylesheets) - - [Tailwind CSS](#tailwindcss) - - [PostCSS](#postcss) - - [Sass](#sass) - - [URL Processing](#url-processing) - - [Source Maps](#css-source-maps) -- [Working With JavaScript](#working-with-scripts) - - [Vue](#vue) - - [React](#react) - - [Vendor Extraction](#vendor-extraction) - - [Custom Webpack Configuration](#custom-webpack-configuration) -- [Versioning / Cache Busting](#versioning-and-cache-busting) -- [Browsersync Reloading](#browsersync-reloading) -- [Environment Variables](#environment-variables) -- [Notifications](#notifications) ## Introduction +> [!WARNING] +> Laravel Mix is a legacy package that is no longer actively maintained. [Vite](/docs/{{version}}/vite) may be used as a modern alternative. + [Laravel Mix](https://github.com/laravel-mix/laravel-mix), a package developed by [Laracasts](https://laracasts.com) creator Jeffrey Way, provides a fluent API for defining [webpack](https://webpack.js.org) build steps for your Laravel application using several common CSS and JavaScript pre-processors. In other words, Mix makes it a cinch to compile and minify your application's CSS and JavaScript files. Through simple method chaining, you can fluently define your asset pipeline. For example: @@ -33,401 +19,5 @@ mix.js('resources/js/app.js', 'public/js') If you've ever been confused and overwhelmed about getting started with webpack and asset compilation, you will love Laravel Mix. However, you are not required to use it while developing your application; you are free to use any asset pipeline tool you wish, or even none at all. -> {tip} If you need a head start building your application with Laravel and [Tailwind CSS](https://tailwindcss.com), check out one of our [application starter kits](/docs/{{version}}/starter-kits). - - -## Installation & Setup - - -#### Installing Node - -Before running Mix, you must first ensure that Node.js and NPM are installed on your machine: - -```shell -node -v -npm -v -``` - -You can easily install the latest version of Node and NPM using simple graphical installers from [the official Node website](https://nodejs.org/en/download/). Or, if you are using [Laravel Sail](/docs/{{version}}/sail), you may invoke Node and NPM through Sail: - -```shell -./sail node -v -./sail npm -v -``` - - -#### Installing Laravel Mix - -The only remaining step is to install Laravel Mix. Within a fresh installation of Laravel, you'll find a `package.json` file in the root of your directory structure. The default `package.json` file already includes everything you need to get started using Laravel Mix. Think of this file like your `composer.json` file, except it defines Node dependencies instead of PHP dependencies. You may install the dependencies it references by running: - -```shell -npm install -``` - - -## Running Mix - -Mix is a configuration layer on top of [webpack](https://webpack.js.org), so to run your Mix tasks you only need to execute one of the NPM scripts that are included in the default Laravel `package.json` file. When you run the `dev` or `production` scripts, all of your application's CSS and JavaScript assets will be compiled and placed in your application's `public` directory: - -```shell -// Run all Mix tasks... -npm run dev - -// Run all Mix tasks and minify output... -npm run prod -``` - - -#### Watching Assets For Changes - -The `npm run watch` command will continue running in your terminal and watch all relevant CSS and JavaScript files for changes. Webpack will automatically recompile your assets when it detects a change to one of these files: - -```shell -npm run watch -``` - -Webpack may not be able to detect your file changes in certain local development environments. If this is the case on your system, consider using the `watch-poll` command: - -```shell -npm run watch-poll -``` - - -## Working With Stylesheets - -Your application's `webpack.mix.js` file is your entry point for all asset compilation. Think of it as a light configuration wrapper around [webpack](https://webpack.js.org). Mix tasks can be chained together to define exactly how your assets should be compiled. - - -### Tailwind CSS - -[Tailwind CSS](https://tailwindcss.com) is a modern, utility-first framework for building amazing sites without ever leaving your HTML. Let's dig into how to start using it in a Laravel project with Laravel Mix. First, we should install Tailwind using NPM and generate our Tailwind configuration file: - -```shell -npm install - -npm install -D tailwindcss - -npx tailwindcss init -``` - -The `init` command will generate a `tailwind.config.js` file. The `content` section of this file allows you to configure the paths to all of your HTML templates, JavaScript components, and any other source files that contain Tailwind class names so that any CSS classes that are not used within these files will be purged from your production CSS build: - -```js -content: [ - './storage/framework/views/*.php', - './resources/**/*.blade.php', - './resources/**/*.js', - './resources/**/*.vue', -], -``` - -Next, you should add each of Tailwind's "layers" to your application's `resources/css/app.css` file: - -```css -@tailwind base; -@tailwind components; -@tailwind utilities; -``` - -Once you have configured Tailwind's layers, you are ready to update your application's `webpack.mix.js` file to compile your Tailwind powered CSS: - -```js -mix.js('resources/js/app.js', 'public/js') - .postCss('resources/css/app.css', 'public/css', [ - require('tailwindcss'), - ]); -``` - -Finally, you should reference your stylesheet in your application's primary layout template. Many applications choose to store this template at `resources/views/layouts/app.blade.php`. In addition, ensure you add the responsive viewport `meta` tag if it's not already present: - -```blade - - - - - -``` - - -### PostCSS - -[PostCSS](https://postcss.org/), a powerful tool for transforming your CSS, is included with Laravel Mix out of the box. By default, Mix leverages the popular [Autoprefixer](https://github.com/postcss/autoprefixer) plugin to automatically apply all necessary CSS3 vendor prefixes. However, you're free to add any additional plugins that are appropriate for your application. - -First, install the desired plugin through NPM and include it in your array of plugins when calling Mix's `postCss` method. The `postCss` method accepts the path to your CSS file as its first argument and the directory where the compiled file should be placed as its second argument: - -```js -mix.postCss('resources/css/app.css', 'public/css', [ - require('postcss-custom-properties') -]); -``` - -Or, you may execute `postCss` with no additional plugins in order to achieve simple CSS compilation and minification: - -```js -mix.postCss('resources/css/app.css', 'public/css'); -``` - - -### Sass - -The `sass` method allows you to compile [Sass](https://sass-lang.com/) into CSS that can be understood by web browsers. The `sass` method accepts the path to your Sass file as its first argument and the directory where the compiled file should be placed as its second argument: - -```js -mix.sass('resources/sass/app.scss', 'public/css'); -``` - -You may compile multiple Sass files into their own respective CSS files and even customize the output directory of the resulting CSS by calling the `sass` method multiple times: - -```js -mix.sass('resources/sass/app.sass', 'public/css') - .sass('resources/sass/admin.sass', 'public/css/admin'); -``` - - -### URL Processing - -Because Laravel Mix is built on top of webpack, it's important to understand a few webpack concepts. For CSS compilation, webpack will rewrite and optimize any `url()` calls within your stylesheets. While this might initially sound strange, it's an incredibly powerful piece of functionality. Imagine that we want to compile Sass that includes a relative URL to an image: - -```css -.example { - background: url('https://github.com/images/example.png'); -} -``` - -> {note} Absolute paths for any given `url()` will be excluded from URL-rewriting. For example, `url('https://github.com/images/thing.png')` or `url('http://example.com/images/thing.png')` won't be modified. - -By default, Laravel Mix and webpack will find `example.png`, copy it to your `public/images` folder, and then rewrite the `url()` within your generated stylesheet. As such, your compiled CSS will be: - -```css -.example { - background: url(https://github.com/images/example.png?d41d8cd98f00b204e9800998ecf8427e); -} -``` - -As useful as this feature may be, your existing folder structure may already be configured in a way you like. If this is the case, you may disable `url()` rewriting like so: - -```js -mix.sass('resources/sass/app.scss', 'public/css').options({ - processCssUrls: false -}); -``` - -With this addition to your `webpack.mix.js` file, Mix will no longer match any `url()` or copy assets to your public directory. In other words, the compiled CSS will look just like how you originally typed it: - -```css -.example { - background: url("https://github.com/images/thing.png"); -} -``` - - -### Source Maps - -Though disabled by default, source maps may be activated by calling the `mix.sourceMaps()` method in your `webpack.mix.js` file. Though it comes with a compile/performance cost, this will provide extra debugging information to your browser's developer tools when using compiled assets: - -```js -mix.js('resources/js/app.js', 'public/js') - .sourceMaps(); -``` - - -#### Style Of Source Mapping - -Webpack offers a variety of [source mapping styles](https://webpack.js.org/configuration/devtool/#devtool). By default, Mix's source mapping style is set to `eval-source-map`, which provides a fast rebuild time. If you want to change the mapping style, you may do so using the `sourceMaps` method: - -```js -let productionSourceMaps = false; - -mix.js('resources/js/app.js', 'public/js') - .sourceMaps(productionSourceMaps, 'source-map'); -``` - - -## Working With JavaScript - -Mix provides several features to help you work with your JavaScript files, such as compiling modern ECMAScript, module bundling, minification, and concatenating plain JavaScript files. Even better, this all works seamlessly, without requiring an ounce of custom configuration: - -```js -mix.js('resources/js/app.js', 'public/js'); -``` - -With this single line of code, you may now take advantage of: - -
- -- The latest EcmaScript syntax. -- Modules -- Minification for production environments. - -
- - -### Vue - -Mix will automatically install the Babel plugins necessary for Vue single-file component compilation support when using the `vue` method. No further configuration is required: - -```js -mix.js('resources/js/app.js', 'public/js') - .vue(); -``` - -Once your JavaScript has been compiled, you can reference it in your application: - -```blade - - - - - -``` - - -### React - -Mix can automatically install the Babel plugins necessary for React support. To get started, add a call to the `react` method: - -```js -mix.js('resources/js/app.jsx', 'public/js') - .react(); -``` - -Behind the scenes, Mix will download and include the appropriate `babel-preset-react` Babel plugin. Once your JavaScript has been compiled, you can reference it in your application: - -```blade - - - - - -``` - - -### Vendor Extraction - -One potential downside to bundling all of your application-specific JavaScript with your vendor libraries such as React and Vue is that it makes long-term caching more difficult. For example, a single update to your application code will force the browser to re-download all of your vendor libraries even if they haven't changed. - -If you intend to make frequent updates to your application's JavaScript, you should consider extracting all of your vendor libraries into their own file. This way, a change to your application code will not affect the caching of your large `vendor.js` file. Mix's `extract` method makes this a breeze: - -```js -mix.js('resources/js/app.js', 'public/js') - .extract(['vue']) -``` - -The `extract` method accepts an array of all libraries or modules that you wish to extract into a `vendor.js` file. Using the snippet above as an example, Mix will generate the following files: - -
- -- `public/js/manifest.js`: *The Webpack manifest runtime* -- `public/js/vendor.js`: *Your vendor libraries* -- `public/js/app.js`: *Your application code* - -
- -To avoid JavaScript errors, be sure to load these files in the proper order: - -```html - - - -``` - - -### Custom Webpack Configuration - -Occasionally, you may need to manually modify the underlying Webpack configuration. For example, you might have a special loader or plugin that needs to be referenced. - -Mix provides a useful `webpackConfig` method that allows you to merge any short Webpack configuration overrides. This is particularly appealing, as it doesn't require you to copy and maintain your own copy of the `webpack.config.js` file. The `webpackConfig` method accepts an object, which should contain any [Webpack-specific configuration](https://webpack.js.org/configuration/) that you wish to apply. - -```js -mix.webpackConfig({ - resolve: { - modules: [ - path.resolve(__dirname, 'vendor/laravel/spark/resources/assets/js') - ] - } -}); -``` - - -## Versioning / Cache Busting - -Many developers suffix their compiled assets with a timestamp or unique token to force browsers to load the fresh assets instead of serving stale copies of the code. Mix can automatically handle this for you using the `version` method. - -The `version` method will append a unique hash to the filenames of all compiled files, allowing for more convenient cache busting: - -```js -mix.js('resources/js/app.js', 'public/js') - .version(); -``` - -After generating the versioned file, you won't know the exact filename. So, you should use Laravel's global `mix` function within your [views](/docs/{{version}}/views) to load the appropriately hashed asset. The `mix` function will automatically determine the current name of the hashed file: - -```blade - -``` - -Because versioned files are usually unnecessary in development, you may instruct the versioning process to only run during `npm run prod`: - -```js -mix.js('resources/js/app.js', 'public/js'); - -if (mix.inProduction()) { - mix.version(); -} -``` - - -#### Custom Mix Base URLs - -If your Mix compiled assets are deployed to a CDN separate from your application, you will need to change the base URL generated by the `mix` function. You may do so by adding a `mix_url` configuration option to your application's `config/app.php` configuration file: - - 'mix_url' => env('MIX_ASSET_URL', null) - -After configuring the Mix URL, The `mix` function will prefix the configured URL when generating URLs to assets: - -```shell -https://cdn.example.com/js/app.js?id=1964becbdd96414518cd -``` - - -## Browsersync Reloading - -[BrowserSync](https://browsersync.io/) can automatically monitor your files for changes, and inject your changes into the browser without requiring a manual refresh. You may enable support for this by calling the `mix.browserSync()` method: - -```js -mix.browserSync('laravel.test'); -``` - -[BrowserSync options](https://browsersync.io/docs/options) may be specified by passing a JavaScript object to the `browserSync` method: - -```js -mix.browserSync({ - proxy: 'laravel.test' -}); -``` - -Next, start webpack's development server using the `npm run watch` command. Now, when you modify a script or PHP file you can watch as the browser instantly refreshes the page to reflect your changes. - - -## Environment Variables - -You may inject environment variables into your `webpack.mix.js` script by prefixing one of the environment variables in your `.env` file with `MIX_`: - -```ini -MIX_SENTRY_DSN_PUBLIC=http://example.com -``` - -After the variable has been defined in your `.env` file, you may access it via the `process.env` object. However, you will need to restart the task if the environment variable's value changes while the task is running: - -```js -process.env.MIX_SENTRY_DSN_PUBLIC -``` - - -## Notifications - -When available, Mix will automatically display OS notifications when compiling, giving you instant feedback as to whether the compilation was successful or not. However, there may be instances when you would prefer to disable these notifications. One such example might be triggering Mix on your production server. Notifications may be deactivated using the `disableNotifications` method: - -```js -mix.disableNotifications(); -``` +> [!NOTE] +> Vite has replaced Laravel Mix in new Laravel installations. For Mix documentation, please visit the [official Laravel Mix](https://laravel-mix.com/) website. If you would like to switch to Vite, please see our [Vite migration guide](https://github.com/laravel/vite-plugin/blob/main/UPGRADE.md#migrating-from-laravel-mix-to-vite). diff --git a/mocking.md b/mocking.md index e5d609a5abd..2f1eef67ce8 100644 --- a/mocking.md +++ b/mocking.md @@ -4,17 +4,6 @@ - [Mocking Objects](#mocking-objects) - [Mocking Facades](#mocking-facades) - [Facade Spies](#facade-spies) -- [Bus Fake](#bus-fake) - - [Job Chains](#bus-job-chains) - - [Job Batches](#job-batches) -- [Event Fake](#event-fake) - - [Scoped Event Fakes](#scoped-event-fakes) -- [HTTP Fake](#http-fake) -- [Mail Fake](#mail-fake) -- [Notification Fake](#notification-fake) -- [Queue Fake](#queue-fake) - - [Job Chains](#job-chains) -- [Storage Fake](#storage-fake) - [Interacting With Time](#interacting-with-time) @@ -29,604 +18,280 @@ Laravel provides helpful methods for mocking events, jobs, and other facades out When mocking an object that is going to be injected into your application via Laravel's [service container](/docs/{{version}}/container), you will need to bind your mocked instance into the container as an `instance` binding. This will instruct the container to use your mocked instance of the object instead of constructing the object itself: - use App\Service; - use Mockery; - use Mockery\MockInterface; - - public function test_something_can_be_mocked() - { - $this->instance( - Service::class, - Mockery::mock(Service::class, function (MockInterface $mock) { - $mock->shouldReceive('process')->once(); - }) - ); - } +```php tab=Pest +use App\Service; +use Mockery; +use Mockery\MockInterface; + +test('something can be mocked', function () { + $this->instance( + Service::class, + Mockery::mock(Service::class, function (MockInterface $mock) { + $mock->expects('process'); + }) + ); +}); +``` + +```php tab=PHPUnit +use App\Service; +use Mockery; +use Mockery\MockInterface; + +public function test_something_can_be_mocked(): void +{ + $this->instance( + Service::class, + Mockery::mock(Service::class, function (MockInterface $mock) { + $mock->expects('process'); + }) + ); +} +``` In order to make this more convenient, you may use the `mock` method that is provided by Laravel's base test case class. For example, the following example is equivalent to the example above: - use App\Service; - use Mockery\MockInterface; +```php +use App\Service; +use Mockery\MockInterface; - $mock = $this->mock(Service::class, function (MockInterface $mock) { - $mock->shouldReceive('process')->once(); - }); +$mock = $this->mock(Service::class, function (MockInterface $mock) { + $mock->expects('process'); +}); +``` You may use the `partialMock` method when you only need to mock a few methods of an object. The methods that are not mocked will be executed normally when called: - use App\Service; - use Mockery\MockInterface; +```php +use App\Service; +use Mockery\MockInterface; - $mock = $this->partialMock(Service::class, function (MockInterface $mock) { - $mock->shouldReceive('process')->once(); - }); +$mock = $this->partialMock(Service::class, function (MockInterface $mock) { + $mock->expects('process'); +}); +``` Similarly, if you want to [spy](http://docs.mockery.io/en/latest/reference/spies.html) on an object, Laravel's base test case class offers a `spy` method as a convenient wrapper around the `Mockery::spy` method. Spies are similar to mocks; however, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed: - use App\Service; +```php +use App\Service; - $spy = $this->spy(Service::class); +$spy = $this->spy(Service::class); - // ... +// ... - $spy->shouldHaveReceived('process'); +$spy->shouldHaveReceived('process'); +``` ## Mocking Facades Unlike traditional static method calls, [facades](/docs/{{version}}/facades) (including [real-time facades](/docs/{{version}}/facades#real-time-facades)) may be mocked. This provides a great advantage over traditional static methods and grants you the same testability that you would have if you were using traditional dependency injection. When testing, you may often want to mock a call to a Laravel facade that occurs in one of your controllers. For example, consider the following controller action: - once() - ->with('key') - ->andReturn('value'); - - $response = $this->get('/users'); - - // ... - } - } - -> {note} You should not mock the `Request` facade. Instead, pass the input you desire into the [HTTP testing methods](/docs/{{version}}/http-tests) such as `get` and `post` when running your test. Likewise, instead of mocking the `Config` facade, call the `Config::set` method in your tests. - - -### Facade Spies - -If you would like to [spy](http://docs.mockery.io/en/latest/reference/spies.html) on a facade, you may call the `spy` method on the corresponding facade. Spies are similar to mocks; however, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed: - - use Illuminate\Support\Facades\Cache; - - public function test_values_are_be_stored_in_cache() - { - Cache::spy(); - - $response = $this->get('/'); - - $response->assertStatus(200); - - Cache::shouldHaveReceived('put')->once()->with('name', 'Taylor', 10); - } - - -## Bus Fake - -When testing code that dispatches jobs, you typically want to assert that a given job was dispatched but not actually queue or execute the job. This is because the job's execution can normally be tested in a separate test class. - -You may use the `Bus` facade's `fake` method to prevent jobs from being dispatched to the queue. Then, after executing the code under test, you may inspect which jobs the application attempted to dispatch using the `assertDispatched` and `assertNotDispatched` methods: - - order->id === $order->id; - }); - - -### Job Chains - -The `Bus` facade's `assertChained` method may be used to assert that a [chain of jobs](/docs/{{version}}/queues#job-chaining) was dispatched. The `assertChained` method accepts an array of chained jobs as its first argument: - - use App\Jobs\RecordShipment; - use App\Jobs\ShipOrder; - use App\Jobs\UpdateInventory; - use Illuminate\Support\Facades\Bus; - - Bus::assertChained([ - ShipOrder::class, - RecordShipment::class, - UpdateInventory::class - ]); - -As you can see in the example above, the array of chained jobs may be an array of the job's class names. However, you may also provide an array of actual job instances. When doing so, Laravel will ensure that the job instances are of the same class and have the same property values of the chained jobs dispatched by your application: - - Bus::assertChained([ - new ShipOrder, - new RecordShipment, - new UpdateInventory, - ]); - - -### Job Batches - -The `Bus` facade's `assertBatched` method may be used to assert that a [batch of jobs](/docs/{{version}}/queues#job-batching) was dispatched. The closure given to the `assertBatched` method receives an instance of `Illuminate\Bus\PendingBatch`, which may be used to inspect the jobs within the batch: - - use Illuminate\Bus\PendingBatch; - use Illuminate\Support\Facades\Bus; - - Bus::assertBatched(function (PendingBatch $batch) { - return $batch->name == 'import-csv' && - $batch->jobs->count() === 10; - }); - - -## Event Fake - -When testing code that dispatches events, you may wish to instruct Laravel to not actually execute the event's listeners. Using the `Event` facade's `fake` method, you may prevent listeners from executing, execute the code under test, and then assert which events were dispatched by your application using the `assertDispatched`, `assertNotDispatched`, and `assertNothingDispatched` methods: - - order->id === $order->id; - }); +namespace App\Http\Controllers; -If you would simply like to assert that an event listener is listening to a given event, you may use the `assertListening` method: - - Event::assertListening( - OrderShipped::class, - SendShipmentNotification::class - ); - -> {note} After calling `Event::fake()`, no event listeners will be executed. So, if your tests use model factories that rely on events, such as creating a UUID during a model's `creating` event, you should call `Event::fake()` **after** using your factories. - - -#### Faking A Subset Of Events - -If you only want to fake event listeners for a specific set of events, you may pass them to the `fake` or `fakeFor` method: +use Illuminate\Support\Facades\Cache; +class UserController extends Controller +{ /** - * Test order process. + * Retrieve a list of all users of the application. */ - public function test_orders_can_be_processed() - { - Event::fake([ - OrderCreated::class, - ]); - - $order = Order::factory()->create(); - - Event::assertDispatched(OrderCreated::class); - - // Other events are dispatched as normal... - $order->update([...]); - } - - -### Scoped Event Fakes - -If you only want to fake event listeners for a portion of your test, you may use the `fakeFor` method: - - create(); - - Event::assertDispatched(OrderCreated::class); - - return $order; - }); - - // Events are dispatched as normal and observers will run ... - $order->update([...]); - } - } - - -## HTTP Fake - -The `Http` facade's `fake` method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made. For more information on faking outgoing HTTP requests, please consult the [HTTP Client testing documentation](/docs/{{version}}/http-client#testing). - - -## Mail Fake + $value = Cache::get('key'); -You may use the `Mail` facade's `fake` method to prevent mail from being sent. Typically, sending mail is unrelated to the code you are actually testing. Most likely, it is sufficient to simply assert that Laravel was instructed to send a given mailable. - -After calling the `Mail` facade's `fake` method, you may then assert that [mailables](/docs/{{version}}/mail) were instructed to be sent to users and even inspect the data the mailables received: - - order->id === $order->id; - }); - -When calling the `Mail` facade's assertion methods, the mailable instance accepted by the provided closure exposes helpful methods for examining the recipients of the mailable: - - Mail::assertSent(OrderShipped::class, function ($mail) use ($user) { - return $mail->hasTo($user->email) && - $mail->hasCc('...') && - $mail->hasBcc('...'); - }); +We can mock the call to the `Cache` facade by using the `expects` method, which will return an instance of a [Mockery](https://github.com/padraic/mockery) mock. Since facades are actually resolved and managed by the Laravel [service container](/docs/{{version}}/container), they have much more testability than a typical static class. For example, let's mock our call to the `Cache` facade's `get` method: -You may have noticed that there are two methods for asserting that mail was not sent: `assertNotSent` and `assertNotQueued`. Sometimes you may wish to assert that no mail was sent **or** queued. To accomplish this, you may use the `assertNothingOutgoing` and `assertNotOutgoing` methods: +```php tab=Pest +order->id === $order->id; - }); +test('get index', function () { + Cache::expects('get') + ->with('key') + ->andReturn('value'); - -## Notification Fake + $response = $this->get('/users'); -You may use the `Notification` facade's `fake` method to prevent notifications from being sent. Typically, sending notifications is unrelated to the code you are actually testing. Most likely, it is sufficient to simply assert that Laravel was instructed to send a given notification. - -After calling the `Notification` facade's `fake` method, you may then assert that [notifications](/docs/{{version}}/notifications) were instructed to be sent to users and even inspect the data the notifications received: + // ... +}); +``` - with('key') + ->andReturn('value'); - // Assert that no notifications were sent... - Notification::assertNothingSent(); + $response = $this->get('/users'); - // Assert a notification was sent to the given users... - Notification::assertSentTo( - [$user], OrderShipped::class - ); - - // Assert a notification was not sent... - Notification::assertNotSentTo( - [$user], AnotherNotification::class - ); - } + // ... } +} +``` -You may pass a closure to the `assertSentTo` or `assertNotSentTo` methods in order to assert that a notification was sent that passes a given "truth test". If at least one notification was sent that passes the given truth test then the assertion will be successful: - - Notification::assertSentTo( - $user, - function (OrderShipped $notification, $channels) use ($order) { - return $notification->order->id === $order->id; - } - ); - - -#### On-Demand Notifications - -If the code you are testing sends [on-demand notifications](/docs/{{version}}/notifications#on-demand-notifications), you will need to assert that the notification was sent to an `Illuminate\Notifications\AnonymousNotifiable` instance: - - use Illuminate\Notifications\AnonymousNotifiable; - - Notification::assertSentTo( - new AnonymousNotifiable, OrderShipped::class - ); - -By passing a closure as the third argument to the notification assertion methods, you may determine if an on-demand notification was sent to the correct "route" address: - - Notification::assertSentTo( - new AnonymousNotifiable, - OrderShipped::class, - function ($notification, $channels, $notifiable) use ($user) { - return $notifiable->routes['mail'] === $user->email; - } - ); - - -## Queue Fake - -You may use the `Queue` facade's `fake` method to prevent queued jobs from being pushed to the queue. Most likely, it is sufficient to simply assert that Laravel was instructed to push a given job to the queue since the queued jobs themselves may be tested in another test class. - -After calling the `Queue` facade's `fake` method, you may then assert that the application attempted to push jobs to the queue: - - [!WARNING] +> You should not mock the `Request` facade. Instead, pass the input you desire into the [HTTP testing methods](/docs/{{version}}/http-tests) such as `get` and `post` when running your test. Likewise, instead of mocking the `Config` facade, call the `Config::set` method in your tests. - use App\Jobs\AnotherJob; - use App\Jobs\FinalJob; - use App\Jobs\ShipOrder; - use Illuminate\Foundation\Testing\RefreshDatabase; - use Illuminate\Foundation\Testing\WithoutMiddleware; - use Illuminate\Support\Facades\Queue; - use Tests\TestCase; - - class ExampleTest extends TestCase - { - public function test_orders_can_be_shipped() - { - Queue::fake(); - - // Perform order shipping... + +### Facade Spies - // Assert that no jobs were pushed... - Queue::assertNothingPushed(); +If you would like to [spy](http://docs.mockery.io/en/latest/reference/spies.html) on a facade, you may call the `spy` method on the corresponding facade. Spies are similar to mocks; however, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed: - // Assert a job was pushed to a given queue... - Queue::assertPushedOn('queue-name', ShipOrder::class); +```php tab=Pest +get('/'); - Queue::assertPushed(function (ShipOrder $job) use ($order) { - return $job->order->id === $order->id; - }); + $response->assertStatus(200); - -### Job Chains + Cache::shouldHaveReceived('put')->with('name', 'Taylor', 10); +}); +``` -The `Queue` facade's `assertPushedWithChain` and `assertPushedWithoutChain` methods may be used to inspect the job chain of a pushed job. The `assertPushedWithChain` method accepts the primary job as its first argument and an array of chained jobs as its second argument: +```php tab=PHPUnit +use Illuminate\Support\Facades\Cache; - use App\Jobs\RecordShipment; - use App\Jobs\ShipOrder; - use App\Jobs\UpdateInventory; - use Illuminate\Support\Facades\Queue; +public function test_values_are_stored_in_cache(): void +{ + Cache::spy(); - Queue::assertPushedWithChain(ShipOrder::class, [ - RecordShipment::class, - UpdateInventory::class - ]); + $response = $this->get('/'); -As you can see in the example above, the array of chained jobs may be an array of the job's class names. However, you may also provide an array of actual job instances. When doing so, Laravel will ensure that the job instances are of the same class and have the same property values of the chained jobs dispatched by your application: + $response->assertStatus(200); - Queue::assertPushedWithChain(ShipOrder::class, [ - new RecordShipment, - new UpdateInventory, - ]); + Cache::shouldHaveReceived('put')->with('name', 'Taylor', 10); +} +``` -You may use the `assertPushedWithoutChain` method to assert that a job was pushed without a chain of jobs: + +## Interacting With Time - Queue::assertPushedWithoutChain(ShipOrder::class); +When testing, you may occasionally need to modify the time returned by helpers such as `now` or `Illuminate\Support\Carbon::now()`. Thankfully, Laravel's base feature test class includes helpers that allow you to manipulate the current time: - -## Storage Fake +```php tab=Pest +test('time can be manipulated', function () { + // Travel into the future... + $this->travel(5)->milliseconds(); + $this->travel(5)->seconds(); + $this->travel(5)->minutes(); + $this->travel(5)->hours(); + $this->travel(5)->days(); + $this->travel(5)->weeks(); + $this->travel(5)->years(); + + // Travel into the past... + $this->travel(-5)->hours(); + + // Travel to an explicit time... + $this->travelTo(now()->subHours(6)); + + // Return back to the present time... + $this->travelBack(); +}); +``` + +```php tab=PHPUnit +public function test_time_can_be_manipulated(): void +{ + // Travel into the future... + $this->travel(5)->milliseconds(); + $this->travel(5)->seconds(); + $this->travel(5)->minutes(); + $this->travel(5)->hours(); + $this->travel(5)->days(); + $this->travel(5)->weeks(); + $this->travel(5)->years(); + + // Travel into the past... + $this->travel(-5)->hours(); + + // Travel to an explicit time... + $this->travelTo(now()->subHours(6)); + + // Return back to the present time... + $this->travelBack(); +} +``` + +You may also provide a closure to the various time travel methods. The closure will be invoked with time frozen at the specified time. Once the closure has executed, time will resume as normal: + +```php +$this->travel(5)->days(function () { + // Test something five days into the future... +}); + +$this->travelTo(now()->subDays(10), function () { + // Test something during a given moment... +}); +``` + +The `freezeTime` method may be used to freeze the current time. Similarly, the `freezeSecond` method will freeze the current time but at the start of the current second: + +```php +use Illuminate\Support\Carbon; + +// Freeze time and resume normal time after executing closure... +$this->freezeTime(function (Carbon $time) { + // ... +}); -The `Storage` facade's `fake` method allows you to easily generate a fake disk that, combined with the file generation utilities of the `Illuminate\Http\UploadedFile` class, greatly simplifies the testing of file uploads. For example: +// Freeze time at the current second and resume normal time after executing closure... +$this->freezeSecond(function (Carbon $time) { + // ... +}) +``` - create(); - class ExampleTest extends TestCase - { - public function test_albums_can_be_uploaded() - { - Storage::fake('photos'); - - $response = $this->json('POST', '/photos', [ - UploadedFile::fake()->image('photo1.jpg'), - UploadedFile::fake()->image('photo2.jpg') - ]); - - // Assert one or more files were stored... - Storage::disk('photos')->assertExists('photo1.jpg'); - Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']); - - // Assert one or more files were not stored... - Storage::disk('photos')->assertMissing('missing.jpg'); - Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']); - } - } + $this->travel(1)->week(); -For more information on testing file uploads, you may consult the [HTTP testing documentation's information on file uploads](/docs/{{version}}/http-tests#testing-file-uploads). + expect($thread->isLockedByInactivity())->toBeTrue(); +}); +``` -> {tip} By default, the `fake` method will delete all files in its temporary directory. If you would like to keep these files, you may use the "persistentFake" method instead. +```php tab=PHPUnit +use App\Models\Thread; - -## Interacting With Time +public function test_forum_threads_lock_after_one_week_of_inactivity() +{ + $thread = Thread::factory()->create(); -When testing, you may occasionally need to modify the time returned by helpers such as `now` or `Illuminate\Support\Carbon::now()`. Thankfully, Laravel's base feature test class includes helpers that allow you to manipulate the current time: + $this->travel(1)->week(); - public function testTimeCanBeManipulated() - { - // Travel into the future... - $this->travel(5)->milliseconds(); - $this->travel(5)->seconds(); - $this->travel(5)->minutes(); - $this->travel(5)->hours(); - $this->travel(5)->days(); - $this->travel(5)->weeks(); - $this->travel(5)->years(); - - // Travel into the past... - $this->travel(-5)->hours(); - - // Travel to an explicit time... - $this->travelTo(now()->subHours(6)); - - // Return back to the present time... - $this->travelBack(); - } + $this->assertTrue($thread->isLockedByInactivity()); +} +``` diff --git a/mongodb.md b/mongodb.md new file mode 100644 index 00000000000..5aaf4927959 --- /dev/null +++ b/mongodb.md @@ -0,0 +1,99 @@ +# MongoDB + +- [Introduction](#introduction) +- [Installation](#installation) + - [MongoDB Driver](#mongodb-driver) + - [Starting a MongoDB Server](#starting-a-mongodb-server) + - [Install the Laravel MongoDB Package](#install-the-laravel-mongodb-package) +- [Configuration](#configuration) +- [Features](#features) + + +## Introduction + +[MongoDB](https://www.mongodb.com/resources/products/fundamentals/why-use-mongodb) is one of the most popular NoSQL document-oriented database, used for its high write load (useful for analytics or IoT) and high availability (easy to set replica sets with automatic failover). It can also shard the database easily for horizontal scalability and has a powerful query language for doing aggregation, text search or geospatial queries. + +Instead of storing data in tables of rows or columns like SQL databases, each record in a MongoDB database is a document described in BSON, a binary representation of the data. Applications can then retrieve this information in a JSON format. It supports a wide variety of data types, including documents, arrays, embedded documents, and binary data. + +Before using MongoDB with Laravel, we recommend installing and using the `mongodb/laravel-mongodb` package via Composer. The `laravel-mongodb` package is officially maintained by MongoDB, and while MongoDB is natively supported by PHP through the MongoDB driver, the [Laravel MongoDB](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/) package provides a richer integration with Eloquent and other Laravel features: + +```shell +composer require mongodb/laravel-mongodb +``` + + +## Installation + + +### MongoDB Driver + +To connect to a MongoDB database, the `mongodb` PHP extension is required. If you are developing locally using [Laravel Herd](https://herd.laravel.com) or installed PHP via `php.new`, you already have this extension installed on your system. However, if you need to install the extension manually, you may do so via PECL: + +```shell +pecl install mongodb +``` + +For more information on installing the MongoDB PHP extension, check out the [MongoDB PHP extension installation instructions](https://www.php.net/manual/en/mongodb.installation.php). + + +### Starting a MongoDB Server + +The MongoDB Community Server can be used to run MongoDB locally and is available for installation on Windows, macOS, Linux, or as a Docker container. To learn how to install MongoDB, please refer to the [official MongoDB Community installation guide](https://docs.mongodb.com/manual/administration/install-community/). + +The connection string for the MongoDB server can be set in your `.env` file: + +```ini +MONGODB_URI="mongodb://localhost:27017" +MONGODB_DATABASE="laravel_app" +``` + +For hosting MongoDB in the cloud, consider using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). +To access a MongoDB Atlas cluster locally from your application, you will need to [add your own IP address in the cluster's network settings](https://www.mongodb.com/docs/atlas/security/add-ip-address-to-list/) to the project's IP Access List. + +The connection string for MongoDB Atlas can also be set in your `.env` file: + +```ini +MONGODB_URI="mongodb+srv://:@.mongodb.net/?retryWrites=true&w=majority" +MONGODB_DATABASE="laravel_app" +``` + + +### Install the Laravel MongoDB Package + +Finally, use Composer to install the Laravel MongoDB package: + +```shell +composer require mongodb/laravel-mongodb +``` + +> [!NOTE] +> This installation of the package will fail if the `mongodb` PHP extension is not installed. The PHP configuration can differ between the CLI and the web server, so ensure the extension is enabled in both configurations. + + +## Configuration + +You may configure your MongoDB connection via your application's `config/database.php` configuration file. Within this file, add a `mongodb` connection that utilizes the `mongodb` driver: + +```php +'connections' => [ + 'mongodb' => [ + 'driver' => 'mongodb', + 'dsn' => env('MONGODB_URI', 'mongodb://localhost:27017'), + 'database' => env('MONGODB_DATABASE', 'laravel_app'), + ], +], +``` + + +## Features + +Once your configuration is complete, you can use the `mongodb` package and database connection in your application to leverage a variety of powerful features: + +- [Using Eloquent](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/eloquent-models/), models can be stored in MongoDB collections. In addition to the standard Eloquent features, the Laravel MongoDB package provides additional features such as embedded relationships. The package also provides direct access to the MongoDB driver, which can be used to execute operations such as raw queries and aggregation pipelines. +- [Write complex queries](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/query-builder/) using the query builder. +- The `mongodb` [cache driver](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/cache/) is optimized to use MongoDB features such as TTL indexes to automatically clear expired cache entries. +- [Dispatch and process queued jobs](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/queues/) with the `mongodb` queue driver. +- [Storing files in GridFS](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/filesystems/), via the [GridFS Adapter for Flysystem](https://flysystem.thephpleague.com/docs/adapter/gridfs/). +- Most third party packages using a database connection or Eloquent can be used with MongoDB. + +To continue learning how to use MongoDB and Laravel, refer to MongoDB's [Quick Start guide](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/quick-start/). diff --git a/notifications.md b/notifications.md index e2ea7962859..29de44d933d 100644 --- a/notifications.md +++ b/notifications.md @@ -3,54 +3,57 @@ - [Introduction](#introduction) - [Generating Notifications](#generating-notifications) - [Sending Notifications](#sending-notifications) - - [Using The Notifiable Trait](#using-the-notifiable-trait) - - [Using The Notification Facade](#using-the-notification-facade) + - [Using the Notifiable Trait](#using-the-notifiable-trait) + - [Using the Notification Facade](#using-the-notification-facade) - [Specifying Delivery Channels](#specifying-delivery-channels) - [Queueing Notifications](#queueing-notifications) - [On-Demand Notifications](#on-demand-notifications) - [Mail Notifications](#mail-notifications) - [Formatting Mail Messages](#formatting-mail-messages) - - [Customizing The Sender](#customizing-the-sender) - - [Customizing The Recipient](#customizing-the-recipient) - - [Customizing The Subject](#customizing-the-subject) - - [Customizing The Mailer](#customizing-the-mailer) - - [Customizing The Templates](#customizing-the-templates) + - [Customizing the Sender](#customizing-the-sender) + - [Customizing the Recipient](#customizing-the-recipient) + - [Customizing the Subject](#customizing-the-subject) + - [Customizing the Mailer](#customizing-the-mailer) + - [Customizing the Templates](#customizing-the-templates) - [Attachments](#mail-attachments) + - [Adding Tags and Metadata](#adding-tags-metadata) + - [Customizing the Symfony Message](#customizing-the-symfony-message) - [Using Mailables](#using-mailables) - [Previewing Mail Notifications](#previewing-mail-notifications) - [Markdown Mail Notifications](#markdown-mail-notifications) - - [Generating The Message](#generating-the-message) - - [Writing The Message](#writing-the-message) - - [Customizing The Components](#customizing-the-components) + - [Generating the Message](#generating-the-message) + - [Writing the Message](#writing-the-message) + - [Customizing the Components](#customizing-the-components) - [Database Notifications](#database-notifications) - [Prerequisites](#database-prerequisites) - [Formatting Database Notifications](#formatting-database-notifications) - - [Accessing The Notifications](#accessing-the-notifications) - - [Marking Notifications As Read](#marking-notifications-as-read) + - [Accessing the Notifications](#accessing-the-notifications) + - [Marking Notifications as Read](#marking-notifications-as-read) - [Broadcast Notifications](#broadcast-notifications) - [Prerequisites](#broadcast-prerequisites) - [Formatting Broadcast Notifications](#formatting-broadcast-notifications) - - [Listening For Notifications](#listening-for-notifications) + - [Listening for Notifications](#listening-for-notifications) - [SMS Notifications](#sms-notifications) - [Prerequisites](#sms-prerequisites) - [Formatting SMS Notifications](#formatting-sms-notifications) - - [Formatting Shortcode Notifications](#formatting-shortcode-notifications) - - [Customizing The "From" Number](#customizing-the-from-number) - - [Adding A Client Reference](#adding-a-client-reference) + - [Customizing the "From" Number](#customizing-the-from-number) + - [Adding a Client Reference](#adding-a-client-reference) - [Routing SMS Notifications](#routing-sms-notifications) - [Slack Notifications](#slack-notifications) - [Prerequisites](#slack-prerequisites) - [Formatting Slack Notifications](#formatting-slack-notifications) - - [Slack Attachments](#slack-attachments) + - [Slack Interactivity](#slack-interactivity) - [Routing Slack Notifications](#routing-slack-notifications) + - [Notifying External Slack Workspaces](#notifying-external-slack-workspaces) - [Localizing Notifications](#localizing-notifications) +- [Testing](#testing) - [Notification Events](#notification-events) - [Custom Channels](#custom-channels) ## Introduction -In addition to support for [sending email](/docs/{{version}}/mail), Laravel provides support for sending notifications across a variety of delivery channels, including email, SMS (via [Vonage](https://www.vonage.com/communications-apis/), formerly known as Nexmo), and [Slack](https://slack.com). In addition, a variety of [community built notification channels](https://laravel-notification-channels.com/about/#suggesting-a-new-channel) have been created to send notification over dozens of different channels! Notifications may also be stored in a database so they may be displayed in your web interface. +In addition to support for [sending email](/docs/{{version}}/mail), Laravel provides support for sending notifications across a variety of delivery channels, including email, SMS (via [Vonage](https://www.vonage.com/communications-apis/), formerly known as Nexmo), and [Slack](https://slack.com). In addition, a variety of [community built notification channels](https://laravel-notification-channels.com/about/#suggesting-a-new-channel) have been created to send notifications over dozens of different channels! Notifications may also be stored in a database so they may be displayed in your web interface. Typically, notifications should be short, informational messages that notify users of something that occurred in your application. For example, if you are writing a billing application, you might send an "Invoice Paid" notification to your users via the email and SMS channels. @@ -69,206 +72,410 @@ This command will place a fresh notification class in your `app/Notifications` d ## Sending Notifications -### Using The Notifiable Trait +### Using the Notifiable Trait Notifications may be sent in two ways: using the `notify` method of the `Notifiable` trait or using the `Notification` [facade](/docs/{{version}}/facades). The `Notifiable` trait is included on your application's `App\Models\User` model by default: - notify(new InvoicePaid($invoice)); +$user->notify(new InvoicePaid($invoice)); +``` -> {tip} Remember, you may use the `Notifiable` trait on any of your models. You are not limited to only including it on your `User` model. +> [!NOTE] +> Remember, you may use the `Notifiable` trait on any of your models. You are not limited to only including it on your `User` model. -### Using The Notification Facade +### Using the Notification Facade Alternatively, you may send notifications via the `Notification` [facade](/docs/{{version}}/facades). This approach is useful when you need to send a notification to multiple notifiable entities such as a collection of users. To send notifications using the facade, pass all of the notifiable entities and the notification instance to the `send` method: - use Illuminate\Support\Facades\Notification; +```php +use Illuminate\Support\Facades\Notification; - Notification::send($users, new InvoicePaid($invoice)); +Notification::send($users, new InvoicePaid($invoice)); +``` You can also send notifications immediately using the `sendNow` method. This method will send the notification immediately even if the notification implements the `ShouldQueue` interface: - Notification::sendNow($developers, new DeploymentCompleted($deployment)); +```php +Notification::sendNow($developers, new DeploymentCompleted($deployment)); +``` ### Specifying Delivery Channels Every notification class has a `via` method that determines on which channels the notification will be delivered. Notifications may be sent on the `mail`, `database`, `broadcast`, `vonage`, and `slack` channels. -> {tip} If you would like to use other delivery channels such as Telegram or Pusher, check out the community driven [Laravel Notification Channels website](http://laravel-notification-channels.com). +> [!NOTE] +> If you would like to use other delivery channels such as Telegram or Pusher, check out the community driven [Laravel Notification Channels website](http://laravel-notification-channels.com). The `via` method receives a `$notifiable` instance, which will be an instance of the class to which the notification is being sent. You may use `$notifiable` to determine which channels the notification should be delivered on: - /** - * Get the notification's delivery channels. - * - * @param mixed $notifiable - * @return array - */ - public function via($notifiable) - { - return $notifiable->prefers_sms ? ['vonage'] : ['mail', 'database']; - } +```php +/** + * Get the notification's delivery channels. + * + * @return array + */ +public function via(object $notifiable): array +{ + return $notifiable->prefers_sms ? ['vonage'] : ['mail', 'database']; +} +``` ### Queueing Notifications -> {note} Before queueing notifications you should configure your queue and [start a worker](/docs/{{version}}/queues). +> [!WARNING] +> Before queueing notifications, you should configure your queue and [start a worker](/docs/{{version}}/queues#running-the-queue-worker). Sending notifications can take time, especially if the channel needs to make an external API call to deliver the notification. To speed up your application's response time, let your notification be queued by adding the `ShouldQueue` interface and `Queueable` trait to your class. The interface and trait are already imported for all notifications generated using the `make:notification` command, so you may immediately add them to your notification class: - notify(new InvoicePaid($invoice)); +```php +$user->notify(new InvoicePaid($invoice)); +``` + +When queueing notifications, a queued job will be created for each recipient and channel combination. For example, six jobs will be dispatched to the queue if your notification has three recipients and two channels. + + +#### Delaying Notifications If you would like to delay the delivery of the notification, you may chain the `delay` method onto your notification instantiation: - $delay = now()->addMinutes(10); +```php +$delay = now()->addMinutes(10); - $user->notify((new InvoicePaid($invoice))->delay($delay)); +$user->notify((new InvoicePaid($invoice))->delay($delay)); +``` You may pass an array to the `delay` method to specify the delay amount for specific channels: - $user->notify((new InvoicePaid($invoice))->delay([ +```php +$user->notify((new InvoicePaid($invoice))->delay([ + 'mail' => now()->addMinutes(5), + 'sms' => now()->addMinutes(10), +])); +``` + +Alternatively, you may define a `withDelay` method on the notification class itself. The `withDelay` method should return an array of channel names and delay values: + +```php +/** + * Determine the notification's delivery delay. + * + * @return array + */ +public function withDelay(object $notifiable): array +{ + return [ 'mail' => now()->addMinutes(5), 'sms' => now()->addMinutes(10), - ])); - -When queueing notifications, a queued job will be created for each recipient and channel combination. For example, six jobs will be dispatched to the queue if your notification has three recipients and two channels. + ]; +} +``` -#### Customizing The Notification Queue Connection +#### Customizing the Notification Queue Connection + +By default, queued notifications will be queued using your application's default queue connection. If you would like to specify a different connection that should be used for a particular notification, you may call the `onConnection` method from your notification's constructor: + +```php +onConnection('redis'); + } +} +``` + +Or, if you would like to specify a specific queue connection that should be used for each notification channel supported by the notification, you may define a `viaConnections` method on your notification. This method should return an array of channel name / queue connection name pairs: + +```php +/** + * Determine which connections should be used for each notification channel. + * + * @return array + */ +public function viaConnections(): array +{ + return [ + 'mail' => 'redis', + 'database' => 'sync', + ]; +} +``` #### Customizing Notification Channel Queues If you would like to specify a specific queue that should be used for each notification channel supported by the notification, you may define a `viaQueues` method on your notification. This method should return an array of channel name / queue name pairs: +```php +/** + * Determine which queues should be used for each notification channel. + * + * @return array + */ +public function viaQueues(): array +{ + return [ + 'mail' => 'mail-queue', + 'slack' => 'slack-queue', + ]; +} +``` + + +#### Customizing Queued Notification Job Properties + +You may customize the behavior of the underlying queued job by defining properties on your notification class. These properties will be inherited by the queued job that sends the notification: + +```php + 'mail-queue', - 'slack' => 'slack-queue', - ]; - } + public $tries = 5; + + /** + * The number of seconds the notification can run before timing out. + * + * @var int + */ + public $timeout = 120; + + /** + * The maximum number of unhandled exceptions to allow before failing. + * + * @var int + */ + public $maxExceptions = 3; + + // ... +} +``` + +If you would like to ensure the privacy and integrity of a queued notification's data via [encryption](/docs/{{version}}/encryption), add the `ShouldBeEncrypted` interface to your notification class: + +```php +addMinutes(5); +} +``` + +> [!NOTE] +> For more information on these job properties and methods, please review the documentation on [queued jobs](/docs/{{version}}/queues#max-job-attempts-and-timeout). + + +#### Queued Notification Middleware + +Queued notifications may define middleware [just like queued jobs](/docs/{{version}}/queues#job-middleware). To get started, define a `middleware` method on your notification class. The `middleware` method will receive `$notifiable` and `$channel` variables, which allow you to customize the returned middleware based on the notification's destination: + +```php +use Illuminate\Queue\Middleware\RateLimited; + +/** + * Get the middleware the notification job should pass through. + * + * @return array + */ +public function middleware(object $notifiable, string $channel) +{ + return match ($channel) { + 'mail' => [new RateLimited('postmark')], + 'slack' => [new RateLimited('slack')], + default => [], + }; +} +``` -#### Queued Notifications & Database Transactions +#### Queued Notifications and Database Transactions When queued notifications are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your notification depends on these models, unexpected errors can occur when the job that sends the queued notification is processed. If your queue connection's `after_commit` configuration option is set to `false`, you may still indicate that a particular queued notification should be dispatched after all open database transactions have been committed by calling the `afterCommit` method when sending the notification: - use App\Notifications\InvoicePaid; +```php +use App\Notifications\InvoicePaid; - $user->notify((new InvoicePaid($invoice))->afterCommit()); +$user->notify((new InvoicePaid($invoice))->afterCommit()); +``` Alternatively, you may call the `afterCommit` method from your notification's constructor: - afterCommit(); - } + $this->afterCommit(); } +} +``` -> {tip} To learn more about working around these issues, please review the documentation regarding [queued jobs and database transactions](/docs/{{version}}/queues#jobs-and-database-transactions). +> [!NOTE] +> To learn more about working around these issues, please review the documentation regarding [queued jobs and database transactions](/docs/{{version}}/queues#jobs-and-database-transactions). -#### Determining If A Queued Notification Should Be Sent +#### Determining if a Queued Notification Should Be Sent After a queued notification has been dispatched for the queue for background processing, it will typically be accepted by a queue worker and sent to its intended recipient. However, if you would like to make the final determination on whether the queued notification should be sent after it is being processed by a queue worker, you may define a `shouldSend` method on the notification class. If this method returns `false`, the notification will not be sent: - /** - * Determine if the notification should be sent. - * - * @param mixed $notifiable - * @param string $channel - * @return bool - */ - public function shouldSend($notifiable, $channel) - { - return $this->invoice->isPaid(); - } +```php +/** + * Determine if the notification should be sent. + */ +public function shouldSend(object $notifiable, string $channel): bool +{ + return $this->invoice->isPaid(); +} +``` ### On-Demand Notifications Sometimes you may need to send a notification to someone who is not stored as a "user" of your application. Using the `Notification` facade's `route` method, you may specify ad-hoc notification routing information before sending the notification: - Notification::route('mail', 'taylor@example.com') - ->route('vonage', '5555555555') - ->route('slack', 'https://hooks.slack.com/services/...') - ->notify(new InvoicePaid($invoice)); +```php +use Illuminate\Broadcasting\Channel; +use Illuminate\Support\Facades\Notification; + +Notification::route('mail', 'taylor@example.com') + ->route('vonage', '5555555555') + ->route('slack', '#slack-channel') + ->route('broadcast', [new Channel('channel-name')]) + ->notify(new InvoicePaid($invoice)); +``` If you would like to provide the recipient's name when sending an on-demand notification to the `mail` route, you may provide an array that contains the email address as the key and the name as the value of the first element in the array: - Notification::route('mail', [ - 'barrett@example.com' => 'Barrett Blair', - ])->notify(new InvoicePaid($invoice)); +```php +Notification::route('mail', [ + 'barrett@example.com' => 'Barrett Blair', +])->notify(new InvoicePaid($invoice)); +``` + +Using the `routes` method, you may provide ad-hoc routing information for multiple notification channels at once: + +```php +Notification::routes([ + 'mail' => ['barrett@example.com' => 'Barrett Blair'], + 'vonage' => '5555555555', +])->notify(new InvoicePaid($invoice)); +``` ## Mail Notifications @@ -280,172 +487,184 @@ If a notification supports being sent as an email, you should define a `toMail` The `MailMessage` class contains a few simple methods to help you build transactional email messages. Mail messages may contain lines of text as well as a "call to action". Let's take a look at an example `toMail` method: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - $url = url('https://github.com/invoice/'.$this-%3Einvoice-%3Eid); - - return (new MailMessage) - ->greeting('Hello!') - ->line('One of your invoices has been paid!') - ->action('View Invoice', $url) - ->line('Thank you for using our application!'); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + $url = url('https://github.com/invoice/'.$this-%3Einvoice-%3Eid); + + return (new MailMessage) + ->greeting('Hello!') + ->line('One of your invoices has been paid!') + ->lineIf($this->amount > 0, "Amount paid: {$this->amount}") + ->action('View Invoice', $url) + ->line('Thank you for using our application!'); +} +``` -> {tip} Note we are using `$this->invoice->id` in our `toMail` method. You may pass any data your notification needs to generate its message into the notification's constructor. +> [!NOTE] +> Note we are using `$this->invoice->id` in our `toMail` method. You may pass any data your notification needs to generate its message into the notification's constructor. In this example, we register a greeting, a line of text, a call to action, and then another line of text. These methods provided by the `MailMessage` object make it simple and fast to format small transactional emails. The mail channel will then translate the message components into a beautiful, responsive HTML email template with a plain-text counterpart. Here is an example of an email generated by the `mail` channel: -> {tip} When sending mail notifications, be sure to set the `name` configuration option in your `config/app.php` configuration file. This value will be used in the header and footer of your mail notification messages. +> [!NOTE] +> When sending mail notifications, be sure to set the `name` configuration option in your `config/app.php` configuration file. This value will be used in the header and footer of your mail notification messages. + + +#### Error Messages + +Some notifications inform users of errors, such as a failed invoice payment. You may indicate that a mail message is regarding an error by calling the `error` method when building your message. When using the `error` method on a mail message, the call to action button will be red instead of black: + +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->error() + ->subject('Invoice Payment Failed') + ->line('...'); +} +``` #### Other Mail Notification Formatting Options Instead of defining the "lines" of text in the notification class, you may use the `view` method to specify a custom template that should be used to render the notification email: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage)->view( - 'emails.name', ['invoice' => $this->invoice] - ); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage)->view( + 'mail.invoice.paid', ['invoice' => $this->invoice] + ); +} +``` You may specify a plain-text view for the mail message by passing the view name as the second element of an array that is given to the `view` method: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage)->view( - ['emails.name.html', 'emails.name.plain'], - ['invoice' => $this->invoice] - ); - } - - -#### Error Messages +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage)->view( + ['mail.invoice.paid', 'mail.invoice.paid-text'], + ['invoice' => $this->invoice] + ); +} +``` -Some notifications inform users of errors, such as a failed invoice payment. You may indicate that a mail message is regarding an error by calling the `error` method when building your message. When using the `error` method on a mail message, the call to action button will be red instead of black: +Or, if your message only has a plain-text view, you may utilize the `text` method: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Message - */ - public function toMail($notifiable) - { - return (new MailMessage) - ->error() - ->subject('Notification Subject') - ->line('...'); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage)->text( + 'mail.invoice.paid-text', ['invoice' => $this->invoice] + ); +} +``` -### Customizing The Sender +### Customizing the Sender By default, the email's sender / from address is defined in the `config/mail.php` configuration file. However, you may specify the from address for a specific notification using the `from` method: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage) - ->from('barrett@example.com', 'Barrett Blair') - ->line('...'); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->from('barrett@example.com', 'Barrett Blair') + ->line('...'); +} +``` -### Customizing The Recipient +### Customizing the Recipient When sending notifications via the `mail` channel, the notification system will automatically look for an `email` property on your notifiable entity. You may customize which email address is used to deliver the notification by defining a `routeNotificationForMail` method on the notifiable entity: - |string + */ + public function routeNotificationForMail(Notification $notification): array|string { - use Notifiable; - - /** - * Route notifications for the mail channel. - * - * @param \Illuminate\Notifications\Notification $notification - * @return array|string - */ - public function routeNotificationForMail($notification) - { - // Return email address only... - return $this->email_address; + // Return email address only... + return $this->email_address; - // Return email address and name... - return [$this->email_address => $this->name]; - } + // Return email address and name... + return [$this->email_address => $this->name]; } +} +``` -### Customizing The Subject +### Customizing the Subject By default, the email's subject is the class name of the notification formatted to "Title Case". So, if your notification class is named `InvoicePaid`, the email's subject will be `Invoice Paid`. If you would like to specify a different subject for the message, you may call the `subject` method when building your message: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage) - ->subject('Notification Subject') - ->line('...'); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->subject('Notification Subject') + ->line('...'); +} +``` -### Customizing The Mailer +### Customizing the Mailer By default, the email notification will be sent using the default mailer defined in the `config/mail.php` configuration file. However, you may specify a different mailer at runtime by calling the `mailer` method when building your message: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage) - ->mailer('postmark') - ->line('...'); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->mailer('postmark') + ->line('...'); +} +``` -### Customizing The Templates +### Customizing the Templates You can modify the HTML and plain-text template used by mail notifications by publishing the notification package's resources. After running this command, the mail notification templates will be located in the `resources/views/vendor/notifications` directory: @@ -458,131 +677,196 @@ php artisan vendor:publish --tag=laravel-notifications To add attachments to an email notification, use the `attach` method while building your message. The `attach` method accepts the absolute path to the file as its first argument: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage) - ->greeting('Hello!') - ->attach('/path/to/file'); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->greeting('Hello!') + ->attach('/path/to/file'); +} +``` + +> [!NOTE] +> The `attach` method offered by notification mail messages also accepts [attachable objects](/docs/{{version}}/mail#attachable-objects). Please consult the comprehensive [attachable object documentation](/docs/{{version}}/mail#attachable-objects) to learn more. When attaching files to a message, you may also specify the display name and / or MIME type by passing an `array` as the second argument to the `attach` method: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage) - ->greeting('Hello!') - ->attach('/path/to/file', [ - 'as' => 'name.pdf', - 'mime' => 'application/pdf', - ]); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->greeting('Hello!') + ->attach('/path/to/file', [ + 'as' => 'name.pdf', + 'mime' => 'application/pdf', + ]); +} +``` Unlike attaching files in mailable objects, you may not attach a file directly from a storage disk using `attachFromStorage`. You should rather use the `attach` method with an absolute path to the file on the storage disk. Alternatively, you could return a [mailable](/docs/{{version}}/mail#generating-mailables) from the `toMail` method: - use App\Mail\InvoicePaid as InvoicePaidMailable; +```php +use App\Mail\InvoicePaid as InvoicePaidMailable; + +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): Mailable +{ + return (new InvoicePaidMailable($this->invoice)) + ->to($notifiable->email) + ->attachFromStorage('/path/to/file'); +} +``` - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return Mailable - */ - public function toMail($notifiable) - { - return (new InvoicePaidMailable($this->invoice)) - ->to($notifiable->email) - ->attachFromStorage('/path/to/file'); - } +When necessary, multiple files may be attached to a message using the `attachMany` method: + +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->greeting('Hello!') + ->attachMany([ + '/path/to/forge.svg', + '/path/to/vapor.svg' => [ + 'as' => 'Logo.svg', + 'mime' => 'image/svg+xml', + ], + ]); +} +``` #### Raw Data Attachments The `attachData` method may be used to attach a raw string of bytes as an attachment. When calling the `attachData` method, you should provide the filename that should be assigned to the attachment: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage) - ->greeting('Hello!') - ->attachData($this->pdf, 'name.pdf', [ - 'mime' => 'application/pdf', - ]); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->greeting('Hello!') + ->attachData($this->pdf, 'name.pdf', [ + 'mime' => 'application/pdf', + ]); +} +``` + + +### Adding Tags and Metadata + +Some third-party email providers such as Mailgun and Postmark support message "tags" and "metadata", which may be used to group and track emails sent by your application. You may add tags and metadata to an email message via the `tag` and `metadata` methods: + +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->greeting('Comment Upvoted!') + ->tag('upvote') + ->metadata('comment_id', $this->comment->id); +} +``` + +If your application is using the Mailgun driver, you may consult Mailgun's documentation for more information on [tags](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/#tags) and [metadata](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/#attaching-metadata-to-messages). Likewise, the Postmark documentation may also be consulted for more information on their support for [tags](https://postmarkapp.com/blog/tags-support-for-smtp) and [metadata](https://postmarkapp.com/support/article/1125-custom-metadata-faq). + +If your application is using Amazon SES to send emails, you should use the `metadata` method to attach [SES "tags"](https://docs.aws.amazon.com/ses/latest/APIReference/API_MessageTag.html) to the message. + + +### Customizing the Symfony Message + +The `withSymfonyMessage` method of the `MailMessage` class allows you to register a closure which will be invoked with the Symfony Message instance before sending the message. This gives you an opportunity to deeply customize the message before it is delivered: + +```php +use Symfony\Component\Mime\Email; + +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->withSymfonyMessage(function (Email $message) { + $message->getHeaders()->addTextHeader( + 'Custom-Header', 'Header Value' + ); + }); +} +``` ### Using Mailables If needed, you may return a full [mailable object](/docs/{{version}}/mail) from your notification's `toMail` method. When returning a `Mailable` instead of a `MailMessage`, you will need to specify the message recipient using the mailable object's `to` method: - use App\Mail\InvoicePaid as InvoicePaidMailable; - - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return Mailable - */ - public function toMail($notifiable) - { - return (new InvoicePaidMailable($this->invoice)) - ->to($notifiable->email); - } +```php +use App\Mail\InvoicePaid as InvoicePaidMailable; +use Illuminate\Mail\Mailable; + +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): Mailable +{ + return (new InvoicePaidMailable($this->invoice)) + ->to($notifiable->email); +} +``` -#### Mailables & On-Demand Notifications +#### Mailables and On-Demand Notifications If you are sending an [on-demand notification](#on-demand-notifications), the `$notifiable` instance given to the `toMail` method will be an instance of `Illuminate\Notifications\AnonymousNotifiable`, which offers a `routeNotificationFor` method that may be used to retrieve the email address the on-demand notification should be sent to: - use App\Mail\InvoicePaid as InvoicePaidMailable; - use Illuminate\Notifications\AnonymousNotifiable; - - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return Mailable - */ - public function toMail($notifiable) - { - $address = $notifiable instanceof AnonymousNotifiable - ? $notifiable->routeNotificationFor('mail') - : $notifiable->email; - - return (new InvoicePaidMailable($this->invoice)) - ->to($address); - } +```php +use App\Mail\InvoicePaid as InvoicePaidMailable; +use Illuminate\Notifications\AnonymousNotifiable; +use Illuminate\Mail\Mailable; + +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): Mailable +{ + $address = $notifiable instanceof AnonymousNotifiable + ? $notifiable->routeNotificationFor('mail') + : $notifiable->email; + + return (new InvoicePaidMailable($this->invoice)) + ->to($address); +} +``` ### Previewing Mail Notifications When designing a mail notification template, it is convenient to quickly preview the rendered mail message in your browser like a typical Blade template. For this reason, Laravel allows you to return any mail message generated by a mail notification directly from a route closure or controller. When a `MailMessage` is returned, it will be rendered and displayed in the browser, allowing you to quickly preview its design without needing to send it to an actual email address: - use App\Models\Invoice; - use App\Notifications\InvoicePaid; +```php +use App\Models\Invoice; +use App\Notifications\InvoicePaid; - Route::get('/notification', function () { - $invoice = Invoice::find(1); +Route::get('/notification', function () { + $invoice = Invoice::find(1); - return (new InvoicePaid($invoice)) - ->toMail($invoice->user); - }); + return (new InvoicePaid($invoice)) + ->toMail($invoice->user); +}); +``` ## Markdown Mail Notifications @@ -590,7 +874,7 @@ When designing a mail notification template, it is convenient to quickly preview Markdown mail notifications allow you to take advantage of the pre-built templates of mail notifications, while giving you more freedom to write longer, customized messages. Since the messages are written in Markdown, Laravel is able to render beautiful, responsive HTML templates for the messages while also automatically generating a plain-text counterpart. -### Generating The Message +### Generating the Message To generate a notification with a corresponding Markdown template, you may use the `--markdown` option of the `make:notification` Artisan command: @@ -600,50 +884,52 @@ php artisan make:notification InvoicePaid --markdown=mail.invoice.paid Like all other mail notifications, notifications that use Markdown templates should define a `toMail` method on their notification class. However, instead of using the `line` and `action` methods to construct the notification, use the `markdown` method to specify the name of the Markdown template that should be used. An array of data you wish to make available to the template may be passed as the method's second argument: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - $url = url('https://github.com/invoice/'.$this-%3Einvoice-%3Eid); - - return (new MailMessage) - ->subject('Invoice Paid') - ->markdown('mail.invoice.paid', ['url' => $url]); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + $url = url('https://github.com/invoice/'.$this-%3Einvoice-%3Eid); + + return (new MailMessage) + ->subject('Invoice Paid') + ->markdown('mail.invoice.paid', ['url' => $url]); +} +``` -### Writing The Message +### Writing the Message Markdown mail notifications use a combination of Blade components and Markdown syntax which allow you to easily construct notifications while leveraging Laravel's pre-crafted notification components: ```blade -@component('mail::message') + # Invoice Paid Your invoice has been paid! -@component('mail::button', ['url' => $url]) + View Invoice -@endcomponent + Thanks,
{{ config('app.name') }} -@endcomponent +
``` +> [!NOTE] +> Do not use excess indentation when writing Markdown emails. Per Markdown standards, Markdown parsers will render indented content as code blocks. + #### Button Component The button component renders a centered button link. The component accepts two arguments, a `url` and an optional `color`. Supported colors are `primary`, `green`, and `red`. You may add as many button components to a notification as you wish: ```blade -@component('mail::button', ['url' => $url, 'color' => 'green']) + View Invoice -@endcomponent + ``` @@ -652,9 +938,9 @@ View Invoice The panel component renders the given block of text in a panel that has a slightly different background color than the rest of the notification. This allows you to draw attention to a given block of text: ```blade -@component('mail::panel') + This is the panel content. -@endcomponent + ``` @@ -663,16 +949,16 @@ This is the panel content. The table component allows you to transform a Markdown table into an HTML table. The component accepts the Markdown table as its content. Table column alignment is supported using the default Markdown table alignment syntax: ```blade -@component('mail::table') -| Laravel | Table | Example | -| ------------- |:-------------:| --------:| -| Col 2 is | Centered | $10 | -| Col 3 is | Right-Aligned | $20 | -@endcomponent + +| Laravel | Table | Example | +| ------------- | :-----------: | ------------: | +| Col 2 is | Centered | $10 | +| Col 3 is | Right-Aligned | $20 | + ``` -### Customizing The Components +### Customizing the Components You may export all of the Markdown notification components to your own application for customization. To export the components, use the `vendor:publish` Artisan command to publish the `laravel-mail` asset tag: @@ -683,7 +969,7 @@ php artisan vendor:publish --tag=laravel-mail This command will publish the Markdown mail components to the `resources/views/vendor/mail` directory. The `mail` directory will contain an `html` and a `text` directory, each containing their respective representations of every available component. You are free to customize these components however you like. -#### Customizing The CSS +#### Customizing the CSS After exporting the components, the `resources/views/vendor/mail/html/themes` directory will contain a `default.css` file. You may customize the CSS in this file and your styles will automatically be in-lined within the HTML representations of your Markdown notifications. @@ -691,19 +977,18 @@ If you would like to build an entirely new theme for Laravel's Markdown componen To customize the theme for an individual notification, you may call the `theme` method while building the notification's mail message. The `theme` method accepts the name of the theme that should be used when sending the notification: - /** - * Get the mail representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage - */ - public function toMail($notifiable) - { - return (new MailMessage) - ->theme('invoice') - ->subject('Invoice Paid') - ->markdown('mail.invoice.paid', ['url' => $url]); - } +```php +/** + * Get the mail representation of the notification. + */ +public function toMail(object $notifiable): MailMessage +{ + return (new MailMessage) + ->theme('invoice') + ->subject('Invoice Paid') + ->markdown('mail.invoice.paid', ['url' => $url]); +} +``` ## Database Notifications @@ -713,83 +998,132 @@ To customize the theme for an individual notification, you may call the `theme` The `database` notification channel stores the notification information in a database table. This table will contain information such as the notification type as well as a JSON data structure that describes the notification. -You can query the table to display the notifications in your application's user interface. But, before you can do that, you will need to create a database table to hold your notifications. You may use the `notifications:table` command to generate a [migration](/docs/{{version}}/migrations) with the proper table schema: +You can query the table to display the notifications in your application's user interface. But, before you can do that, you will need to create a database table to hold your notifications. You may use the `make:notifications-table` command to generate a [migration](/docs/{{version}}/migrations) with the proper table schema: ```shell -php artisan notifications:table +php artisan make:notifications-table php artisan migrate ``` +> [!NOTE] +> If your notifiable models are using [UUID or ULID primary keys](/docs/{{version}}/eloquent#uuid-and-ulid-keys), you should replace the `morphs` method with [uuidMorphs](/docs/{{version}}/migrations#column-method-uuidMorphs) or [ulidMorphs](/docs/{{version}}/migrations#column-method-ulidMorphs) in the notification table migration. + ### Formatting Database Notifications If a notification supports being stored in a database table, you should define a `toDatabase` or `toArray` method on the notification class. This method will receive a `$notifiable` entity and should return a plain PHP array. The returned array will be encoded as JSON and stored in the `data` column of your `notifications` table. Let's take a look at an example `toArray` method: - /** - * Get the array representation of the notification. - * - * @param mixed $notifiable - * @return array - */ - public function toArray($notifiable) - { - return [ - 'invoice_id' => $this->invoice->id, - 'amount' => $this->invoice->amount, - ]; - } +```php +/** + * Get the array representation of the notification. + * + * @return array + */ +public function toArray(object $notifiable): array +{ + return [ + 'invoice_id' => $this->invoice->id, + 'amount' => $this->invoice->amount, + ]; +} +``` + +When a notification is stored in your application's database, the `type` column will be set to the notification's class name by default, and the `read_at` column will be `null`. However, you can customize this behavior by defining the `databaseType` and `initialDatabaseReadAtValue` methods in your notification class: + +```php +use Illuminate\Support\Carbon; + +/** + * Get the notification's database type. + */ +public function databaseType(object $notifiable): string +{ + return 'invoice-paid'; +} + +/** + * Get the initial value for the "read_at" column. + */ +public function initialDatabaseReadAtValue(): ?Carbon +{ + return null; +} +``` -#### `toDatabase` Vs. `toArray` +#### `toDatabase` vs. `toArray` The `toArray` method is also used by the `broadcast` channel to determine which data to broadcast to your JavaScript powered frontend. If you would like to have two different array representations for the `database` and `broadcast` channels, you should define a `toDatabase` method instead of a `toArray` method. -### Accessing The Notifications +### Accessing the Notifications Once notifications are stored in the database, you need a convenient way to access them from your notifiable entities. The `Illuminate\Notifications\Notifiable` trait, which is included on Laravel's default `App\Models\User` model, includes a `notifications` [Eloquent relationship](/docs/{{version}}/eloquent-relationships) that returns the notifications for the entity. To fetch notifications, you may access this method like any other Eloquent relationship. By default, notifications will be sorted by the `created_at` timestamp with the most recent notifications at the beginning of the collection: - $user = App\Models\User::find(1); +```php +$user = App\Models\User::find(1); - foreach ($user->notifications as $notification) { - echo $notification->type; - } +foreach ($user->notifications as $notification) { + echo $notification->type; +} +``` If you want to retrieve only the "unread" notifications, you may use the `unreadNotifications` relationship. Again, these notifications will be sorted by the `created_at` timestamp with the most recent notifications at the beginning of the collection: - $user = App\Models\User::find(1); +```php +$user = App\Models\User::find(1); - foreach ($user->unreadNotifications as $notification) { - echo $notification->type; - } +foreach ($user->unreadNotifications as $notification) { + echo $notification->type; +} +``` + +If you want to retrieve only the "read" notifications, you may use the `readNotifications` relationship: -> {tip} To access your notifications from your JavaScript client, you should define a notification controller for your application which returns the notifications for a notifiable entity, such as the current user. You may then make an HTTP request to that controller's URL from your JavaScript client. +```php +$user = App\Models\User::find(1); + +foreach ($user->readNotifications as $notification) { + echo $notification->type; +} +``` + +> [!NOTE] +> To access your notifications from your JavaScript client, you should define a notification controller for your application which returns the notifications for a notifiable entity, such as the current user. You may then make an HTTP request to that controller's URL from your JavaScript client. -### Marking Notifications As Read +### Marking Notifications as Read Typically, you will want to mark a notification as "read" when a user views it. The `Illuminate\Notifications\Notifiable` trait provides a `markAsRead` method, which updates the `read_at` column on the notification's database record: - $user = App\Models\User::find(1); +```php +$user = App\Models\User::find(1); - foreach ($user->unreadNotifications as $notification) { - $notification->markAsRead(); - } +foreach ($user->unreadNotifications as $notification) { + $notification->markAsRead(); +} +``` However, instead of looping through each notification, you may use the `markAsRead` method directly on a collection of notifications: - $user->unreadNotifications->markAsRead(); +```php +$user->unreadNotifications->markAsRead(); +``` You may also use a mass-update query to mark all of the notifications as read without retrieving them from the database: - $user = App\Models\User::find(1); +```php +$user = App\Models\User::find(1); - $user->unreadNotifications()->update(['read_at' => now()]); +$user->unreadNotifications()->update(['read_at' => now()]); +``` You may `delete` the notifications to remove them from the table entirely: - $user->notifications()->delete(); +```php +$user->notifications()->delete(); +``` ## Broadcast Notifications @@ -804,85 +1138,162 @@ Before broadcasting notifications, you should configure and be familiar with Lar The `broadcast` channel broadcasts notifications using Laravel's [event broadcasting](/docs/{{version}}/broadcasting) services, allowing your JavaScript powered frontend to catch notifications in realtime. If a notification supports broadcasting, you can define a `toBroadcast` method on the notification class. This method will receive a `$notifiable` entity and should return a `BroadcastMessage` instance. If the `toBroadcast` method does not exist, the `toArray` method will be used to gather the data that should be broadcast. The returned data will be encoded as JSON and broadcast to your JavaScript powered frontend. Let's take a look at an example `toBroadcast` method: - use Illuminate\Notifications\Messages\BroadcastMessage; - - /** - * Get the broadcastable representation of the notification. - * - * @param mixed $notifiable - * @return BroadcastMessage - */ - public function toBroadcast($notifiable) - { - return new BroadcastMessage([ - 'invoice_id' => $this->invoice->id, - 'amount' => $this->invoice->amount, - ]); - } +```php +use Illuminate\Notifications\Messages\BroadcastMessage; + +/** + * Get the broadcastable representation of the notification. + */ +public function toBroadcast(object $notifiable): BroadcastMessage +{ + return new BroadcastMessage([ + 'invoice_id' => $this->invoice->id, + 'amount' => $this->invoice->amount, + ]); +} +``` #### Broadcast Queue Configuration All broadcast notifications are queued for broadcasting. If you would like to configure the queue connection or queue name that is used to queue the broadcast operation, you may use the `onConnection` and `onQueue` methods of the `BroadcastMessage`: - return (new BroadcastMessage($data)) - ->onConnection('sqs') - ->onQueue('broadcasts'); +```php +return (new BroadcastMessage($data)) + ->onConnection('sqs') + ->onQueue('broadcasts'); +``` -#### Customizing The Notification Type +#### Customizing the Notification Type In addition to the data you specify, all broadcast notifications also have a `type` field containing the full class name of the notification. If you would like to customize the notification `type`, you may define a `broadcastType` method on the notification class: - use Illuminate\Notifications\Messages\BroadcastMessage; - - /** - * Get the type of the notification being broadcast. - * - * @return string - */ - public function broadcastType() - { - return 'broadcast.message'; - } +```php +/** + * Get the type of the notification being broadcast. + */ +public function broadcastType(): string +{ + return 'broadcast.message'; +} +``` -### Listening For Notifications +### Listening for Notifications Notifications will broadcast on a private channel formatted using a `{notifiable}.{id}` convention. So, if you are sending a notification to an `App\Models\User` instance with an ID of `1`, the notification will be broadcast on the `App.Models.User.1` private channel. When using [Laravel Echo](/docs/{{version}}/broadcasting#client-side-installation), you may easily listen for notifications on a channel using the `notification` method: - Echo.private('App.Models.User.' + userId) - .notification((notification) => { - console.log(notification.type); - }); +```js +Echo.private('App.Models.User.' + userId) + .notification((notification) => { + console.log(notification.type); + }); +``` + + +#### Using React or Vue + +Laravel Echo includes React and Vue hooks that make it painless to listen for notifications. To get started, invoke the `useEchoNotification` hook, which is used to listen for notifications. The `useEchoNotification` hook will automatically leave channels when the consuming component is unmounted: + +```js tab=React +import { useEchoNotification } from "@laravel/echo-react"; + +useEchoNotification( + `App.Models.User.${userId}`, + (notification) => { + console.log(notification.type); + }, +); +``` + +```vue tab=Vue + +``` + +By default, the hook listens to all notifications. To specify the notification types you would like to listen to, you can provide either a string or array of types to `useEchoNotification`: + +```js tab=React +import { useEchoNotification } from "@laravel/echo-react"; + +useEchoNotification( + `App.Models.User.${userId}`, + (notification) => { + console.log(notification.type); + }, + 'App.Notifications.InvoicePaid', +); +``` + +```vue tab=Vue + +``` + +You may also specify the shape of the notification payload data, providing greater type safety and editing convenience: + +```ts +type InvoicePaidNotification = { + invoice_id: number; + created_at: string; +}; + +useEchoNotification( + `App.Models.User.${userId}`, + (notification) => { + console.log(notification.invoice_id); + console.log(notification.created_at); + console.log(notification.type); + }, + 'App.Notifications.InvoicePaid', +); +``` -#### Customizing The Notification Channel +#### Customizing the Notification Channel If you would like to customize which channel that an entity's broadcast notifications are broadcast on, you may define a `receivesBroadcastNotificationsOn` method on the notifiable entity: - id; - } + return 'users.'.$this->id; } +} +``` ## SMS Notifications @@ -892,112 +1303,120 @@ If you would like to customize which channel that an entity's broadcast notifica Sending SMS notifications in Laravel is powered by [Vonage](https://www.vonage.com/) (formerly known as Nexmo). Before you can send notifications via Vonage, you need to install the `laravel/vonage-notification-channel` and `guzzlehttp/guzzle` packages: - composer require laravel/vonage-notification-channel guzzlehttp/guzzle +```shell +composer require laravel/vonage-notification-channel guzzlehttp/guzzle +``` The package includes a [configuration file](https://github.com/laravel/vonage-notification-channel/blob/3.x/config/vonage.php). However, you are not required to export this configuration file to your own application. You can simply use the `VONAGE_KEY` and `VONAGE_SECRET` environment variables to define your Vonage public and secret keys. -After defining your keys, you may set a `VONAGE_SMS_FROM` environment variable that defines the phone number that your SMS messages should be sent from by default. You may generate this phone number within the Vonage control panel: +After defining your keys, you should set a `VONAGE_SMS_FROM` environment variable that defines the phone number that your SMS messages should be sent from by default. You may generate this phone number within the Vonage control panel: - VONAGE_SMS_FROM=15556666666 +```ini +VONAGE_SMS_FROM=15556666666 +``` ### Formatting SMS Notifications If a notification supports being sent as an SMS, you should define a `toVonage` method on the notification class. This method will receive a `$notifiable` entity and should return an `Illuminate\Notifications\Messages\VonageMessage` instance: - /** - * Get the Vonage / SMS representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\VonageMessage - */ - public function toVonage($notifiable) - { - return (new VonageMessage) - ->content('Your SMS message content'); - } +```php +use Illuminate\Notifications\Messages\VonageMessage; + +/** + * Get the Vonage / SMS representation of the notification. + */ +public function toVonage(object $notifiable): VonageMessage +{ + return (new VonageMessage) + ->content('Your SMS message content'); +} +``` #### Unicode Content If your SMS message will contain unicode characters, you should call the `unicode` method when constructing the `VonageMessage` instance: - /** - * Get the Vonage / SMS representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\VonageMessage - */ - public function toVonage($notifiable) - { - return (new VonageMessage) - ->content('Your unicode message') - ->unicode(); - } +```php +use Illuminate\Notifications\Messages\VonageMessage; + +/** + * Get the Vonage / SMS representation of the notification. + */ +public function toVonage(object $notifiable): VonageMessage +{ + return (new VonageMessage) + ->content('Your unicode message') + ->unicode(); +} +``` -### Customizing The "From" Number +### Customizing the "From" Number If you would like to send some notifications from a phone number that is different from the phone number specified by your `VONAGE_SMS_FROM` environment variable, you may call the `from` method on a `VonageMessage` instance: - /** - * Get the Vonage / SMS representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\VonageMessage - */ - public function toVonage($notifiable) - { - return (new VonageMessage) - ->content('Your SMS message content') - ->from('15554443333'); - } +```php +use Illuminate\Notifications\Messages\VonageMessage; + +/** + * Get the Vonage / SMS representation of the notification. + */ +public function toVonage(object $notifiable): VonageMessage +{ + return (new VonageMessage) + ->content('Your SMS message content') + ->from('15554443333'); +} +``` ### Adding a Client Reference If you would like to keep track of costs per user, team, or client, you may add a "client reference" to the notification. Vonage will allow you to generate reports using this client reference so that you can better understand a particular customer's SMS usage. The client reference can be any string up to 40 characters: - /** - * Get the Vonage / SMS representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\VonageMessage - */ - public function toVonage($notifiable) - { - return (new VonageMessage) - ->clientReference((string) $notifiable->id) - ->content('Your SMS message content'); - } +```php +use Illuminate\Notifications\Messages\VonageMessage; + +/** + * Get the Vonage / SMS representation of the notification. + */ +public function toVonage(object $notifiable): VonageMessage +{ + return (new VonageMessage) + ->clientReference((string) $notifiable->id) + ->content('Your SMS message content'); +} +``` ### Routing SMS Notifications To route Vonage notifications to the proper phone number, define a `routeNotificationForVonage` method on your notifiable entity: - phone_number; - } + return $this->phone_number; } +} +``` ## Slack Notifications @@ -1005,133 +1424,261 @@ To route Vonage notifications to the proper phone number, define a `routeNotific ### Prerequisites -Before you can send notifications via Slack, you must install the Slack notification channel via Composer: +Before sending Slack notifications, you should install the Slack notification channel via Composer: ```shell composer require laravel/slack-notification-channel ``` -You will also need to create a [Slack App](https://api.slack.com/apps?new_app=1) for your team. After creating the App, you should configure an "Incoming Webhook" for the workspace. Slack will then provide you with a webhook URL that you may use when [routing Slack notifications](#routing-slack-notifications). +Additionally, you must create a [Slack App](https://api.slack.com/apps?new_app=1) for your Slack workspace. + +If you only need to send notifications to the same Slack workspace that the App is created in, you should ensure that your App has the `chat:write`, `chat:write.public`, and `chat:write.customize` scopes. These scopes can be added from the "OAuth & Permissions" App management tab within Slack. + +Next, copy the App's "Bot User OAuth Token" and place it within a `slack` configuration array in your application's `services.php` configuration file. This token can be found on the "OAuth & Permissions" tab within Slack: + +```php +'slack' => [ + 'notifications' => [ + 'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'), + 'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'), + ], +], +``` + + +#### App Distribution + +If your application will be sending notifications to external Slack workspaces that are owned by your application's users, you will need to "distribute" your App via Slack. App distribution can be managed from your App's "Manage Distribution" tab within Slack. Once your App has been distributed, you may use [Socialite](/docs/{{version}}/socialite) to [obtain Slack Bot tokens](/docs/{{version}}/socialite#slack-bot-scopes) on behalf of your application's users. ### Formatting Slack Notifications -If a notification supports being sent as a Slack message, you should define a `toSlack` method on the notification class. This method will receive a `$notifiable` entity and should return an `Illuminate\Notifications\Messages\SlackMessage` instance. Slack messages may contain text content as well as an "attachment" that formats additional text or an array of fields. Let's take a look at a basic `toSlack` example: +If a notification supports being sent as a Slack message, you should define a `toSlack` method on the notification class. This method will receive a `$notifiable` entity and should return an `Illuminate\Notifications\Slack\SlackMessage` instance. You can construct rich notifications using [Slack's Block Kit API](https://api.slack.com/block-kit). The following example may be previewed in [Slack's Block Kit builder](https://app.slack.com/block-kit-builder/T01KWS6K23Z#%7B%22blocks%22:%5B%7B%22type%22:%22header%22,%22text%22:%7B%22type%22:%22plain_text%22,%22text%22:%22Invoice%20Paid%22%7D%7D,%7B%22type%22:%22context%22,%22elements%22:%5B%7B%22type%22:%22plain_text%22,%22text%22:%22Customer%20%231234%22%7D%5D%7D,%7B%22type%22:%22section%22,%22text%22:%7B%22type%22:%22plain_text%22,%22text%22:%22An%20invoice%20has%20been%20paid.%22%7D,%22fields%22:%5B%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Invoice%20No:*%5Cn1000%22%7D,%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Invoice%20Recipient:*%5Cntaylor@laravel.com%22%7D%5D%7D,%7B%22type%22:%22divider%22%7D,%7B%22type%22:%22section%22,%22text%22:%7B%22type%22:%22plain_text%22,%22text%22:%22Congratulations!%22%7D%7D%5D%7D): + +```php +use Illuminate\Notifications\Slack\BlockKit\Blocks\ContextBlock; +use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock; +use Illuminate\Notifications\Slack\SlackMessage; + +/** + * Get the Slack representation of the notification. + */ +public function toSlack(object $notifiable): SlackMessage +{ + return (new SlackMessage) + ->text('One of your invoices has been paid!') + ->headerBlock('Invoice Paid') + ->contextBlock(function (ContextBlock $block) { + $block->text('Customer #1234'); + }) + ->sectionBlock(function (SectionBlock $block) { + $block->text('An invoice has been paid.'); + $block->field("*Invoice No:*\n1000")->markdown(); + $block->field("*Invoice Recipient:*\ntaylor@laravel.com")->markdown(); + }) + ->dividerBlock() + ->sectionBlock(function (SectionBlock $block) { + $block->text('Congratulations!'); + }); +} +``` - /** - * Get the Slack representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\SlackMessage - */ - public function toSlack($notifiable) - { - return (new SlackMessage) - ->content('One of your invoices has been paid!'); - } + +#### Using Slack's Block Kit Builder Template - -### Slack Attachments +Instead of using the fluent message builder methods to construct your Block Kit message, you may provide the raw JSON payload generated by Slack's Block Kit Builder to the `usingBlockKitTemplate` method: -You may also add "attachments" to Slack messages. Attachments provide richer formatting options than simple text messages. In this example, we will send an error notification about an exception that occurred in an application, including a link to view more details about the exception: +```php +use Illuminate\Notifications\Slack\SlackMessage; +use Illuminate\Support\Str; - /** - * Get the Slack representation of the notification. - * - * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\SlackMessage - */ - public function toSlack($notifiable) - { - $url = url('https://github.com/exceptions/'.$this-%3Eexception-%3Eid); - - return (new SlackMessage) - ->error() - ->content('Whoops! Something went wrong.') - ->attachment(function ($attachment) use ($url) { - $attachment->title('Exception: File Not Found', $url) - ->content('File [background.jpg] was not found.'); - }); - } +/** + * Get the Slack representation of the notification. + */ +public function toSlack(object $notifiable): SlackMessage +{ + $template = <<usingBlockKitTemplate($template); +} +``` - /** - * Get the Slack representation of the notification. - * - * @param mixed $notifiable - * @return SlackMessage - */ - public function toSlack($notifiable) - { - $url = url('https://github.com/invoices/'.$this-%3Einvoice-%3Eid); - - return (new SlackMessage) - ->success() - ->content('One of your invoices has been paid!') - ->attachment(function ($attachment) use ($url) { - $attachment->title('Invoice 1322', $url) - ->fields([ - 'Title' => 'Server Expenses', - 'Amount' => '$1,234', - 'Via' => 'American Express', - 'Was Overdue' => ':-1:', - ]); - }); - } + +### Slack Interactivity + +Slack's Block Kit notification system provides powerful features to [handle user interaction](https://api.slack.com/interactivity/handling). To utilize these features, your Slack App should have "Interactivity" enabled and a "Request URL" configured that points to a URL served by your application. These settings can be managed from the "Interactivity & Shortcuts" App management tab within Slack. + +In the following example, which utilizes the `actionsBlock` method, Slack will send a `POST` request to your "Request URL" with a payload containing the Slack user who clicked the button, the ID of the clicked button, and more. Your application can then determine the action to take based on the payload. You should also [verify the request](https://api.slack.com/authentication/verifying-requests-from-slack) was made by Slack: + +```php +use Illuminate\Notifications\Slack\BlockKit\Blocks\ActionsBlock; +use Illuminate\Notifications\Slack\BlockKit\Blocks\ContextBlock; +use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock; +use Illuminate\Notifications\Slack\SlackMessage; + +/** + * Get the Slack representation of the notification. + */ +public function toSlack(object $notifiable): SlackMessage +{ + return (new SlackMessage) + ->text('One of your invoices has been paid!') + ->headerBlock('Invoice Paid') + ->contextBlock(function (ContextBlock $block) { + $block->text('Customer #1234'); + }) + ->sectionBlock(function (SectionBlock $block) { + $block->text('An invoice has been paid.'); + }) + ->actionsBlock(function (ActionsBlock $block) { + // ID defaults to "button_acknowledge_invoice"... + $block->button('Acknowledge Invoice')->primary(); + + // Manually configure the ID... + $block->button('Deny')->danger()->id('deny_invoice'); + }); +} +``` + + +#### Confirmation Modals + +If you would like users to be required to confirm an action before it is performed, you may invoke the `confirm` method when defining your button. The `confirm` method accepts a message and a closure which receives a `ConfirmObject` instance: + +```php +use Illuminate\Notifications\Slack\BlockKit\Blocks\ActionsBlock; +use Illuminate\Notifications\Slack\BlockKit\Blocks\ContextBlock; +use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock; +use Illuminate\Notifications\Slack\BlockKit\Composites\ConfirmObject; +use Illuminate\Notifications\Slack\SlackMessage; + +/** + * Get the Slack representation of the notification. + */ +public function toSlack(object $notifiable): SlackMessage +{ + return (new SlackMessage) + ->text('One of your invoices has been paid!') + ->headerBlock('Invoice Paid') + ->contextBlock(function (ContextBlock $block) { + $block->text('Customer #1234'); + }) + ->sectionBlock(function (SectionBlock $block) { + $block->text('An invoice has been paid.'); + }) + ->actionsBlock(function (ActionsBlock $block) { + $block->button('Acknowledge Invoice') + ->primary() + ->confirm( + 'Acknowledge the payment and send a thank you email?', + function (ConfirmObject $dialog) { + $dialog->confirm('Yes'); + $dialog->deny('No'); + } + ); + }); +} +``` + + +#### Inspecting Slack Blocks + +If you would like to quickly inspect the blocks you've been building, you can invoke the `dd` method on the `SlackMessage` instance. The `dd` method will generate and dump a URL to Slack's [Block Kit Builder](https://app.slack.com/block-kit-builder/), which displays a preview of the payload and notification in your browser. You may pass `true` to the `dd` method to dump the raw payload: + +```php +return (new SlackMessage) + ->text('One of your invoices has been paid!') + ->headerBlock('Invoice Paid') + ->dd(); +``` + + +### Routing Slack Notifications + +To direct Slack notifications to the appropriate Slack team and channel, define a `routeNotificationForSlack` method on your notifiable model. This method can return one of three values: + +- `null` - which defers routing to the channel configured in the notification itself. You may use the `to` method when building your `SlackMessage` to configure the channel within the notification. +- A string specifying the Slack channel to send the notification to, e.g. `#support-channel`. +- A `SlackRoute` instance, which allows you to specify an OAuth token and channel name, e.g. `SlackRoute::make($this->slack_channel, $this->slack_token)`. This method should be used to send notifications to external workspaces. - -#### Markdown Attachment Content +For instance, returning `#support-channel` from the `routeNotificationForSlack` method will send the notification to the `#support-channel` channel in the workspace associated with the Bot User OAuth token located in your application's `services.php` configuration file: -If some of your attachment fields contain Markdown, you may use the `markdown` method to instruct Slack to parse and display the given attachment fields as Markdown formatted text. The values accepted by this method are: `pretext`, `text`, and / or `fields`. For more information about Slack attachment formatting, check out the [Slack API documentation](https://api.slack.com/docs/message-formatting#message_formatting): +```php +error() - ->content('Whoops! Something went wrong.') - ->attachment(function ($attachment) use ($url) { - $attachment->title('Exception: File Not Found', $url) - ->content('File [background.jpg] was *not found*.') - ->markdown(['text']); - }); + return '#support-channel'; } +} +``` - -### Routing Slack Notifications + +### Notifying External Slack Workspaces + +> [!NOTE] +> Before sending notifications to external Slack workspaces, your Slack App must be [distributed](#slack-app-distribution). -To route Slack notifications to the proper Slack team and channel, define a `routeNotificationForSlack` method on your notifiable entity. This should return the webhook URL to which the notification should be delivered. Webhook URLs may be generated by adding an "Incoming Webhook" service to your Slack team: +Of course, you will often want to send notifications to the Slack workspaces owned by your application's users. To do so, you will first need to obtain a Slack OAuth token for the user. Thankfully, [Laravel Socialite](/docs/{{version}}/socialite) includes a Slack driver that will allow you to easily authenticate your application's users with Slack and [obtain a bot token](/docs/{{version}}/socialite#slack-bot-scopes). - slack_channel, $this->slack_token); } +} +``` ## Localizing Notifications @@ -1140,37 +1687,152 @@ Laravel allows you to send notifications in a locale other than the HTTP request To accomplish this, the `Illuminate\Notifications\Notification` class offers a `locale` method to set the desired language. The application will change into this locale when the notification is being evaluated and then revert back to the previous locale when evaluation is complete: - $user->notify((new InvoicePaid($invoice))->locale('es')); +```php +$user->notify((new InvoicePaid($invoice))->locale('es')); +``` Localization of multiple notifiable entries may also be achieved via the `Notification` facade: - Notification::locale('es')->send( - $users, new InvoicePaid($invoice) - ); +```php +Notification::locale('es')->send( + $users, new InvoicePaid($invoice) +); +``` -### User Preferred Locales +#### User Preferred Locales Sometimes, applications store each user's preferred locale. By implementing the `HasLocalePreference` contract on your notifiable model, you may instruct Laravel to use this stored locale when sending a notification: - use Illuminate\Contracts\Translation\HasLocalePreference; +```php +use Illuminate\Contracts\Translation\HasLocalePreference; - class User extends Model implements HasLocalePreference +class User extends Model implements HasLocalePreference +{ + /** + * Get the user's preferred locale. + */ + public function preferredLocale(): string { - /** - * Get the user's preferred locale. - * - * @return string - */ - public function preferredLocale() - { - return $this->locale; - } + return $this->locale; } +} +``` Once you have implemented the interface, Laravel will automatically use the preferred locale when sending notifications and mailables to the model. Therefore, there is no need to call the `locale` method when using this interface: - $user->notify(new InvoicePaid($invoice)); +```php +$user->notify(new InvoicePaid($invoice)); +``` + + +## Testing + +You may use the `Notification` facade's `fake` method to prevent notifications from being sent. Typically, sending notifications is unrelated to the code you are actually testing. Most likely, it is sufficient to simply assert that Laravel was instructed to send a given notification. + +After calling the `Notification` facade's `fake` method, you may then assert that notifications were instructed to be sent to users and even inspect the data the notifications received: + +```php tab=Pest +order->id === $order->id; + } +); +``` + + +#### On-Demand Notifications + +If the code you are testing sends [on-demand notifications](#on-demand-notifications), you can test that the on-demand notification was sent via the `assertSentOnDemand` method: + +```php +Notification::assertSentOnDemand(OrderShipped::class); +``` + +By passing a closure as the second argument to the `assertSentOnDemand` method, you may determine if an on-demand notification was sent to the correct "route" address: + +```php +Notification::assertSentOnDemand( + OrderShipped::class, + function (OrderShipped $notification, array $channels, object $notifiable) use ($user) { + return $notifiable->routes['mail'] === $user->email; + } +); +``` ## Notification Events @@ -1178,82 +1840,83 @@ Once you have implemented the interface, Laravel will automatically use the pref #### Notification Sending Event -When a notification is sending, the `Illuminate\Notifications\Events\NotificationSending` [event](/docs/{{version}}/events) is dispatched by the notification system. This contains the "notifiable" entity and the notification instance itself. You may register listeners for this event in your application's `EventServiceProvider`: +When a notification is sending, the `Illuminate\Notifications\Events\NotificationSending` event is dispatched by the notification system. This contains the "notifiable" entity and the notification instance itself. You may create [event listeners](/docs/{{version}}/events) for this event within your application: - /** - * The event listener mappings for the application. - * - * @var array - */ - protected $listen = [ - 'Illuminate\Notifications\Events\NotificationSending' => [ - 'App\Listeners\CheckNotificationStatus', - ], - ]; - -The notification will not be sent if an event listener for the `NotificationSending` event returns `false` from its `handle` method: - - use Illuminate\Notifications\Events\NotificationSending; +```php +use Illuminate\Notifications\Events\NotificationSending; +class CheckNotificationStatus +{ /** * Handle the event. - * - * @param \Illuminate\Notifications\Events\NotificationSending $event - * @return void */ - public function handle(NotificationSending $event) + public function handle(NotificationSending $event): void { - return false; + // ... } +} +``` + +The notification will not be sent if an event listener for the `NotificationSending` event returns `false` from its `handle` method: + +```php +/** + * Handle the event. + */ +public function handle(NotificationSending $event): bool +{ + return false; +} +``` Within an event listener, you may access the `notifiable`, `notification`, and `channel` properties on the event to learn more about the notification recipient or the notification itself: - /** - * Handle the event. - * - * @param \Illuminate\Notifications\Events\NotificationSending $event - * @return void - */ - public function handle(NotificationSending $event) - { - // $event->channel - // $event->notifiable - // $event->notification - } +```php +/** + * Handle the event. + */ +public function handle(NotificationSending $event): void +{ + // $event->channel + // $event->notifiable + // $event->notification +} +``` #### Notification Sent Event -When a notification is sent, the `Illuminate\Notifications\Events\NotificationSent` [event](/docs/{{version}}/events) is dispatched by the notification system. This contains the "notifiable" entity and the notification instance itself. You may register listeners for this event in your `EventServiceProvider`: - - /** - * The event listener mappings for the application. - * - * @var array - */ - protected $listen = [ - 'Illuminate\Notifications\Events\NotificationSent' => [ - 'App\Listeners\LogNotification', - ], - ]; - -> {tip} After registering listeners in your `EventServiceProvider`, use the `event:generate` Artisan command to quickly generate listener classes. +When a notification is sent, the `Illuminate\Notifications\Events\NotificationSent` [event](/docs/{{version}}/events) is dispatched by the notification system. This contains the "notifiable" entity and the notification instance itself. You may create [event listeners](/docs/{{version}}/events) for this event within your application: -Within an event listener, you may access the `notifiable`, `notification`, `channel`, and `response` properties on the event to learn more about the notification recipient or the notification itself: +```php +use Illuminate\Notifications\Events\NotificationSent; +class LogNotification +{ /** * Handle the event. - * - * @param \Illuminate\Notifications\Events\NotificationSent $event - * @return void */ - public function handle(NotificationSent $event) + public function handle(NotificationSent $event): void { - // $event->channel - // $event->notifiable - // $event->notification - // $event->response + // ... } +} +``` + +Within an event listener, you may access the `notifiable`, `notification`, `channel`, and `response` properties on the event to learn more about the notification recipient or the notification itself: + +```php +/** + * Handle the event. + */ +public function handle(NotificationSent $event): void +{ + // $event->channel + // $event->notifiable + // $event->notification + // $event->response +} +``` ## Custom Channels @@ -1262,64 +1925,58 @@ Laravel ships with a handful of notification channels, but you may want to write Within the `send` method, you may call methods on the notification to retrieve a message object understood by your channel and then send the notification to the `$notifiable` instance however you wish: - toVoice($notifiable); + $message = $notification->toVoice($notifiable); - // Send notification to the $notifiable instance... - } + // Send notification to the $notifiable instance... } +} +``` Once your notification channel class has been defined, you may return the class name from the `via` method of any of your notifications. In this example, the `toVoice` method of your notification can return whatever object you choose to represent voice messages. For example, you might define your own `VoiceMessage` class to represent these messages: - ## Introduction -[Laravel Octane](https://github.com/laravel/octane) supercharges your application's performance by serving your application using high-powered application servers, including [Open Swoole](https://swoole.co.uk), [Swoole](https://github.com/swoole/swoole-src), and [RoadRunner](https://roadrunner.dev). Octane boots your application once, keeps it in memory, and then feeds it requests at supersonic speeds. +[Laravel Octane](https://github.com/laravel/octane) supercharges your application's performance by serving your application using high-powered application servers, including [FrankenPHP](https://frankenphp.dev/), [Open Swoole](https://openswoole.com/), [Swoole](https://github.com/swoole/swoole-src), and [RoadRunner](https://roadrunner.dev). Octane boots your application once, keeps it in memory, and then feeds it requests at supersonic speeds. ## Installation @@ -46,7 +48,105 @@ php artisan octane:install ## Server Prerequisites -> {note} Laravel Octane requires [PHP 8.0+](https://php.net/releases/). + +### FrankenPHP + +[FrankenPHP](https://frankenphp.dev) is a PHP application server, written in Go, that supports modern web features like early hints, Brotli, and Zstandard compression. When you install Octane and choose FrankenPHP as your server, Octane will automatically download and install the FrankenPHP binary for you. + + +#### FrankenPHP via Laravel Sail + +If you plan to develop your application using [Laravel Sail](/docs/{{version}}/sail), you should run the following commands to install Octane and FrankenPHP: + +```shell +./vendor/bin/sail up + +./vendor/bin/sail composer require laravel/octane +``` + +Next, you should use the `octane:install` Artisan command to install the FrankenPHP binary: + +```shell +./vendor/bin/sail artisan octane:install --server=frankenphp +``` + +Finally, add a `SUPERVISOR_PHP_COMMAND` environment variable to the `laravel.test` service definition in your application's `docker-compose.yml` file. This environment variable will contain the command that Sail will use to serve your application using Octane instead of the PHP development server: + +```yaml +services: + laravel.test: + environment: + SUPERVISOR_PHP_COMMAND: "/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --server=frankenphp --host=0.0.0.0 --admin-port=2019 --port='${APP_PORT:-80}'" # [tl! add] + XDG_CONFIG_HOME: /var/www/html/config # [tl! add] + XDG_DATA_HOME: /var/www/html/data # [tl! add] +``` + +To enable HTTPS, HTTP/2, and HTTP/3, apply these modifications instead: + +```yaml +services: + laravel.test: + ports: + - '${APP_PORT:-80}:80' + - '${VITE_PORT:-5173}:${VITE_PORT:-5173}' + - '443:443' # [tl! add] + - '443:443/udp' # [tl! add] + environment: + SUPERVISOR_PHP_COMMAND: "/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --host=localhost --port=443 --admin-port=2019 --https" # [tl! add] + XDG_CONFIG_HOME: /var/www/html/config # [tl! add] + XDG_DATA_HOME: /var/www/html/data # [tl! add] +``` + +Typically, you should access your FrankenPHP Sail application via `https://localhost`, as using `https://127.0.0.1` requires additional configuration and is [discouraged](https://frankenphp.dev/docs/known-issues/#using-https127001-with-docker). + + +#### FrankenPHP via Docker + +Using FrankenPHP's official Docker images can offer improved performance and the use of additional extensions not included with static installations of FrankenPHP. In addition, the official Docker images provide support for running FrankenPHP on platforms it doesn't natively support, such as Windows. FrankenPHP's official Docker images are suitable for both local development and production usage. + +You may use the following Dockerfile as a starting point for containerizing your FrankenPHP powered Laravel application: + +```dockerfile +FROM dunglas/frankenphp + +RUN install-php-extensions \ + pcntl + # Add other PHP extensions here... + +COPY . /app + +ENTRYPOINT ["php", "artisan", "octane:frankenphp"] +``` + +Then, during development, you may utilize the following Docker Compose file to run your application: + +```yaml +# compose.yaml +services: + frankenphp: + build: + context: . + entrypoint: php artisan octane:frankenphp --workers=1 --max-requests=1 + ports: + - "8000:8000" + volumes: + - .:/app +``` + +If the `--log-level` option is explicitly passed to the `php artisan octane:start` command, Octane will use FrankenPHP's native logger and, unless configured differently, will produce structured JSON logs. + +You may consult [the official FrankenPHP documentation](https://frankenphp.dev/docs/docker/) for more information on running FrankenPHP with Docker. + + +#### Custom Caddyfile Configuration + +When using FrankenPHP, you may specify a custom Caddyfile using the `--caddyfile` option when starting Octane: + +```shell +php artisan octane:start --server=frankenphp --caddyfile=/path/to/your/Caddyfile +``` + +This allows you to customize FrankenPHP's configuration beyond the default settings, such as adding custom middleware, configuring advanced routing, or setting up custom directives. You may consult the [official Caddy documentation](https://caddyserver.com/docs/caddyfile) for more information on Caddyfile syntax and configuration options. ### RoadRunner @@ -54,14 +154,14 @@ php artisan octane:install [RoadRunner](https://roadrunner.dev) is powered by the RoadRunner binary, which is built using Go. The first time you start a RoadRunner based Octane server, Octane will offer to download and install the RoadRunner binary for you. -#### RoadRunner Via Laravel Sail +#### RoadRunner via Laravel Sail If you plan to develop your application using [Laravel Sail](/docs/{{version}}/sail), you should run the following commands to install Octane and RoadRunner: ```shell ./vendor/bin/sail up -./vendor/bin/sail composer require laravel/octane spiral/roadrunner +./vendor/bin/sail composer require laravel/octane spiral/roadrunner-cli spiral/roadrunner-http ``` Next, you should start a Sail shell and use the `rr` executable to retrieve the latest Linux based build of the RoadRunner binary: @@ -73,16 +173,13 @@ Next, you should start a Sail shell and use the `rr` executable to retrieve the ./vendor/bin/rr get-binary ``` -After installing the RoadRunner binary, you may exit your Sail shell session. You will now need to adjust the `supervisor.conf` file used by Sail to keep your application running. To get started, execute the `sail:publish` Artisan command: - -```shell -./vendor/bin/sail artisan sail:publish -``` - -Next, update the `command` directive of your application's `docker/supervisord.conf` file so that Sail serves your application using Octane instead of the PHP development server: +Then, add a `SUPERVISOR_PHP_COMMAND` environment variable to the `laravel.test` service definition in your application's `docker-compose.yml` file. This environment variable will contain the command that Sail will use to serve your application using Octane instead of the PHP development server: -```ini -command=/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --server=roadrunner --host=0.0.0.0 --rpc-port=6001 --port=8000 +```yaml +services: + laravel.test: + environment: + SUPERVISOR_PHP_COMMAND: "/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --server=roadrunner --host=0.0.0.0 --rpc-port=6001 --port='${APP_PORT:-80}'" # [tl! add] ``` Finally, ensure the `rr` binary is executable and build your Sail images: @@ -102,21 +199,32 @@ If you plan to use the Swoole application server to serve your Laravel Octane ap pecl install swoole ``` - -#### Swoole Via Laravel Sail - -> {note} Before serving an Octane application via Sail, ensure you have the latest version of Laravel Sail and execute `./vendor/bin/sail build --no-cache` within your application's root directory. + +#### Open Swoole -Alternatively, you may develop your Swoole based Octane application using [Laravel Sail](/docs/{{version}}/sail), the official Docker based development environment for Laravel. Laravel Sail includes the Swoole extension by default. However, you will still need to adjust the `supervisor.conf` file used by Sail to keep your application running. To get started, execute the `sail:publish` Artisan command: +If you want to use the Open Swoole application server to serve your Laravel Octane application, you must install the Open Swoole PHP extension. Typically, this can be done via PECL: ```shell -./vendor/bin/sail artisan sail:publish +pecl install openswoole ``` -Next, update the `command` directive of your application's `docker/supervisord.conf` file so that Sail serves your application using Octane instead of the PHP development server: +Using Laravel Octane with Open Swoole grants the same functionality provided by Swoole, such as concurrent tasks, ticks, and intervals. -```ini -command=/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --server=swoole --host=0.0.0.0 --port=80 + +#### Swoole via Laravel Sail + +> [!WARNING] +> Before serving an Octane application via Sail, ensure you have the latest version of Laravel Sail and execute `./vendor/bin/sail build --no-cache` within your application's root directory. + +Alternatively, you may develop your Swoole based Octane application using [Laravel Sail](/docs/{{version}}/sail), the official Docker based development environment for Laravel. Laravel Sail includes the Swoole extension by default. However, you will still need to adjust the `docker-compose.yml` file used by Sail. + +To get started, add a `SUPERVISOR_PHP_COMMAND` environment variable to the `laravel.test` service definition in your application's `docker-compose.yml` file. This environment variable will contain the command that Sail will use to serve your application using Octane instead of the PHP development server: + +```yaml +services: + laravel.test: + environment: + SUPERVISOR_PHP_COMMAND: "/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --server=swoole --host=0.0.0.0 --port='${APP_PORT:-80}'" # [tl! add] ``` Finally, build your Sail images: @@ -136,7 +244,7 @@ Swoole supports a few additional configuration options that you may add to your 'log_file' => storage_path('logs/swoole_http.log'), 'package_max_length' => 10 * 1024 * 1024, ], -]; +], ``` @@ -150,8 +258,25 @@ php artisan octane:start By default, Octane will start the server on port 8000, so you may access your application in a web browser via `http://localhost:8000`. + +#### Keeping Octane Running in Production + +If you are deploying your Octane application to production, you should use a process monitor such as Supervisor to ensure the Octane server stays running. A sample Supervisor configuration file for Octane might look like the following: + +```ini +[program:octane] +process_name=%(program_name)s_%(process_num)02d +command=php /home/forge/example.com/artisan octane:start --server=frankenphp --host=127.0.0.1 --port=8000 +autostart=true +autorestart=true +user=forge +redirect_stderr=true +stdout_logfile=/home/forge/example.com/storage/logs/octane.log +stopwaitsecs=3600 +``` + -### Serving Your Application Via HTTPS +### Serving Your Application via HTTPS By default, applications running via Octane generate links prefixed with `http://`. The `OCTANE_HTTPS` environment variable, used within your application's `config/octane.php` configuration file, can be set to `true` when serving your application via HTTPS. When this configuration value is set to `true`, Octane will instruct Laravel to prefix all generated links with `https://`: @@ -160,11 +285,12 @@ By default, applications running via Octane generate links prefixed with `http:/ ``` -### Serving Your Application Via Nginx +### Serving Your Application via Nginx -> {tip} If you aren't quite ready to manage your own server configuration or aren't comfortable configuring all of the various services needed to run a robust Laravel Octane application, check out [Laravel Forge](https://forge.laravel.com). +> [!NOTE] +> If you aren't quite ready to manage your own server configuration or aren't comfortable configuring all of the various services needed to run a robust Laravel Octane application, check out [Laravel Cloud](https://cloud.laravel.com), which offers fully-managed Laravel Octane support. -In production environments, you should serve your Octane application behind a traditional web server such as a Nginx or Apache. Doing so will allow the web server to serve your static assets such as images and stylesheets, as well as manage your SSL certificate termination. +In production environments, you should serve your Octane application behind a traditional web server such as Nginx or Apache. Doing so will allow the web server to serve your static assets such as images and stylesheets, as well as manage your SSL certificate termination. In the Nginx configuration example below, Nginx will serve the site's static assets and proxy requests to the Octane server that is running on port 8000: @@ -223,7 +349,7 @@ server { ``` -### Watching For File Changes +### Watching for File Changes Since your application is loaded in memory once when the Octane server starts, any changes to your application's files will not be reflected when you refresh your browser. For example, route definitions added to your `routes/web.php` file will not be reflected until the server is restarted. For convenience, you may use the `--watch` flag to instruct Octane to automatically restart the server on any file changes within your application: @@ -231,7 +357,7 @@ Since your application is loaded in memory once when the Octane server starts, a php artisan octane:start --watch ``` -Before using this feature, you should ensure that [Node](https://nodejs.org) is installed within your local development environment. In addition, you should install the [Chokidar](https://github.com/paulmillr/chokidar) file-watching library within your project:library: +Before using this feature, you should ensure that [Node](https://nodejs.org) is installed within your local development environment. In addition, you should install the [Chokidar](https://github.com/paulmillr/chokidar) file-watching library within your project: ```shell npm install --save-dev chokidar @@ -240,7 +366,7 @@ npm install --save-dev chokidar You may configure the directories and files that should be watched using the `watch` configuration option within your application's `config/octane.php` configuration file. -### Specifying The Worker Count +### Specifying the Worker Count By default, Octane will start an application request worker for each CPU core provided by your machine. These workers will then be used to serve incoming HTTP requests as they enter your application. You may manually specify how many workers you would like to start using the `--workers` option when invoking the `octane:start` command: @@ -255,16 +381,30 @@ php artisan octane:start --workers=4 --task-workers=6 ``` -### Specifying The Max Request Count +### Specifying the Max Request Count -To help prevent stray memory leaks, Octane can gracefully restart a worker once it has handled a given number of requests. To instruct Octane to do this, you may use the `--max-requests` option: +To help prevent stray memory leaks, Octane gracefully restarts any worker once it has handled 500 requests. To adjust this number, you may use the `--max-requests` option: ```shell php artisan octane:start --max-requests=250 ``` + +### Specifying the Max Execution Time + +By default, Laravel Octane sets a maximum execution time of 30 seconds for incoming requests via the `max_execution_time` option in your application's `config/octane.php` configuration file: + +```php +'max_execution_time' => 30, +``` + +This setting defines the maximum number of seconds that an incoming request is allowed to execute before being terminated. Setting this value to `0` will disable the execution time limit entirely. This configuration option is particularly useful for applications that handle long-running requests, such as file uploads, data processing, or API calls to external services. + +> [!WARNING] +> When you modify the `max_execution_time` configuration, you must restart the Octane server for the changes to take effect. + -### Reloading The Workers +### Reloading the Workers You may gracefully restart the Octane server's application workers using the `octane:reload` command. Typically, this should be done after deployment so that your newly deployed code is loaded into memory and is used to serve to subsequent requests: @@ -273,7 +413,7 @@ php artisan octane:reload ``` -### Stopping The Server +### Stopping the Server You may stop the Octane server using the `octane:stop` Artisan command: @@ -282,7 +422,7 @@ php artisan octane:stop ``` -#### Checking The Server Status +#### Checking the Server Status You may check the current status of the Octane server using the `octane:status` Artisan command: @@ -291,7 +431,7 @@ php artisan octane:status ``` -## Dependency Injection & Octane +## Dependency Injection and Octane Since Octane boots your application once and keeps it in memory while serving requests, there are a few caveats you should consider while building your application. For example, the `register` and `boot` methods of your application's service providers will only be executed once when the request worker initially boots. On subsequent requests, the same application instance will be reused. @@ -306,15 +446,14 @@ In general, you should avoid injecting the application service container or HTTP ```php use App\Service; +use Illuminate\Contracts\Foundation\Application; /** * Register any application services. - * - * @return void */ -public function register() +public function register(): void { - $this->app->singleton(Service::class, function ($app) { + $this->app->singleton(Service::class, function (Application $app) { return new Service($app); }); } @@ -327,8 +466,9 @@ As a work-around, you could either stop registering the binding as a singleton, ```php use App\Service; use Illuminate\Container\Container; +use Illuminate\Contracts\Foundation\Application; -$this->app->bind(Service::class, function ($app) { +$this->app->bind(Service::class, function (Application $app) { return new Service($app); }); @@ -346,15 +486,14 @@ In general, you should avoid injecting the application service container or HTTP ```php use App\Service; +use Illuminate\Contracts\Foundation\Application; /** * Register any application services. - * - * @return void */ -public function register() +public function register(): void { - $this->app->singleton(Service::class, function ($app) { + $this->app->singleton(Service::class, function (Application $app) { return new Service($app['request']); }); } @@ -366,12 +505,13 @@ As a work-around, you could either stop registering the binding as a singleton, ```php use App\Service; +use Illuminate\Contracts\Foundation\Application; -$this->app->bind(Service::class, function ($app) { +$this->app->bind(Service::class, function (Application $app) { return new Service($app['request']); }); -$this->app->singleton(Service::class, function ($app) { +$this->app->singleton(Service::class, function (Application $app) { return new Service(fn () => $app['request']); }); @@ -382,7 +522,8 @@ $service->method($request->input('name')); The global `request` helper will always return the request the application is currently handling and is therefore safe to use within your application. -> {note} It is acceptable to type-hint the `Illuminate\Http\Request` instance on your controller methods and route closures. +> [!WARNING] +> It is acceptable to type-hint the `Illuminate\Http\Request` instance on your controller methods and route closures. ### Configuration Repository Injection @@ -391,15 +532,14 @@ In general, you should avoid injecting the configuration repository instance int ```php use App\Service; +use Illuminate\Contracts\Foundation\Application; /** * Register any application services. - * - * @return void */ -public function register() +public function register(): void { - $this->app->singleton(Service::class, function ($app) { + $this->app->singleton(Service::class, function (Application $app) { return new Service($app->make('config')); }); } @@ -412,8 +552,9 @@ As a work-around, you could either stop registering the binding as a singleton, ```php use App\Service; use Illuminate\Container\Container; +use Illuminate\Contracts\Foundation\Application; -$this->app->bind(Service::class, function ($app) { +$this->app->bind(Service::class, function (Application $app) { return new Service($app->make('config')); }); @@ -436,15 +577,14 @@ use Illuminate\Support\Str; /** * Handle an incoming request. - * - * @param \Illuminate\Http\Request $request - * @return void */ -public function index(Request $request) +public function index(Request $request): array { Service::$data[] = Str::random(10); - // ... + return [ + // ... + ]; } ``` @@ -453,13 +593,14 @@ While building your application, you should take special care to avoid creating ## Concurrent Tasks -> {note} This feature requires [Swoole](#swoole). +> [!WARNING] +> This feature requires [Swoole](#swoole). When using Swoole, you may execute operations concurrently via light-weight background tasks. You may accomplish this using Octane's `concurrently` method. You may combine this method with PHP array destructuring to retrieve the results of each operation: ```php -use App\User; -use App\Server; +use App\Models\User; +use App\Models\Server; use Laravel\Octane\Facades\Octane; [$users, $servers] = Octane::concurrently([ @@ -474,10 +615,13 @@ Concurrent tasks processed by Octane utilize Swoole's "task workers", and execut php artisan octane:start --workers=4 --task-workers=6 ``` +When invoking the `concurrently` method, you should not provide more than 1024 tasks due to limitations imposed by Swoole's task system. + -## Ticks & Intervals +## Ticks and Intervals -> {note} This feature requires [Swoole](#swoole). +> [!WARNING] +> This feature requires [Swoole](#swoole). When using Swoole, you may register "tick" operations that will be executed every specified number of seconds. You may register "tick" callbacks via the `tick` method. The first argument provided to the `tick` method should be a string that represents the name of the ticker. The second argument should be a callable that will be invoked at the specified interval. @@ -485,21 +629,22 @@ In this example, we will register a closure to be invoked every 10 seconds. Typi ```php Octane::tick('simple-ticker', fn () => ray('Ticking...')) - ->seconds(10); + ->seconds(10); ``` Using the `immediate` method, you may instruct Octane to immediately invoke the tick callback when the Octane server initially boots, and every N seconds thereafter: ```php Octane::tick('simple-ticker', fn () => ray('Ticking...')) - ->seconds(10) - ->immediate(); + ->seconds(10) + ->immediate(); ``` ## The Octane Cache -> {note} This feature requires [Swoole](#swoole). +> [!WARNING] +> This feature requires [Swoole](#swoole). When using Swoole, you may leverage the Octane cache driver, which provides read and write speeds of up to 2 million operations per second. Therefore, this cache driver is an excellent choice for applications that need extreme read / write speeds from their caching layer. @@ -509,7 +654,8 @@ This cache driver is powered by [Swoole tables](https://www.swoole.co.uk/docs/mo Cache::store('octane')->put('framework', 'Laravel', 30); ``` -> {tip} The maximum number of entries allowed in the Octane cache may be defined in your application's `octane` configuration file. +> [!NOTE] +> The maximum number of entries allowed in the Octane cache may be defined in your application's `octane` configuration file. ### Cache Intervals @@ -521,13 +667,14 @@ use Illuminate\Support\Str; Cache::store('octane')->interval('random', function () { return Str::random(10); -}, seconds: 5) +}, seconds: 5); ``` ## Tables -> {note} This feature requires [Swoole](#swoole). +> [!WARNING] +> This feature requires [Swoole](#swoole). When using Swoole, you may define and interact with your own arbitrary [Swoole tables](https://www.swoole.co.uk/docs/modules/swoole-table). Swoole tables provide extreme performance throughput and the data in these tables can be accessed by all workers on the server. However, the data within them will be lost when the server is restarted. @@ -555,4 +702,5 @@ Octane::table('example')->set('uuid', [ return Octane::table('example')->get('uuid'); ``` -> {note} The column types supported by Swoole tables are: `string`, `int`, and `float`. +> [!WARNING] +> The column types supported by Swoole tables are: `string`, `int`, and `float`. diff --git a/packages.md b/packages.md index 83248a5dac9..3fb9dd306f1 100644 --- a/packages.md +++ b/packages.md @@ -1,17 +1,19 @@ # Package Development - [Introduction](#introduction) - - [A Note On Facades](#a-note-on-facades) + - [A Note on Facades](#a-note-on-facades) - [Package Discovery](#package-discovery) - [Service Providers](#service-providers) - [Resources](#resources) - [Configuration](#configuration) - - [Migrations](#migrations) - [Routes](#routes) - - [Translations](#translations) + - [Migrations](#migrations) + - [Language Files](#language-files) - [Views](#views) - [View Components](#view-components) + - ["About" Artisan Command](#about-artisan-command) - [Commands](#commands) + - [Optimize Commands](#optimize-commands) - [Public Assets](#public-assets) - [Publishing File Groups](#publishing-file-groups) @@ -20,19 +22,19 @@ Packages are the primary way of adding functionality to Laravel. Packages might be anything from a great way to work with dates like [Carbon](https://github.com/briannesbitt/Carbon) or a package that allows you to associate files with Eloquent models like Spatie's [Laravel Media Library](https://github.com/spatie/laravel-medialibrary). -There are different types of packages. Some packages are stand-alone, meaning they work with any PHP framework. Carbon and PHPUnit are examples of stand-alone packages. Any of these packages may be used with Laravel by requiring them in your `composer.json` file. +There are different types of packages. Some packages are stand-alone, meaning they work with any PHP framework. Carbon and Pest are examples of stand-alone packages. Any of these packages may be used with Laravel by requiring them in your `composer.json` file. On the other hand, other packages are specifically intended for use with Laravel. These packages may have routes, controllers, views, and configuration specifically intended to enhance a Laravel application. This guide primarily covers the development of those packages that are Laravel specific. -### A Note On Facades +### A Note on Facades When writing a Laravel application, it generally does not matter if you use contracts or facades since both provide essentially equal levels of testability. However, when writing packages, your package will not typically have access to all of Laravel's testing helpers. If you would like to be able to write your package tests as if the package were installed inside a typical Laravel application, you may use the [Orchestral Testbench](https://github.com/orchestral/testbench) package. ## Package Discovery -In a Laravel application's `config/app.php` configuration file, the `providers` option defines a list of service providers that should be loaded by Laravel. When someone installs your package, you will typically want your service provider to be included in this list. Instead of requiring users to manually add your service provider to the list, you may define the provider in the `extra` section of your package's `composer.json` file. In addition to service providers, you may also list any [facades](/docs/{{version}}/facades) you would like to be registered: +A Laravel application's `bootstrap/providers.php` file contains the list of service providers that should be loaded by Laravel. However, instead of requiring users to manually add your service provider to the list, you may define the provider in the `extra` section of your package's `composer.json` file so that it is automatically loaded by Laravel. In addition to service providers, you may also list any [facades](/docs/{{version}}/facades) you would like to be registered: ```json "extra": { @@ -50,7 +52,7 @@ In a Laravel application's `config/app.php` configuration file, the `providers` Once your package has been configured for discovery, Laravel will automatically register its service providers and facades when it is installed, creating a convenient installation experience for your package's users. -### Opting Out Of Package Discovery +#### Opting Out of Package Discovery If you are the consumer of a package and would like to disable package discovery for a package, you may list the package name in the `extra` section of your application's `composer.json` file: @@ -79,7 +81,7 @@ You may disable package discovery for all packages using the `*` character insid ## Service Providers -[Service providers](/docs/{{version}}/providers) are the connection point between your package and Laravel. A service provider is responsible for binding things into Laravel's [service container](/docs/{{version}}/container) and informing Laravel where to load package resources such as views, configuration, and localization files. +[Service providers](/docs/{{version}}/providers) are the connection point between your package and Laravel. A service provider is responsible for binding things into Laravel's [service container](/docs/{{version}}/container) and informing Laravel where to load package resources such as views, configuration, and language files. A service provider extends the `Illuminate\Support\ServiceProvider` class and contains two methods: `register` and `boot`. The base `ServiceProvider` class is located in the `illuminate/support` Composer package, which you should add to your own package's dependencies. To learn more about the structure and purpose of service providers, check out [their documentation](/docs/{{version}}/providers). @@ -91,23 +93,26 @@ A service provider extends the `Illuminate\Support\ServiceProvider` class and co Typically, you will need to publish your package's configuration file to the application's `config` directory. This will allow users of your package to easily override your default configuration options. To allow your configuration files to be published, call the `publishes` method from the `boot` method of your service provider: - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->publishes([ - __DIR__.'/../config/courier.php' => config_path('courier.php'), - ]); - } +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->publishes([ + __DIR__.'/../config/courier.php' => config_path('courier.php'), + ]); +} +``` Now, when users of your package execute Laravel's `vendor:publish` command, your file will be copied to the specified publish location. Once your configuration has been published, its values may be accessed like any other configuration file: - $value = config('courier.option'); +```php +$value = config('courier.option'); +``` -> {note} You should not define closures in your configuration files. They can not be serialized correctly when users execute the `config:cache` Artisan command. +> [!WARNING] +> You should not define closures in your configuration files. They cannot be serialized correctly when users execute the `config:cache` Artisan command. #### Default Package Configuration @@ -116,112 +121,129 @@ You may also merge your own package configuration file with the application's pu The `mergeConfigFrom` method accepts the path to your package's configuration file as its first argument and the name of the application's copy of the configuration file as its second argument: - /** - * Register any application services. - * - * @return void - */ - public function register() - { - $this->mergeConfigFrom( - __DIR__.'/../config/courier.php', 'courier' - ); - } +```php +/** + * Register any package services. + */ +public function register(): void +{ + $this->mergeConfigFrom( + __DIR__.'/../config/courier.php', 'courier' + ); +} +``` -> {note} This method only merges the first level of the configuration array. If your users partially define a multi-dimensional configuration array, the missing options will not be merged. +> [!WARNING] +> This method only merges the first level of the configuration array. If your users partially define a multi-dimensional configuration array, the missing options will not be merged. ### Routes If your package contains routes, you may load them using the `loadRoutesFrom` method. This method will automatically determine if the application's routes are cached and will not load your routes file if the routes have already been cached: - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->loadRoutesFrom(__DIR__.'/../routes/web.php'); - } +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->loadRoutesFrom(__DIR__.'/../routes/web.php'); +} +``` ### Migrations -If your package contains [database migrations](/docs/{{version}}/migrations), you may use the `loadMigrationsFrom` method to inform Laravel how to load them. The `loadMigrationsFrom` method accepts the path to your package's migrations as its only argument: +If your package contains [database migrations](/docs/{{version}}/migrations), you may use the `publishesMigrations` method to inform Laravel that the given directory or file contains migrations. When Laravel publishes the migrations, it will automatically update the timestamp within their filename to reflect the current date and time: + +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->publishesMigrations([ + __DIR__.'/../database/migrations' => database_path('migrations'), + ]); +} +``` - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); - } + +### Language Files -Once your package's migrations have been registered, they will automatically be run when the `php artisan migrate` command is executed. You do not need to export them to the application's `database/migrations` directory. +If your package contains [language files](/docs/{{version}}/localization), you may use the `loadTranslationsFrom` method to inform Laravel how to load them. For example, if your package is named `courier`, you should add the following to your service provider's `boot` method: - -### Translations +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->loadTranslationsFrom(__DIR__.'/../lang', 'courier'); +} +``` -If your package contains [translation files](/docs/{{version}}/localization), you may use the `loadTranslationsFrom` method to inform Laravel how to load them. For example, if your package is named `courier`, you should add the following to your service provider's `boot` method: +Package translation lines are referenced using the `package::file.line` syntax convention. So, you may load the `courier` package's `welcome` line from the `messages` file like so: - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->loadTranslationsFrom(__DIR__.'/../lang', 'courier'); - } +```php +echo trans('courier::messages.welcome'); +``` -Package translations are referenced using the `package::file.line` syntax convention. So, you may load the `courier` package's `welcome` line from the `messages` file like so: +You can register JSON translation files for your package using the `loadJsonTranslationsFrom` method. This method accepts the path to the directory that contains your package's JSON translation files: - echo trans('courier::messages.welcome'); +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->loadJsonTranslationsFrom(__DIR__.'/../lang'); +} +``` - -#### Publishing Translations + +#### Publishing Language Files -If you would like to publish your package's translations to the application's `lang/vendor` directory, you may use the service provider's `publishes` method. The `publishes` method accepts an array of package paths and their desired publish locations. For example, to publish the translation files for the `courier` package, you may do the following: +If you would like to publish your package's language files to the application's `lang/vendor` directory, you may use the service provider's `publishes` method. The `publishes` method accepts an array of package paths and their desired publish locations. For example, to publish the language files for the `courier` package, you may do the following: - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->loadTranslationsFrom(__DIR__.'/../lang', 'courier'); +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->loadTranslationsFrom(__DIR__.'/../lang', 'courier'); - $this->publishes([ - __DIR__.'/../lang' => $this->app->langPath('vendor/courier'), - ]); - } + $this->publishes([ + __DIR__.'/../lang' => $this->app->langPath('vendor/courier'), + ]); +} +``` -Now, when users of your package execute Laravel's `vendor:publish` Artisan command, your package's translations will be published to the specified publish location. +Now, when users of your package execute Laravel's `vendor:publish` Artisan command, your package's language files will be published to the specified publish location. ### Views To register your package's [views](/docs/{{version}}/views) with Laravel, you need to tell Laravel where the views are located. You may do this using the service provider's `loadViewsFrom` method. The `loadViewsFrom` method accepts two arguments: the path to your view templates and your package's name. For example, if your package's name is `courier`, you would add the following to your service provider's `boot` method: - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->loadViewsFrom(__DIR__.'/../resources/views', 'courier'); - } +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->loadViewsFrom(__DIR__.'/../resources/views', 'courier'); +} +``` Package views are referenced using the `package::view` syntax convention. So, once your view path is registered in a service provider, you may load the `dashboard` view from the `courier` package like so: - Route::get('/dashboard', function () { - return view('courier::dashboard'); - }); +```php +Route::get('/dashboard', function () { + return view('courier::dashboard'); +}); +``` #### Overriding Package Views @@ -233,99 +255,157 @@ When you use the `loadViewsFrom` method, Laravel actually registers two location If you would like to make your views available for publishing to the application's `resources/views/vendor` directory, you may use the service provider's `publishes` method. The `publishes` method accepts an array of package view paths and their desired publish locations: - /** - * Bootstrap the package services. - * - * @return void - */ - public function boot() - { - $this->loadViewsFrom(__DIR__.'/../resources/views', 'courier'); - - $this->publishes([ - __DIR__.'/../resources/views' => resource_path('views/vendor/courier'), - ]); - } +```php +/** + * Bootstrap the package services. + */ +public function boot(): void +{ + $this->loadViewsFrom(__DIR__.'/../resources/views', 'courier'); + + $this->publishes([ + __DIR__.'/../resources/views' => resource_path('views/vendor/courier'), + ]); +} +``` Now, when users of your package execute Laravel's `vendor:publish` Artisan command, your package's views will be copied to the specified publish location. ### View Components -If your package contains [view components](/docs/{{version}}/blade#components), you may use the `loadViewComponentsAs` method to inform Laravel how to load them. The `loadViewComponentsAs` method accepts two arguments: the tag prefix for your view components and an array of your view component class names. For example, if your package's prefix is `courier` and you have `Alert` and `Button` view components, you would add the following to your service provider's `boot` method: - - use Courier\Components\Alert; - use Courier\Components\Button; - - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->loadViewComponentsAs('courier', [ - Alert::class, - Button::class, - ]); - } +If you are building a package that utilizes Blade components or placing components in non-conventional directories, you will need to manually register your component class and its HTML tag alias so that Laravel knows where to find the component. You should typically register your components in the `boot` method of your package's service provider: + +```php +use Illuminate\Support\Facades\Blade; +use VendorPackage\View\Components\AlertComponent; + +/** + * Bootstrap your package's services. + */ +public function boot(): void +{ + Blade::component('package-alert', AlertComponent::class); +} +``` -Once your view components are registered in a service provider, you may reference them in your view like so: +Once your component has been registered, it may be rendered using its tag alias: ```blade - + +``` + + +#### Autoloading Package Components + +Alternatively, you may use the `componentNamespace` method to autoload component classes by convention. For example, a `Nightshade` package might have `Calendar` and `ColorPicker` components that reside within the `Nightshade\Views\Components` namespace: - +```php +use Illuminate\Support\Facades\Blade; + +/** + * Bootstrap your package's services. + */ +public function boot(): void +{ + Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade'); +} ``` +This will allow the usage of package components by their vendor namespace using the `package-name::` syntax: + +```blade + + +``` + +Blade will automatically detect the class that's linked to this component by pascal-casing the component name. Subdirectories are also supported using "dot" notation. + #### Anonymous Components -If your package contains anonymous components, they must be placed within a `components` directory of your package's "views" directory (as specified by `loadViewsFrom`). Then, you may render them by prefixing the component name with the package's view namespace: +If your package contains anonymous components, they must be placed within a `components` directory of your package's "views" directory (as specified by the [loadViewsFrom method](#views)). Then, you may render them by prefixing the component name with the package's view namespace: ```blade ``` + +### "About" Artisan Command + +Laravel's built-in `about` Artisan command provides a synopsis of the application's environment and configuration. Packages may push additional information to this command's output via the `AboutCommand` class. Typically, this information may be added from your package service provider's `boot` method: + +```php +use Illuminate\Foundation\Console\AboutCommand; + +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + AboutCommand::add('My Package', fn () => ['Version' => '1.0.0']); +} +``` + ## Commands To register your package's Artisan commands with Laravel, you may use the `commands` method. This method expects an array of command class names. Once the commands have been registered, you may execute them using the [Artisan CLI](/docs/{{version}}/artisan): - use Courier\Console\Commands\InstallCommand; - use Courier\Console\Commands\NetworkCommand; - - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - if ($this->app->runningInConsole()) { - $this->commands([ - InstallCommand::class, - NetworkCommand::class, - ]); - } +```php +use Courier\Console\Commands\InstallCommand; +use Courier\Console\Commands\NetworkCommand; + +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + if ($this->app->runningInConsole()) { + $this->commands([ + InstallCommand::class, + NetworkCommand::class, + ]); + } +} +``` + + +### Optimize Commands + +Laravel's [optimize command](/docs/{{version}}/deployment#optimization) caches the application's configuration, events, routes, and views. Using the `optimizes` method, you may register your package's own Artisan commands that should be invoked when the `optimize` and `optimize:clear` commands are executed: + +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + if ($this->app->runningInConsole()) { + $this->optimizes( + optimize: 'package:optimize', + clear: 'package:clear-optimizations', + ); } +} +``` ## Public Assets Your package may have assets such as JavaScript, CSS, and images. To publish these assets to the application's `public` directory, use the service provider's `publishes` method. In this example, we will also add a `public` asset group tag, which may be used to easily publish groups of related assets: - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->publishes([ - __DIR__.'/../public' => public_path('vendor/courier'), - ], 'public'); - } +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->publishes([ + __DIR__.'/../public' => public_path('vendor/courier'), + ], 'public'); +} +``` Now, when your package's users execute the `vendor:publish` command, your assets will be copied to the specified publish location. Since users will typically need to overwrite the assets every time the package is updated, you may use the `--force` flag: @@ -338,24 +418,30 @@ php artisan vendor:publish --tag=public --force You may want to publish groups of package assets and resources separately. For instance, you might want to allow your users to publish your package's configuration files without being forced to publish your package's assets. You may do this by "tagging" them when calling the `publishes` method from a package's service provider. For example, let's use tags to define two publish groups for the `courier` package (`courier-config` and `courier-migrations`) in the `boot` method of the package's service provider: - /** - * Bootstrap any package services. - * - * @return void - */ - public function boot() - { - $this->publishes([ - __DIR__.'/../config/package.php' => config_path('package.php') - ], 'courier-config'); - - $this->publishes([ - __DIR__.'/../database/migrations/' => database_path('migrations') - ], 'courier-migrations'); - } +```php +/** + * Bootstrap any package services. + */ +public function boot(): void +{ + $this->publishes([ + __DIR__.'/../config/package.php' => config_path('package.php') + ], 'courier-config'); + + $this->publishesMigrations([ + __DIR__.'/../database/migrations/' => database_path('migrations') + ], 'courier-migrations'); +} +``` Now your users may publish these groups separately by referencing their tag when executing the `vendor:publish` command: ```shell php artisan vendor:publish --tag=courier-config ``` + +Your users can also publish all publishable files defined by your package's service provider using the `--provider` flag: + +```shell +php artisan vendor:publish --provider="Your\Package\ServiceProvider" +``` diff --git a/pagination.md b/pagination.md index e68e3d5a5ce..8ffa1a6ae4a 100644 --- a/pagination.md +++ b/pagination.md @@ -5,12 +5,12 @@ - [Paginating Query Builder Results](#paginating-query-builder-results) - [Paginating Eloquent Results](#paginating-eloquent-results) - [Cursor Pagination](#cursor-pagination) - - [Manually Creating A Paginator](#manually-creating-a-paginator) + - [Manually Creating a Paginator](#manually-creating-a-paginator) - [Customizing Pagination URLs](#customizing-pagination-urls) - [Displaying Pagination Results](#displaying-pagination-results) - - [Adjusting The Pagination Link Window](#adjusting-the-pagination-link-window) - - [Converting Results To JSON](#converting-results-to-json) -- [Customizing The Pagination View](#customizing-the-pagination-view) + - [Adjusting the Pagination Link Window](#adjusting-the-pagination-link-window) + - [Converting Results to JSON](#converting-results-to-json) +- [Customizing the Pagination View](#customizing-the-pagination-view) - [Using Bootstrap](#using-bootstrap) - [Paginator and LengthAwarePaginator Instance Methods](#paginator-instance-methods) - [Cursor Paginator Instance Methods](#cursor-paginator-instance-methods) @@ -20,20 +20,17 @@ In other frameworks, pagination can be very painful. We hope Laravel's approach to pagination will be a breath of fresh air. Laravel's paginator is integrated with the [query builder](/docs/{{version}}/queries) and [Eloquent ORM](/docs/{{version}}/eloquent) and provides convenient, easy-to-use pagination of database records with zero configuration. -By default, the HTML generated by the paginator is compatible with the [Tailwind CSS framework](https://tailwindcss.com/); however, Bootstrap pagination support is also available. +By default, the HTML generated by the paginator is compatible with the [Tailwind CSS framework](https://tailwindcss.com/); however, Bootstrap pagination support is also available. - -#### Tailwind JIT + +#### Tailwind -If you are using Laravel's default Tailwind pagination views and the Tailwind JIT engine, you should ensure your application's `tailwind.config.js` file's `content` key references Laravel's pagination views so that their Tailwind classes are not purged: +If you are using Laravel's default Tailwind pagination views with Tailwind 4.x, your application's `resources/css/app.css` file will already be properly configured to `@source` Laravel's pagination views: -```js -content: [ - './resources/**/*.blade.php', - './resources/**/*.js', - './resources/**/*.vue', - './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php', -], +```css +@import 'https://github.com/tailwindcss'; + +@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php'; ``` @@ -46,27 +43,27 @@ There are several ways to paginate items. The simplest is by using the `paginate In this example, the only argument passed to the `paginate` method is the number of items you would like displayed "per page". In this case, let's specify that we would like to display `15` items per page: - DB::table('users')->paginate(15) - ]); - } + return view('user.index', [ + 'users' => DB::table('users')->paginate(15) + ]); } +} +``` #### Simple Pagination @@ -75,58 +72,73 @@ The `paginate` method counts the total number of records matched by the query be Therefore, if you only need to display simple "Next" and "Previous" links in your application's UI, you may use the `simplePaginate` method to perform a single, efficient query: - $users = DB::table('users')->simplePaginate(15); +```php +$users = DB::table('users')->simplePaginate(15); +``` ### Paginating Eloquent Results You may also paginate [Eloquent](/docs/{{version}}/eloquent) queries. In this example, we will paginate the `App\Models\User` model and indicate that we plan to display 15 records per page. As you can see, the syntax is nearly identical to paginating query builder results: - use App\Models\User; +```php +use App\Models\User; - $users = User::paginate(15); +$users = User::paginate(15); +``` Of course, you may call the `paginate` method after setting other constraints on the query, such as `where` clauses: - $users = User::where('votes', '>', 100)->paginate(15); +```php +$users = User::where('votes', '>', 100)->paginate(15); +``` You may also use the `simplePaginate` method when paginating Eloquent models: - $users = User::where('votes', '>', 100)->simplePaginate(15); +```php +$users = User::where('votes', '>', 100)->simplePaginate(15); +``` Similarly, you may use the `cursorPaginate` method to cursor paginate Eloquent models: - $users = User::where('votes', '>', 100)->cursorPaginate(15); +```php +$users = User::where('votes', '>', 100)->cursorPaginate(15); +``` -#### Multiple Paginator Instances Per Page +#### Multiple Paginator Instances per Page -Sometimes you may need to render two separate paginators on a single screen that is rendered by your application. However, if both paginator instances use the `page` query string parameter to store the current page, the two paginator's will conflict. To resolve this conflict, you may pass the name of the query string parameter you wish to use to store the paginator's current page via the third argument provided to the `paginate`, `simplePaginate`, and `cursorPaginate` methods: +Sometimes you may need to render two separate paginators on a single screen that is rendered by your application. However, if both paginator instances use the `page` query string parameter to store the current page, the two paginators will conflict. To resolve this conflict, you may pass the name of the query string parameter you wish to use to store the paginator's current page via the third argument provided to the `paginate`, `simplePaginate`, and `cursorPaginate` methods: - use App\Models\User; +```php +use App\Models\User; - $users = User::where('votes', '>', 100)->paginate( - $perPage = 15, $columns = ['*'], $pageName = 'users' - ); +$users = User::where('votes', '>', 100)->paginate( + $perPage = 15, $columns = ['*'], $pageName = 'users' +); +``` ### Cursor Pagination While `paginate` and `simplePaginate` create queries using the SQL "offset" clause, cursor pagination works by constructing "where" clauses that compare the values of the ordered columns contained in the query, providing the most efficient database performance available amongst all of Laravel's pagination methods. This method of pagination is particularly well-suited for large data-sets and "infinite" scrolling user interfaces. -Unlike offset based pagination, which includes a page number in the query string of the URLs generated by the paginator, cursor based pagination places a "cursor" string in the query string. The cursor is an encoded string containing the location that the next paginated query should start paginating and the direction that it should paginate: +Unlike offset based pagination, which includes a page number in the query string of the URLs generated by the paginator, cursor-based pagination places a "cursor" string in the query string. The cursor is an encoded string containing the location that the next paginated query should start paginating and the direction that it should paginate: -```nothing +```text http://localhost/users?cursor=eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0 ``` -You may create a cursor based paginator instance via the `cursorPaginate` method offered by the query builder. This method returns an instance of `Illuminate\Pagination\CursorPaginator`: +You may create a cursor-based paginator instance via the `cursorPaginate` method offered by the query builder. This method returns an instance of `Illuminate\Pagination\CursorPaginator`: - $users = DB::table('users')->orderBy('id')->cursorPaginate(15); +```php +$users = DB::table('users')->orderBy('id')->cursorPaginate(15); +``` Once you have retrieved a cursor paginator instance, you may [display the pagination results](#displaying-pagination-results) as you typically would when using the `paginate` and `simplePaginate` methods. For more information on the instance methods offered by the cursor paginator, please consult the [cursor paginator instance method documentation](#cursor-paginator-instance-methods). -> {note} Your query must contain an "order by" clause in order to take advantage of cursor pagination. +> [!WARNING] +> Your query must contain an "order by" clause in order to take advantage of cursor pagination. In addition, the columns that the query are ordered by must belong to the table you are paginating. #### Cursor vs. Offset Pagination @@ -151,9 +163,10 @@ However, cursor pagination has the following limitations: - Like `simplePaginate`, cursor pagination can only be used to display "Next" and "Previous" links and does not support generating links with page numbers. - It requires that the ordering is based on at least one unique column or a combination of columns that are unique. Columns with `null` values are not supported. - Query expressions in "order by" clauses are supported only if they are aliased and added to the "select" clause as well. +- Query expressions with parameters are not supported. -### Manually Creating A Paginator +### Manually Creating a Paginator Sometimes you may wish to create a pagination instance manually, passing it an array of items that you already have in memory. You may do so by creating either an `Illuminate\Pagination\Paginator`, `Illuminate\Pagination\LengthAwarePaginator` or `Illuminate\Pagination\CursorPaginator` instance, depending on your needs. @@ -161,55 +174,64 @@ The `Paginator` and `CursorPaginator` classes do not need to know the total numb In other words, the `Paginator` corresponds to the `simplePaginate` method on the query builder, the `CursorPaginator` corresponds to the `cursorPaginate` method, and the `LengthAwarePaginator` corresponds to the `paginate` method. -> {note} When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. If you're unsure how to do this, check out the [array_slice](https://secure.php.net/manual/en/function.array-slice.php) PHP function. +> [!WARNING] +> When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. If you're unsure how to do this, check out the [array_slice](https://secure.php.net/manual/en/function.array-slice.php) PHP function. ### Customizing Pagination URLs By default, links generated by the paginator will match the current request's URI. However, the paginator's `withPath` method allows you to customize the URI used by the paginator when generating links. For example, if you want the paginator to generate links like `http://example.com/admin/users?page=N`, you should pass `/admin/users` to the `withPath` method: - use App\Models\User; +```php +use App\Models\User; - Route::get('/users', function () { - $users = User::paginate(15); +Route::get('/users', function () { + $users = User::paginate(15); - $users->withPath('/admin/users'); + $users->withPath('/admin/users'); - // - }); + // ... +}); +``` #### Appending Query String Values You may append to the query string of pagination links using the `appends` method. For example, to append `sort=votes` to each pagination link, you should make the following call to `appends`: - use App\Models\User; +```php +use App\Models\User; - Route::get('/users', function () { - $users = User::paginate(15); +Route::get('/users', function () { + $users = User::paginate(15); - $users->appends(['sort' => 'votes']); + $users->appends(['sort' => 'votes']); - // - }); + // ... +}); +``` You may use the `withQueryString` method if you would like to append all of the current request's query string values to the pagination links: - $users = User::paginate(15)->withQueryString(); +```php +$users = User::paginate(15)->withQueryString(); +``` #### Appending Hash Fragments If you need to append a "hash fragment" to URLs generated by the paginator, you may use the `fragment` method. For example, to append `#users` to the end of each pagination link, you should invoke the `fragment` method like so: - $users = User::paginate(15)->fragment('users'); +```php +$users = User::paginate(15)->fragment('users'); +``` ## Displaying Pagination Results When calling the `paginate` method, you will receive an instance of `Illuminate\Pagination\LengthAwarePaginator`, while calling the `simplePaginate` method returns an instance of `Illuminate\Pagination\Paginator`. And, finally, calling the `cursorPaginate` method returns an instance of `Illuminate\Pagination\CursorPaginator`. -These objects provide several methods that describe the result set. In addition to these helpers methods, the paginator instances are iterators and may be looped as an array. So, once you have retrieved the results, you may display the results and render the page links using [Blade](/docs/{{version}}/blade): +These objects provide several methods that describe the result set. In addition to these helper methods, the paginator instances are iterators and may be looped as an array. So, once you have retrieved the results, you may display the results and render the page links using [Blade](/docs/{{version}}/blade): ```blade
@@ -224,7 +246,7 @@ These objects provide several methods that describe the result set. In addition The `links` method will render the links to the rest of the pages in the result set. Each of these links will already contain the proper `page` query string variable. Remember, the HTML generated by the `links` method is compatible with the [Tailwind CSS framework](https://tailwindcss.com). -### Adjusting The Pagination Link Window +### Adjusting the Pagination Link Window When the paginator displays pagination links, the current page number is displayed as well as links for the three pages before and after the current page. Using the `onEachSide` method, you may control how many additional links are displayed on each side of the current page within the middle, sliding window of links generated by the paginator: @@ -233,42 +255,47 @@ When the paginator displays pagination links, the current page number is display ``` -### Converting Results To JSON +### Converting Results to JSON The Laravel paginator classes implement the `Illuminate\Contracts\Support\Jsonable` Interface contract and expose the `toJson` method, so it's very easy to convert your pagination results to JSON. You may also convert a paginator instance to JSON by returning it from a route or controller action: - use App\Models\User; +```php +use App\Models\User; - Route::get('/users', function () { - return User::paginate(); - }); +Route::get('/users', function () { + return User::paginate(); +}); +``` The JSON from the paginator will include meta information such as `total`, `current_page`, `last_page`, and more. The result records are available via the `data` key in the JSON array. Here is an example of the JSON created by returning a paginator instance from a route: - { - "total": 50, - "per_page": 15, - "current_page": 1, - "last_page": 4, - "first_page_url": "http://laravel.app/?page=1", - "last_page_url": "http://laravel.app/?page=4", - "next_page_url": "http://laravel.app/?page=2", - "prev_page_url": null, - "path": "http://laravel.app/", - "from": 1, - "to": 15, - "data":[ - { - // Record... - }, - { - // Record... - } - ] - } +```json +{ + "total": 50, + "per_page": 15, + "current_page": 1, + "last_page": 4, + "current_page_url": "http://laravel.app/?page=1", + "first_page_url": "http://laravel.app/?page=1", + "last_page_url": "http://laravel.app/?page=4", + "next_page_url": "http://laravel.app/?page=2", + "prev_page_url": null, + "path": "http://laravel.app/", + "from": 1, + "to": 15, + "data":[ + { + // Record... + }, + { + // Record... + } + ] +} +``` -## Customizing The Pagination View +## Customizing the Pagination View By default, the views rendered to display the pagination links are compatible with the [Tailwind CSS](https://tailwindcss.com) framework. However, if you are not using Tailwind, you are free to define your own views to render these links. When calling the `links` method on a paginator instance, you may pass the view name as the first argument to the method: @@ -289,91 +316,102 @@ This command will place the views in your application's `resources/views/vendor/ If you would like to designate a different file as the default pagination view, you may invoke the paginator's `defaultView` and `defaultSimpleView` methods within the `boot` method of your `App\Providers\AppServiceProvider` class: - ### Using Bootstrap Laravel includes pagination views built using [Bootstrap CSS](https://getbootstrap.com/). To use these views instead of the default Tailwind views, you may call the paginator's `useBootstrapFour` or `useBootstrapFive` methods within the `boot` method of your `App\Providers\AppServiceProvider` class: - use Illuminate\Pagination\Paginator; - - /** - * Bootstrap any application services. - * - * @return void - */ - public function boot() - { - Paginator::useBootstrapFive(); - Paginator::useBootstrapFour(); - } +```php +use Illuminate\Pagination\Paginator; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Paginator::useBootstrapFive(); + Paginator::useBootstrapFour(); +} +``` ## Paginator / LengthAwarePaginator Instance Methods Each paginator instance provides additional pagination information via the following methods: -Method | Description -------- | ----------- -`$paginator->count()` | Get the number of items for the current page. -`$paginator->currentPage()` | Get the current page number. -`$paginator->firstItem()` | Get the result number of the first item in the results. -`$paginator->getOptions()` | Get the paginator options. -`$paginator->getUrlRange($start, $end)` | Create a range of pagination URLs. -`$paginator->hasPages()` | Determine if there are enough items to split into multiple pages. -`$paginator->hasMorePages()` | Determine if there are more items in the data store. -`$paginator->items()` | Get the items for the current page. -`$paginator->lastItem()` | Get the result number of the last item in the results. -`$paginator->lastPage()` | Get the page number of the last available page. (Not available when using `simplePaginate`). -`$paginator->nextPageUrl()` | Get the URL for the next page. -`$paginator->onFirstPage()` | Determine if the paginator is on the first page. -`$paginator->perPage()` | The number of items to be shown per page. -`$paginator->previousPageUrl()` | Get the URL for the previous page. -`$paginator->total()` | Determine the total number of matching items in the data store. (Not available when using `simplePaginate`). -`$paginator->url(https://github.com/$page)` | Get the URL for a given page number. -`$paginator->getPageName()` | Get the query string variable used to store the page. -`$paginator->setPageName($name)` | Set the query string variable used to store the page. +
+ +| Method | Description | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------ | +| `$paginator->count()` | Get the number of items for the current page. | +| `$paginator->currentPage()` | Get the current page number. | +| `$paginator->firstItem()` | Get the result number of the first item in the results. | +| `$paginator->getOptions()` | Get the paginator options. | +| `$paginator->getUrlRange($start, $end)` | Create a range of pagination URLs. | +| `$paginator->hasPages()` | Determine if there are enough items to split into multiple pages. | +| `$paginator->hasMorePages()` | Determine if there are more items in the data store. | +| `$paginator->items()` | Get the items for the current page. | +| `$paginator->lastItem()` | Get the result number of the last item in the results. | +| `$paginator->lastPage()` | Get the page number of the last available page. (Not available when using `simplePaginate`). | +| `$paginator->nextPageUrl()` | Get the URL for the next page. | +| `$paginator->onFirstPage()` | Determine if the paginator is on the first page. | +| `$paginator->onLastPage()` | Determine if the paginator is on the last page. | +| `$paginator->perPage()` | The number of items to be shown per page. | +| `$paginator->previousPageUrl()` | Get the URL for the previous page. | +| `$paginator->total()` | Determine the total number of matching items in the data store. (Not available when using `simplePaginate`). | +| `$paginator->url(https://github.com/$page)` | Get the URL for a given page number. | +| `$paginator->getPageName()` | Get the query string variable used to store the page. | +| `$paginator->setPageName($name)` | Set the query string variable used to store the page. | +| `$paginator->through($callback)` | Transform each item using a callback. | + +
## Cursor Paginator Instance Methods Each cursor paginator instance provides additional pagination information via the following methods: -Method | Description -------- | ----------- -`$paginator->count()` | Get the number of items for the current page. -`$paginator->cursor()` | Get the current cursor instance. -`$paginator->getOptions()` | Get the paginator options. -`$paginator->hasPages()` | Determine if there are enough items to split into multiple pages. -`$paginator->hasMorePages()` | Determine if there are more items in the data store. -`$paginator->getCursorName()` | Get the query string variable used to store the cursor. -`$paginator->items()` | Get the items for the current page. -`$paginator->nextCursor()` | Get the cursor instance for the next set of items. -`$paginator->nextPageUrl()` | Get the URL for the next page. -`$paginator->onFirstPage()` | Determine if the paginator is on the first page. -`$paginator->perPage()` | The number of items to be shown per page. -`$paginator->previousCursor()` | Get the cursor instance for the previous set of items. -`$paginator->previousPageUrl()` | Get the URL for the previous page. -`$paginator->setCursorName()` | Set the query string variable used to store the cursor. -`$paginator->url(https://github.com/$cursor)` | Get the URL for a given cursor instance. +
+ +| Method | Description | +| ------------------------------- | ----------------------------------------------------------------- | +| `$paginator->count()` | Get the number of items for the current page. | +| `$paginator->cursor()` | Get the current cursor instance. | +| `$paginator->getOptions()` | Get the paginator options. | +| `$paginator->hasPages()` | Determine if there are enough items to split into multiple pages. | +| `$paginator->hasMorePages()` | Determine if there are more items in the data store. | +| `$paginator->getCursorName()` | Get the query string variable used to store the cursor. | +| `$paginator->items()` | Get the items for the current page. | +| `$paginator->nextCursor()` | Get the cursor instance for the next set of items. | +| `$paginator->nextPageUrl()` | Get the URL for the next page. | +| `$paginator->onFirstPage()` | Determine if the paginator is on the first page. | +| `$paginator->onLastPage()` | Determine if the paginator is on the last page. | +| `$paginator->perPage()` | The number of items to be shown per page. | +| `$paginator->previousCursor()` | Get the cursor instance for the previous set of items. | +| `$paginator->previousPageUrl()` | Get the URL for the previous page. | +| `$paginator->setCursorName()` | Set the query string variable used to store the cursor. | +| `$paginator->url(https://github.com/$cursor)` | Get the URL for a given cursor instance. | + +
diff --git a/passport.md b/passport.md index aaa7c86ca6e..86714eabe6f 100644 --- a/passport.md +++ b/passport.md @@ -1,45 +1,49 @@ # Laravel Passport - [Introduction](#introduction) - - [Passport Or Sanctum?](#passport-or-sanctum) + - [Passport or Sanctum?](#passport-or-sanctum) - [Installation](#installation) - [Deploying Passport](#deploying-passport) - - [Migration Customization](#migration-customization) - [Upgrading Passport](#upgrading-passport) - [Configuration](#configuration) - - [Client Secret Hashing](#client-secret-hashing) - [Token Lifetimes](#token-lifetimes) - [Overriding Default Models](#overriding-default-models) -- [Issuing Access Tokens](#issuing-access-tokens) + - [Overriding Routes](#overriding-routes) +- [Authorization Code Grant](#authorization-code-grant) - [Managing Clients](#managing-clients) - [Requesting Tokens](#requesting-tokens) + - [Managing Tokens](#managing-tokens) - [Refreshing Tokens](#refreshing-tokens) - [Revoking Tokens](#revoking-tokens) - [Purging Tokens](#purging-tokens) -- [Authorization Code Grant with PKCE](#code-grant-pkce) - - [Creating The Client](#creating-a-auth-pkce-grant-client) +- [Authorization Code Grant With PKCE](#code-grant-pkce) + - [Creating the Client](#creating-a-auth-pkce-grant-client) - [Requesting Tokens](#requesting-auth-pkce-grant-tokens) -- [Password Grant Tokens](#password-grant-tokens) - - [Creating A Password Grant Client](#creating-a-password-grant-client) +- [Device Authorization Grant](#device-authorization-grant) + - [Creating a Device Code Grant Client](#creating-a-device-authorization-grant-client) + - [Requesting Tokens](#requesting-device-authorization-grant-tokens) +- [Password Grant](#password-grant) + - [Creating a Password Grant Client](#creating-a-password-grant-client) - [Requesting Tokens](#requesting-password-grant-tokens) - [Requesting All Scopes](#requesting-all-scopes) - - [Customizing The User Provider](#customizing-the-user-provider) - - [Customizing The Username Field](#customizing-the-username-field) - - [Customizing The Password Validation](#customizing-the-password-validation) -- [Implicit Grant Tokens](#implicit-grant-tokens) -- [Client Credentials Grant Tokens](#client-credentials-grant-tokens) + - [Customizing the User Provider](#customizing-the-user-provider) + - [Customizing the Username Field](#customizing-the-username-field) + - [Customizing the Password Validation](#customizing-the-password-validation) +- [Implicit Grant](#implicit-grant) +- [Client Credentials Grant](#client-credentials-grant) - [Personal Access Tokens](#personal-access-tokens) - - [Creating A Personal Access Client](#creating-a-personal-access-client) + - [Creating a Personal Access Client](#creating-a-personal-access-client) + - [Customizing the User Provider](#customizing-the-user-provider-for-pat) - [Managing Personal Access Tokens](#managing-personal-access-tokens) - [Protecting Routes](#protecting-routes) - [Via Middleware](#via-middleware) - - [Passing The Access Token](#passing-the-access-token) + - [Passing the Access Token](#passing-the-access-token) - [Token Scopes](#token-scopes) - [Defining Scopes](#defining-scopes) - [Default Scope](#default-scope) - - [Assigning Scopes To Tokens](#assigning-scopes-to-tokens) + - [Assigning Scopes to Tokens](#assigning-scopes-to-tokens) - [Checking Scopes](#checking-scopes) -- [Consuming Your API With JavaScript](#consuming-your-api-with-javascript) +- [SPA Authentication](#spa-authentication) - [Events](#events) - [Testing](#testing) @@ -48,10 +52,11 @@ [Laravel Passport](https://github.com/laravel/passport) provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the [League OAuth2 server](https://github.com/thephpleague/oauth2-server) that is maintained by Andy Millington and Simon Hamp. -> {note} This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general [terminology](https://oauth2.thephpleague.com/terminology/) and features of OAuth2 before continuing. +> [!NOTE] +> This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general [terminology](https://oauth2.thephpleague.com/terminology/) and features of OAuth2 before continuing. -### Passport Or Sanctum? +### Passport or Sanctum? Before getting started, you may wish to determine if your application would be better served by Laravel Passport or [Laravel Sanctum](/docs/{{version}}/sanctum). If your application absolutely needs to support OAuth2, then you should use Laravel Passport. @@ -60,99 +65,47 @@ However, if you are attempting to authenticate a single-page application, mobile ## Installation -To get started, install Passport via the Composer package manager: +You may install Laravel Passport via the `install:api` Artisan command: ```shell -composer require laravel/passport +php artisan install:api --passport ``` -Passport's [service provider](/docs/{{version}}/providers) registers its own database migration directory, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store OAuth2 clients and access tokens: +This command will publish and run the database migrations necessary for creating the tables your application needs to store OAuth2 clients and access tokens. The command will also create the encryption keys required to generate secure access tokens. -```shell -php artisan migrate -``` - -Next, you should execute the `passport:install` Artisan command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens: - -```shell -php artisan passport:install -``` +After running the `install:api` command, add the `Laravel\Passport\HasApiTokens` trait and `Laravel\Passport\Contracts\OAuthenticatable` interface to your `App\Models\User` model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes: -> {tip} If you would like to use UUIDs as the primary key value of the Passport `Client` model instead of auto-incrementing integers, please install Passport using [the `uuids` option](#client-uuids). +```php + 'App\Policies\ModelPolicy', - ]; - - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - if (! $this->app->routesAreCached()) { - Passport::routes(); - } - } - } - -Finally, in your application's `config/auth.php` configuration file, you should set the `driver` option of the `api` authentication guard to `passport`. This will instruct your application to use Passport's `TokenGuard` when authenticating incoming API requests: +class User extends Authenticatable implements OAuthenticatable +{ + use HasApiTokens, HasFactory, Notifiable; +} +``` - 'guards' => [ - 'web' => [ - 'driver' => 'session', - 'provider' => 'users', - ], +Finally, in your application's `config/auth.php` configuration file, you should define an `api` authentication guard and set the `driver` option to `passport`. This will instruct your application to use Passport's `TokenGuard` when authenticating incoming API requests: - 'api' => [ - 'driver' => 'passport', - 'provider' => 'users', - ], +```php +'guards' => [ + 'web' => [ + 'driver' => 'session', + 'provider' => 'users', ], - -#### Client UUIDs - -You may also run the `passport:install` command with the `--uuids` option present. This option will instruct Passport that you would like to use UUIDs instead of auto-incrementing integers as the Passport `Client` model's primary key values. After running the `passport:install` command with the `--uuids` option, you will be given additional instructions regarding disabling Passport's default migrations: - -```shell -php artisan passport:install --uuids + 'api' => [ + 'driver' => 'passport', + 'provider' => 'users', + ], +], ``` @@ -164,24 +117,20 @@ When deploying Passport to your application's servers for the first time, you wi php artisan passport:keys ``` -If necessary, you may define the path where Passport's keys should be loaded from. You may use the `Passport::loadKeysFrom` method to accomplish this. Typically, this method should be called from the `boot` method of your application's `App\Providers\AuthServiceProvider` class: +If necessary, you may define the path where Passport's keys should be loaded from. You may use the `Passport::loadKeysFrom` method to accomplish this. Typically, this method should be called from the `boot` method of your application's `App\Providers\AppServiceProvider` class: - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - Passport::routes(); - - Passport::loadKeysFrom(__DIR__.'/../secrets/oauth'); - } +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Passport::loadKeysFrom(__DIR__.'/../secrets/oauth'); +} +``` -#### Loading Keys From The Environment +#### Loading Keys From the Environment Alternatively, you may publish Passport's configuration file using the `vendor:publish` Artisan command: @@ -201,15 +150,6 @@ PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY----- -----END PUBLIC KEY-----" ``` - -### Migration Customization - -If you are not going to use Passport's default migrations, you should call the `Passport::ignoreMigrations` method in the `register` method of your `App\Providers\AppServiceProvider` class. You may export the default migrations using the `vendor:publish` Artisan command: - -```shell -php artisan vendor:publish --tag=passport-migrations -``` - ### Upgrading Passport @@ -218,292 +158,306 @@ When upgrading to a new major version of Passport, it's important that you caref ## Configuration - -### Client Secret Hashing - -If you would like your client's secrets to be hashed when stored in your database, you should call the `Passport::hashClientSecrets` method in the `boot` method of your `App\Providers\AuthServiceProvider` class: - - use Laravel\Passport\Passport; - - Passport::hashClientSecrets(); - -Once enabled, all of your client secrets will only be displayable to the user immediately after they are created. Since the plain-text client secret value is never stored in the database, it is not possible to recover the secret's value if it is lost. - ### Token Lifetimes -By default, Passport issues long-lived access tokens that expire after one year. If you would like to configure a longer / shorter token lifetime, you may use the `tokensExpireIn`, `refreshTokensExpireIn`, and `personalAccessTokensExpireIn` methods. These methods should be called from the `boot` method of your application's `App\Providers\AuthServiceProvider` class: +By default, Passport issues long-lived access tokens that expire after one year. If you would like to configure a longer / shorter token lifetime, you may use the `tokensExpireIn`, `refreshTokensExpireIn`, and `personalAccessTokensExpireIn` methods. These methods should be called from the `boot` method of your application's `App\Providers\AppServiceProvider` class: - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - Passport::routes(); +```php +use Carbon\CarbonInterval; - Passport::tokensExpireIn(now()->addDays(15)); - Passport::refreshTokensExpireIn(now()->addDays(30)); - Passport::personalAccessTokensExpireIn(now()->addMonths(6)); - } +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Passport::tokensExpireIn(CarbonInterval::days(15)); + Passport::refreshTokensExpireIn(CarbonInterval::days(30)); + Passport::personalAccessTokensExpireIn(CarbonInterval::months(6)); +} +``` -> {note} The `expires_at` columns on Passport's database tables are read-only and for display purposes only. When issuing tokens, Passport stores the expiration information within the signed and encrypted tokens. If you need to invalidate a token you should [revoke it](#revoking-tokens). +> [!WARNING] +> The `expires_at` columns on Passport's database tables are read-only and for display purposes only. When issuing tokens, Passport stores the expiration information within the signed and encrypted tokens. If you need to invalidate a token you should [revoke it](#revoking-tokens). ### Overriding Default Models You are free to extend the models used internally by Passport by defining your own model and extending the corresponding Passport model: - use Laravel\Passport\Client as PassportClient; +```php +use Laravel\Passport\Client as PassportClient; - class Client extends PassportClient - { - // ... - } +class Client extends PassportClient +{ + // ... +} +``` -After defining your model, you may instruct Passport to use your custom model via the `Laravel\Passport\Passport` class. Typically, you should inform Passport about your custom models in the `boot` method of your application's `App\Providers\AuthServiceProvider` class: +After defining your model, you may instruct Passport to use your custom model via the `Laravel\Passport\Passport` class. Typically, you should inform Passport about your custom models in the `boot` method of your application's `App\Providers\AppServiceProvider` class: + +```php +use App\Models\Passport\AuthCode; +use App\Models\Passport\Client; +use App\Models\Passport\DeviceCode; +use App\Models\Passport\RefreshToken; +use App\Models\Passport\Token; +use Laravel\Passport\Passport; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Passport::useTokenModel(Token::class); + Passport::useRefreshTokenModel(RefreshToken::class); + Passport::useAuthCodeModel(AuthCode::class); + Passport::useClientModel(Client::class); + Passport::useDeviceCodeModel(DeviceCode::class); +} +``` - use App\Models\Passport\AuthCode; - use App\Models\Passport\Client; - use App\Models\Passport\PersonalAccessClient; - use App\Models\Passport\Token; + +### Overriding Routes - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); +Sometimes you may wish to customize the routes defined by Passport. To achieve this, you first need to ignore the routes registered by Passport by adding `Passport::ignoreRoutes` to the `register` method of your application's `AppServiceProvider`: - Passport::routes(); +```php +use Laravel\Passport\Passport; - Passport::useTokenModel(Token::class); - Passport::useClientModel(Client::class); - Passport::useAuthCodeModel(AuthCode::class); - Passport::usePersonalAccessClientModel(PersonalAccessClient::class); - } +/** + * Register any application services. + */ +public function register(): void +{ + Passport::ignoreRoutes(); +} +``` + +Then, you may copy the routes defined by Passport in [its routes file](https://github.com/laravel/passport/blob/master/routes/web.php) to your application's `routes/web.php` file and modify them to your liking: + +```php +Route::group([ + 'as' => 'passport.', + 'prefix' => config('passport.path', 'oauth'), + 'namespace' => '\Laravel\Passport\Http\Controllers', +], function () { + // Passport routes... +}); +``` - -## Issuing Access Tokens + +## Authorization Code Grant Using OAuth2 via authorization codes is how most developers are familiar with OAuth2. When using authorization codes, a client application will redirect a user to your server where they will either approve or deny the request to issue an access token to the client. +To get started, we need to instruct Passport how to return our "authorization" view. + +All the authorization view's rendering logic may be customized using the appropriate methods available via the `Laravel\Passport\Passport` class. Typically, you should call this method from the `boot` method of your application's `App\Providers\AppServiceProvider` class: + +```php +use Inertia\Inertia; +use Laravel\Passport\Passport; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + // By providing a view name... + Passport::authorizationView('auth.oauth.authorize'); + + // By providing a closure... + Passport::authorizationView( + fn ($parameters) => Inertia::render('Auth/OAuth/Authorize', [ + 'request' => $parameters['request'], + 'authToken' => $parameters['authToken'], + 'client' => $parameters['client'], + 'user' => $parameters['user'], + 'scopes' => $parameters['scopes'], + ]) + ); +} +``` + +Passport will automatically define the `/oauth/authorize` route that returns this view. Your `auth.oauth.authorize` template should include a form that makes a POST request to the `passport.authorizations.approve` route to approve the authorization and a form that makes a DELETE request to the `passport.authorizations.deny` route to deny the authorization. The `passport.authorizations.approve` and `passport.authorizations.deny` routes expect `state`, `client_id`, and `auth_token` fields. + ### Managing Clients -First, developers building applications that need to interact with your application's API will need to register their application with yours by creating a "client". Typically, this consists of providing the name of their application and a URL that your application can redirect to after users approve their request for authorization. +Developers building applications that need to interact with your application's API will need to register their application with yours by creating a "client". Typically, this consists of providing the name of their application and a URI that your application can redirect to after users approve their request for authorization. - -#### The `passport:client` Command + +#### First-Party Clients -The simplest way to create a client is using the `passport:client` Artisan command. This command may be used to create your own clients for testing your OAuth2 functionality. When you run the `client` command, Passport will prompt you for more information about your client and will provide you with a client ID and secret: +The simplest way to create a client is using the `passport:client` Artisan command. This command may be used to create first-party clients or testing your OAuth2 functionality. When you run the `passport:client` command, Passport will prompt you for more information about your client and will provide you with a client ID and secret: ```shell php artisan passport:client ``` -**Redirect URLs** - -If you would like to allow multiple redirect URLs for your client, you may specify them using a comma-delimited list when prompted for the URL by the `passport:client` command. Any URLs which contain commas should be URL encoded: +If you would like to allow multiple redirect URIs for your client, you may specify them using a comma-delimited list when prompted for the URI by the `passport:client` command. Any URIs which contain commas should be URI encoded: ```shell -http://example.com/callback,http://examplefoo.com/callback +https://third-party-app.com/callback,https://example.com/oauth/redirect ``` - -#### JSON API - -Since your application's users will not be able to utilize the `client` command, Passport provides a JSON API that you may use to create clients. This saves you the trouble of having to manually code controllers for creating, updating, and deleting clients. - -However, you will need to pair Passport's JSON API with your own frontend to provide a dashboard for your users to manage their clients. Below, we'll review all of the API endpoints for managing clients. For convenience, we'll use [Axios](https://github.com/axios/axios) to demonstrate making HTTP requests to the endpoints. - -The JSON API is guarded by the `web` and `auth` middleware; therefore, it may only be called from your own application. It is not able to be called from an external source. - - -#### `GET /oauth/clients` - -This route returns all of the clients for the authenticated user. This is primarily useful for listing all of the user's clients so that they may edit or delete them: - -```js -axios.get('/oauth/clients') - .then(response => { - console.log(response.data); - }); -``` - - -#### `POST /oauth/clients` - -This route is used to create new clients. It requires two pieces of data: the client's `name` and a `redirect` URL. The `redirect` URL is where the user will be redirected after approving or denying a request for authorization. + +#### Third-Party Clients -When a client is created, it will be issued a client ID and client secret. These values will be used when requesting access tokens from your application. The client creation route will return the new client instance: +Since your application's users will not be able to utilize the `passport:client` command, you may use `createAuthorizationCodeGrantClient` method of the `Laravel\Passport\ClientRepository` class to register a client for a given user: -```js -const data = { - name: 'Client Name', - redirect: 'http://example.com/callback' -}; - -axios.post('/oauth/clients', data) - .then(response => { - console.log(response.data); - }) - .catch (response => { - // List errors on response... - }); -``` +```php +use App\Models\User; +use Laravel\Passport\ClientRepository; - -#### `PUT /oauth/clients/{client-id}` +$user = User::find($userId); -This route is used to update clients. It requires two pieces of data: the client's `name` and a `redirect` URL. The `redirect` URL is where the user will be redirected after approving or denying a request for authorization. The route will return the updated client instance: +// Creating an OAuth app client that belongs to the given user... +$client = app(ClientRepository::class)->createAuthorizationCodeGrantClient( + user: $user, + name: 'Example App', + redirectUris: ['https://third-party-app.com/callback'], + confidential: false, + enableDeviceFlow: true +); -```js -const data = { - name: 'New Client Name', - redirect: 'http://example.com/callback' -}; - -axios.put('/oauth/clients/' + clientId, data) - .then(response => { - console.log(response.data); - }) - .catch (response => { - // List errors on response... - }); +// Retrieving all the OAuth app clients that belong to the user... +$clients = $user->oauthApps()->get(); ``` - -#### `DELETE /oauth/clients/{client-id}` - -This route is used to delete clients: - -```js -axios.delete('/oauth/clients/' + clientId) - .then(response => { - // - }); -``` +The `createAuthorizationCodeGrantClient` method returns an instance of `Laravel\Passport\Client`. You may display the `$client->id` as the client ID and `$client->plainSecret` as the client secret to the user. ### Requesting Tokens -#### Redirecting For Authorization +#### Redirecting for Authorization Once a client has been created, developers may use their client ID and secret to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's `/oauth/authorize` route like so: - use Illuminate\Http\Request; - use Illuminate\Support\Str; +```php +use Illuminate\Http\Request; +use Illuminate\Support\Str; - Route::get('/redirect', function (Request $request) { - $request->session()->put('state', $state = Str::random(40)); +Route::get('/redirect', function (Request $request) { + $request->session()->put('state', $state = Str::random(40)); - $query = http_build_query([ - 'client_id' => 'client-id', - 'redirect_uri' => 'http://third-party-app.com/callback', - 'response_type' => 'code', - 'scope' => '', - 'state' => $state, - ]); + $query = http_build_query([ + 'client_id' => 'your-client-id', + 'redirect_uri' => 'https://third-party-app.com/callback', + 'response_type' => 'code', + 'scope' => 'user:read orders:create', + 'state' => $state, + // 'prompt' => '', // "none", "consent", or "login" + ]); - return redirect('http://passport-app.test/oauth/authorize?'.$query); - }); + return redirect('https://passport-app.test/oauth/authorize?'.$query); +}); +``` -> {tip} Remember, the `/oauth/authorize` route is already defined by the `Passport::routes` method. You do not need to manually define this route. +The `prompt` parameter may be used to specify the authentication behavior of the Passport application. - -#### Approving The Request +If the `prompt` value is `none`, Passport will always throw an authentication error if the user is not already authenticated with the Passport application. If the value is `consent`, Passport will always display the authorization approval screen, even if all scopes were previously granted to the consuming application. When the value is `login`, the Passport application will always prompt the user to re-login to the application, even if they already have an existing session. -When receiving authorization requests, Passport will automatically display a template to the user allowing them to approve or deny the authorization request. If they approve the request, they will be redirected back to the `redirect_uri` that was specified by the consuming application. The `redirect_uri` must match the `redirect` URL that was specified when the client was created. +If no `prompt` value is provided, the user will be prompted for authorization only if they have not previously authorized access to the consuming application for the requested scopes. -If you would like to customize the authorization approval screen, you may publish Passport's views using the `vendor:publish` Artisan command. The published views will be placed in the `resources/views/vendor/passport` directory: +> [!NOTE] +> Remember, the `/oauth/authorize` route is already defined by Passport. You do not need to manually define this route. -```shell -php artisan vendor:publish --tag=passport-views -``` + +#### Approving the Request -Sometimes you may wish to skip the authorization prompt, such as when authorizing a first-party client. You may accomplish this by [extending the `Client` model](#overriding-default-models) and defining a `skipsAuthorization` method. If `skipsAuthorization` returns `true` the client will be approved and the user will be redirected back to the `redirect_uri` immediately: +When receiving authorization requests, Passport will automatically respond based on the value of `prompt` parameter (if present) and may display a template to the user allowing them to approve or deny the authorization request. If they approve the request, they will be redirected back to the `redirect_uri` that was specified by the consuming application. The `redirect_uri` must match the `redirect` URL that was specified when the client was created. - firstParty(); - } + return $this->firstParty(); } +} +``` -#### Converting Authorization Codes To Access Tokens +#### Converting Authorization Codes to Access Tokens If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should first verify the `state` parameter against the value that was stored prior to the redirect. If the state parameter matches then the consumer should issue a `POST` request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request: - use Illuminate\Http\Request; - use Illuminate\Support\Facades\Http; - - Route::get('/callback', function (Request $request) { - $state = $request->session()->pull('state'); - - throw_unless( - strlen($state) > 0 && $state === $request->state, - InvalidArgumentException::class - ); - - $response = Http::asForm()->post('http://passport-app.test/oauth/token', [ - 'grant_type' => 'authorization_code', - 'client_id' => 'client-id', - 'client_secret' => 'client-secret', - 'redirect_uri' => 'http://third-party-app.com/callback', - 'code' => $request->code, - ]); - - return $response->json(); - }); - -This `/oauth/token` route will return a JSON response containing `access_token`, `refresh_token`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the access token expires. - -> {tip} Like the `/oauth/authorize` route, the `/oauth/token` route is defined for you by the `Passport::routes` method. There is no need to manually define this route. - - -#### JSON API - -Passport also includes a JSON API for managing authorized access tokens. You may pair this with your own frontend to offer your users a dashboard for managing access tokens. For convenience, we'll use [Axios](https://github.com/mzabriskie/axios) to demonstrate making HTTP requests to the endpoints. The JSON API is guarded by the `web` and `auth` middleware; therefore, it may only be called from your own application. - - -#### `GET /oauth/tokens` - -This route returns all of the authorized access tokens that the authenticated user has created. This is primarily useful for listing all of the user's tokens so that they can revoke them: +```php +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Http; + +Route::get('/callback', function (Request $request) { + $state = $request->session()->pull('state'); + + throw_unless( + strlen($state) > 0 && $state === $request->state, + InvalidArgumentException::class, + 'Invalid state value.' + ); + + $response = Http::asForm()->post('https://passport-app.test/oauth/token', [ + 'grant_type' => 'authorization_code', + 'client_id' => 'your-client-id', + 'client_secret' => 'your-client-secret', + 'redirect_uri' => 'https://third-party-app.com/callback', + 'code' => $request->code, + ]); -```js -axios.get('/oauth/tokens') - .then(response => { - console.log(response.data); - }); + return $response->json(); +}); ``` - -#### `DELETE /oauth/tokens/{token-id}` - -This route may be used to revoke authorized access tokens and their related refresh tokens: +This `/oauth/token` route will return a JSON response containing `access_token`, `refresh_token`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the access token expires. -```js -axios.delete('/oauth/tokens/' + tokenId); +> [!NOTE] +> Like the `/oauth/authorize` route, the `/oauth/token` route is defined for you by Passport. There is no need to manually define this route. + + +### Managing Tokens + +You may retrieve user's authorized tokens using the `tokens` method of the `Laravel\Passport\HasApiTokens` trait. For example, this may be used to offer your users a dashboard to keep track of their connections with third-party applications: + +```php +use App\Models\User; +use Illuminate\Database\Eloquent\Collection; +use Illuminate\Support\Facades\Date; +use Laravel\Passport\Token; + +$user = User::find($userId); + +// Retrieving all of the valid tokens for the user... +$tokens = $user->tokens() + ->where('revoked', false) + ->where('expires_at', '>', Date::now()) + ->get(); + +// Retrieving all the user's connections to third-party OAuth app clients... +$connections = $tokens->load('client') + ->reject(fn (Token $token) => $token->client->firstParty()) + ->groupBy('client_id') + ->map(fn (Collection $tokens) => [ + 'client' => $tokens->first()->client, + 'scopes' => $tokens->pluck('scopes')->flatten()->unique()->values()->all(), + 'tokens_count' => $tokens->count(), + ]) + ->values(); ``` @@ -511,36 +465,45 @@ axios.delete('/oauth/tokens/' + tokenId); If your application issues short-lived access tokens, users will need to refresh their access tokens via the refresh token that was provided to them when the access token was issued: - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Support\Facades\Http; - $response = Http::asForm()->post('http://passport-app.test/oauth/token', [ - 'grant_type' => 'refresh_token', - 'refresh_token' => 'the-refresh-token', - 'client_id' => 'client-id', - 'client_secret' => 'client-secret', - 'scope' => '', - ]); +$response = Http::asForm()->post('https://passport-app.test/oauth/token', [ + 'grant_type' => 'refresh_token', + 'refresh_token' => 'the-refresh-token', + 'client_id' => 'your-client-id', + 'client_secret' => 'your-client-secret', // Required for confidential clients only... + 'scope' => 'user:read orders:create', +]); - return $response->json(); +return $response->json(); +``` This `/oauth/token` route will return a JSON response containing `access_token`, `refresh_token`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the access token expires. ### Revoking Tokens -You may revoke a token by using the `revokeAccessToken` method on the `Laravel\Passport\TokenRepository`. You may revoke a token's refresh tokens using the `revokeRefreshTokensByAccessTokenId` method on the `Laravel\Passport\RefreshTokenRepository`. These classes may be resolved using Laravel's [service container](/docs/{{version}}/container): +You may revoke a token by using the `revoke` method on the `Laravel\Passport\Token` model. You may revoke a token's refresh token using the `revoke` method on the `Laravel\Passport\RefreshToken` model: - use Laravel\Passport\TokenRepository; - use Laravel\Passport\RefreshTokenRepository; +```php +use Laravel\Passport\Passport; +use Laravel\Passport\Token; - $tokenRepository = app(TokenRepository::class); - $refreshTokenRepository = app(RefreshTokenRepository::class); +$token = Passport::token()->find($tokenId); - // Revoke an access token... - $tokenRepository->revokeAccessToken($tokenId); +// Revoke an access token... +$token->revoke(); - // Revoke all of the token's refresh tokens... - $refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId); +// Revoke the token's refresh token... +$token->refreshToken?->revoke(); + +// Revoke all of the user's tokens... +User::find($userId)->tokens()->each(function (Token $token) { + $token->revoke(); + $token->refreshToken?->revoke(); +}); +``` ### Purging Tokens @@ -548,36 +511,34 @@ You may revoke a token by using the `revokeAccessToken` method on the `Laravel\P When tokens have been revoked or expired, you might want to purge them from the database. Passport's included `passport:purge` Artisan command can do this for you: ```shell -# Purge revoked and expired tokens and auth codes... +# Purge revoked and expired tokens, auth codes, and device codes... php artisan passport:purge -# Only purge revoked tokens and auth codes... +# Only purge tokens expired for more than 6 hours... +php artisan passport:purge --hours=6 + +# Only purge revoked tokens, auth codes, and device codes... php artisan passport:purge --revoked -# Only purge expired tokens and auth codes... +# Only purge expired tokens, auth codes, and device codes... php artisan passport:purge --expired ``` -You may also configure a [scheduled job](/docs/{{version}}/scheduling) in your application's `App\Console\Kernel` class to automatically prune your tokens on a schedule: +You may also configure a [scheduled job](/docs/{{version}}/scheduling) in your application's `routes/console.php` file to automatically prune your tokens on a schedule: - /** - * Define the application's command schedule. - * - * @param \Illuminate\Console\Scheduling\Schedule $schedule - * @return void - */ - protected function schedule(Schedule $schedule) - { - $schedule->command('passport:purge')->hourly(); - } +```php +use Illuminate\Support\Facades\Schedule; + +Schedule::command('passport:purge')->hourly(); +``` -## Authorization Code Grant with PKCE +## Authorization Code Grant With PKCE -The Authorization Code grant with "Proof Key for Code Exchange" (PKCE) is a secure way to authenticate single page applications or native applications to access your API. This grant should be used when you can't guarantee that the client secret will be stored confidentially or in order to mitigate the threat of having the authorization code intercepted by an attacker. A combination of a "code verifier" and a "code challenge" replaces the client secret when exchanging the authorization code for an access token. +The Authorization Code grant with "Proof Key for Code Exchange" (PKCE) is a secure way to authenticate single page applications or mobile applications to access your API. This grant should be used when you can't guarantee that the client secret will be stored confidentially or in order to mitigate the threat of having the authorization code intercepted by an attacker. A combination of a "code verifier" and a "code challenge" replaces the client secret when exchanging the authorization code for an access token. -### Creating The Client +### Creating the Client Before your application can issue tokens via the authorization code grant with PKCE, you will need to create a PKCE-enabled client. You may do this using the `passport:client` Artisan command with the `--public` option: @@ -589,7 +550,7 @@ php artisan passport:client --public ### Requesting Tokens -#### Code Verifier & Code Challenge +#### Code Verifier and Code Challenge As this authorization grant does not provide a client secret, developers will need to generate a combination of a code verifier and a code challenge in order to request a token. @@ -597,84 +558,233 @@ The code verifier should be a random string of between 43 and 128 characters con The code challenge should be a Base64 encoded string with URL and filename-safe characters. The trailing `'='` characters should be removed and no line breaks, whitespace, or other additional characters should be present. - $encoded = base64_encode(hash('sha256', $code_verifier, true)); +```php +$encoded = base64_encode(hash('sha256', $codeVerifier, true)); - $codeChallenge = strtr(rtrim($encoded, '='), '+/', '-_'); +$codeChallenge = strtr(rtrim($encoded, '='), '+/', '-_'); +``` -#### Redirecting For Authorization +#### Redirecting for Authorization Once a client has been created, you may use the client ID and the generated code verifier and code challenge to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's `/oauth/authorize` route: - use Illuminate\Http\Request; - use Illuminate\Support\Str; +```php +use Illuminate\Http\Request; +use Illuminate\Support\Str; + +Route::get('/redirect', function (Request $request) { + $request->session()->put('state', $state = Str::random(40)); + + $request->session()->put( + 'code_verifier', $codeVerifier = Str::random(128) + ); + + $codeChallenge = strtr(rtrim( + base64_encode(hash('sha256', $codeVerifier, true)) + , '='), '+/', '-_'); + + $query = http_build_query([ + 'client_id' => 'your-client-id', + 'redirect_uri' => 'https://third-party-app.com/callback', + 'response_type' => 'code', + 'scope' => 'user:read orders:create', + 'state' => $state, + 'code_challenge' => $codeChallenge, + 'code_challenge_method' => 'S256', + // 'prompt' => '', // "none", "consent", or "login" + ]); - Route::get('/redirect', function (Request $request) { - $request->session()->put('state', $state = Str::random(40)); + return redirect('https://passport-app.test/oauth/authorize?'.$query); +}); +``` - $request->session()->put( - 'code_verifier', $code_verifier = Str::random(128) - ); + +#### Converting Authorization Codes to Access Tokens - $codeChallenge = strtr(rtrim( - base64_encode(hash('sha256', $code_verifier, true)) - , '='), '+/', '-_'); +If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should verify the `state` parameter against the value that was stored prior to the redirect, as in the standard Authorization Code Grant. - $query = http_build_query([ - 'client_id' => 'client-id', - 'redirect_uri' => 'http://third-party-app.com/callback', - 'response_type' => 'code', - 'scope' => '', - 'state' => $state, - 'code_challenge' => $codeChallenge, - 'code_challenge_method' => 'S256', - ]); +If the state parameter matches, the consumer should issue a `POST` request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request along with the originally generated code verifier: - return redirect('http://passport-app.test/oauth/authorize?'.$query); - }); +```php +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Http; - -#### Converting Authorization Codes To Access Tokens +Route::get('/callback', function (Request $request) { + $state = $request->session()->pull('state'); -If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should verify the `state` parameter against the value that was stored prior to the redirect, as in the standard Authorization Code Grant. + $codeVerifier = $request->session()->pull('code_verifier'); -If the state parameter matches, the consumer should issue a `POST` request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request along with the originally generated code verifier: + throw_unless( + strlen($state) > 0 && $state === $request->state, + InvalidArgumentException::class + ); - use Illuminate\Http\Request; - use Illuminate\Support\Facades\Http; + $response = Http::asForm()->post('https://passport-app.test/oauth/token', [ + 'grant_type' => 'authorization_code', + 'client_id' => 'your-client-id', + 'redirect_uri' => 'https://third-party-app.com/callback', + 'code_verifier' => $codeVerifier, + 'code' => $request->code, + ]); - Route::get('/callback', function (Request $request) { - $state = $request->session()->pull('state'); + return $response->json(); +}); +``` - $codeVerifier = $request->session()->pull('code_verifier'); + +## Device Authorization Grant + +The OAuth2 device authorization grant allows browserless or limited input devices, such as TVs and game consoles, to obtain an access token by exchanging a "device code". When using device flow, the device client will instruct the user to use a secondary device, such as a computer or a smartphone and connect to your server where they will enter the provided "user code" and either approve or deny the access request. + +To get started, we need to instruct Passport how to return our "user code" and "authorization" views. + +All the authorization view's rendering logic may be customized using the appropriate methods available via the `Laravel\Passport\Passport` class. Typically, you should call this method from the `boot` method of your application's `App\Providers\AppServiceProvider` class. + +```php +use Inertia\Inertia; +use Laravel\Passport\Passport; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + // By providing a view name... + Passport::deviceUserCodeView('auth.oauth.device.user-code'); + Passport::deviceAuthorizationView('auth.oauth.device.authorize'); + + // By providing a closure... + Passport::deviceUserCodeView( + fn ($parameters) => Inertia::render('Auth/OAuth/Device/UserCode') + ); + + Passport::deviceAuthorizationView( + fn ($parameters) => Inertia::render('Auth/OAuth/Device/Authorize', [ + 'request' => $parameters['request'], + 'authToken' => $parameters['authToken'], + 'client' => $parameters['client'], + 'user' => $parameters['user'], + 'scopes' => $parameters['scopes'], + ]) + ); + + // ... +} +``` - throw_unless( - strlen($state) > 0 && $state === $request->state, - InvalidArgumentException::class - ); +Passport will automatically define routes that return these views. Your `auth.oauth.device.user-code` template should include a form that makes a GET request to the `passport.device.authorizations.authorize` route. The `passport.device.authorizations.authorize` route expects a `user_code` query parameter. - $response = Http::asForm()->post('http://passport-app.test/oauth/token', [ - 'grant_type' => 'authorization_code', - 'client_id' => 'client-id', - 'redirect_uri' => 'http://third-party-app.com/callback', - 'code_verifier' => $codeVerifier, - 'code' => $request->code, - ]); +Your `auth.oauth.device.authorize` template should include a form that makes a POST request to the `passport.device.authorizations.approve` route to approve the authorization and a form that makes a DELETE request to the `passport.device.authorizations.deny` route to deny the authorization. The `passport.device.authorizations.approve` and `passport.device.authorizations.deny` routes expect `state`, `client_id`, and `auth_token` fields. - return $response->json(); - }); + +### Creating a Device Authorization Grant Client + +Before your application can issue tokens via the device authorization grant, you will need to create a device flow enabled client. You may do this using the `passport:client` Artisan command with the `--device` option. This command will create a first-party device flow enabled client and provide you with a client ID and secret: + +```shell +php artisan passport:client --device +``` + +Additionally, you may use `createDeviceAuthorizationGrantClient` method on the `ClientRepository` class to register a third-party client that belongs to the given user: + +```php +use App\Models\User; +use Laravel\Passport\ClientRepository; - -## Password Grant Tokens +$user = User::find($userId); -> {note} We no longer recommend using password grant tokens. Instead, you should choose [a grant type that is currently recommended by OAuth2 Server](https://oauth2.thephpleague.com/authorization-server/which-grant/). +$client = app(ClientRepository::class)->createDeviceAuthorizationGrantClient( + user: $user, + name: 'Example Device', + confidential: false, +); +``` + + +### Requesting Tokens + + +#### Requesting a Device Code + +Once a client has been created, developers may use their client ID to request a device code from your application. First, the consuming device should make a `POST` request to your application's `/oauth/device/code` route to request a device code: + +```php +use Illuminate\Support\Facades\Http; + +$response = Http::asForm()->post('https://passport-app.test/oauth/device/code', [ + 'client_id' => 'your-client-id', + 'scope' => 'user:read orders:create', +]); + +return $response->json(); +``` + +This will return a JSON response containing `device_code`, `user_code`, `verification_uri`, `interval`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the device code expires. The `interval` attribute contains the number of seconds the consuming device should wait between requests when polling `/oauth/token` route to avoid rate limit errors. + +> [!NOTE] +> Remember, the `/oauth/device/code` route is already defined by Passport. You do not need to manually define this route. + + +#### Displaying the Verification URI and User Code + +Once a device code request has been obtained, the consuming device should instruct the user to use another device and visit the provided `verification_uri` and enter the `user_code` in order to approve the authorization request. + + +#### Polling Token Request + +Since the user will be using a separate device to grant (or deny) access, the consuming device should poll your application's `/oauth/token` route to determine when the user has responded to the request. The consuming device should use the minimum polling `interval` provided in the JSON response when requesting device code to avoid rate limit errors: + +```php +use Illuminate\Support\Facades\Http; +use Illuminate\Support\Sleep; + +$interval = 5; + +do { + Sleep::for($interval)->seconds(); + + $response = Http::asForm()->post('https://passport-app.test/oauth/token', [ + 'grant_type' => 'urn:ietf:params:oauth:grant-type:device_code', + 'client_id' => 'your-client-id', + 'client_secret' => 'your-client-secret', // Required for confidential clients only... + 'device_code' => 'the-device-code', + ]); + + if ($response->json('error') === 'slow_down') { + $interval += 5; + } +} while (in_array($response->json('error'), ['authorization_pending', 'slow_down'])); + +return $response->json(); +``` + +If the user has approved the authorization request, this will return a JSON response containing `access_token`, `refresh_token`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the access token expires. + + +## Password Grant + +> [!WARNING] +> We no longer recommend using password grant tokens. Instead, you should choose [a grant type that is currently recommended by OAuth2 Server](https://oauth2.thephpleague.com/authorization-server/which-grant/). The OAuth2 password grant allows your other first-party clients, such as a mobile application, to obtain an access token using an email address / username and password. This allows you to issue access tokens securely to your first-party clients without requiring your users to go through the entire OAuth2 authorization code redirect flow. +To enable the password grant, call the `enablePasswordGrant` method in the `boot` method of your application's `App\Providers\AppServiceProvider` class: + +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Passport::enablePasswordGrant(); +} +``` + -### Creating A Password Grant Client +### Creating a Password Grant Client -Before your application can issue tokens via the password grant, you will need to create a password grant client. You may do this using the `passport:client` Artisan command with the `--password` option. **If you have already run the `passport:install` command, you do not need to run this command:** +Before your application can issue tokens via the password grant, you will need to create a password grant client. You may do this using the `passport:client` Artisan command with the `--password` option. ```shell php artisan passport:client --password @@ -683,146 +793,158 @@ php artisan passport:client --password ### Requesting Tokens -Once you have created a password grant client, you may request an access token by issuing a `POST` request to the `/oauth/token` route with the user's email address and password. Remember, this route is already registered by the `Passport::routes` method so there is no need to define it manually. If the request is successful, you will receive an `access_token` and `refresh_token` in the JSON response from the server: +Once you have enabled the grant and have created a password grant client, you may request an access token by issuing a `POST` request to the `/oauth/token` route with the user's email address and password. Remember, this route is already registered by Passport so there is no need to define it manually. If the request is successful, you will receive an `access_token` and `refresh_token` in the JSON response from the server: - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Support\Facades\Http; - $response = Http::asForm()->post('http://passport-app.test/oauth/token', [ - 'grant_type' => 'password', - 'client_id' => 'client-id', - 'client_secret' => 'client-secret', - 'username' => 'taylor@laravel.com', - 'password' => 'my-password', - 'scope' => '', - ]); +$response = Http::asForm()->post('https://passport-app.test/oauth/token', [ + 'grant_type' => 'password', + 'client_id' => 'your-client-id', + 'client_secret' => 'your-client-secret', // Required for confidential clients only... + 'username' => 'taylor@laravel.com', + 'password' => 'my-password', + 'scope' => 'user:read orders:create', +]); - return $response->json(); +return $response->json(); +``` -> {tip} Remember, access tokens are long-lived by default. However, you are free to [configure your maximum access token lifetime](#configuration) if needed. +> [!NOTE] +> Remember, access tokens are long-lived by default. However, you are free to [configure your maximum access token lifetime](#configuration) if needed. ### Requesting All Scopes When using the password grant or client credentials grant, you may wish to authorize the token for all of the scopes supported by your application. You can do this by requesting the `*` scope. If you request the `*` scope, the `can` method on the token instance will always return `true`. This scope may only be assigned to a token that is issued using the `password` or `client_credentials` grant: - use Illuminate\Support\Facades\Http; - - $response = Http::asForm()->post('http://passport-app.test/oauth/token', [ - 'grant_type' => 'password', - 'client_id' => 'client-id', - 'client_secret' => 'client-secret', - 'username' => 'taylor@laravel.com', - 'password' => 'my-password', - 'scope' => '*', - ]); +```php +use Illuminate\Support\Facades\Http; + +$response = Http::asForm()->post('https://passport-app.test/oauth/token', [ + 'grant_type' => 'password', + 'client_id' => 'your-client-id', + 'client_secret' => 'your-client-secret', // Required for confidential clients only... + 'username' => 'taylor@laravel.com', + 'password' => 'my-password', + 'scope' => '*', +]); +``` -### Customizing The User Provider +### Customizing the User Provider -If your application uses more than one [authentication user provider](/docs/{{version}}/authentication#introduction), you may specify which user provider the password grant client uses by providing a `--provider` option when creating the client via the `artisan passport:client --password` command. The given provider name should match a valid provider defined in your application's `config/auth.php` configuration file. You can then [protect your route using middleware](#via-middleware) to ensure that only users from the guard's specified provider are authorized. +If your application uses more than one [authentication user provider](/docs/{{version}}/authentication#introduction), you may specify which user provider the password grant client uses by providing a `--provider` option when creating the client via the `artisan passport:client --password` command. The given provider name should match a valid provider defined in your application's `config/auth.php` configuration file. You can then [protect your route using middleware](#multiple-authentication-guards) to ensure that only users from the guard's specified provider are authorized. -### Customizing The Username Field +### Customizing the Username Field When authenticating using the password grant, Passport will use the `email` attribute of your authenticatable model as the "username". However, you may customize this behavior by defining a `findForPassport` method on your model: - where('username', $username)->first(); - } + return $this->where('username', $username)->first(); } +} +``` -### Customizing The Password Validation +### Customizing the Password Validation When authenticating using the password grant, Passport will use the `password` attribute of your model to validate the given password. If your model does not have a `password` attribute or you wish to customize the password validation logic, you can define a `validateForPassportPasswordGrant` method on your model: - password); - } + return Hash::check($password, $this->password); } +} +``` - -## Implicit Grant Tokens + +## Implicit Grant -> {note} We no longer recommend using implicit grant tokens. Instead, you should choose [a grant type that is currently recommended by OAuth2 Server](https://oauth2.thephpleague.com/authorization-server/which-grant/). +> [!WARNING] +> We no longer recommend using implicit grant tokens. Instead, you should choose [a grant type that is currently recommended by OAuth2 Server](https://oauth2.thephpleague.com/authorization-server/which-grant/). -The implicit grant is similar to the authorization code grant; however, the token is returned to the client without exchanging an authorization code. This grant is most commonly used for JavaScript or mobile applications where the client credentials can't be securely stored. To enable the grant, call the `enableImplicitGrant` method in the `boot` method of your application's `App\Providers\AuthServiceProvider` class: +The implicit grant is similar to the authorization code grant; however, the token is returned to the client without exchanging an authorization code. This grant is most commonly used for JavaScript or mobile applications where the client credentials can't be securely stored. To enable the grant, call the `enableImplicitGrant` method in the `boot` method of your application's `App\Providers\AppServiceProvider` class: - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Passport::enableImplicitGrant(); +} +``` - Passport::routes(); +Before your application can issue tokens via the implicit grant, you will need to create an implicit grant client. You may do this using the `passport:client` Artisan command with the `--implicit` option. - Passport::enableImplicitGrant(); - } +```shell +php artisan passport:client --implicit +``` -Once the grant has been enabled, developers may use their client ID to request an access token from your application. The consuming application should make a redirect request to your application's `/oauth/authorize` route like so: +Once the grant has been enabled and an implicit client has been created, developers may use their client ID to request an access token from your application. The consuming application should make a redirect request to your application's `/oauth/authorize` route like so: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/redirect', function (Request $request) { - $request->session()->put('state', $state = Str::random(40)); +Route::get('/redirect', function (Request $request) { + $request->session()->put('state', $state = Str::random(40)); - $query = http_build_query([ - 'client_id' => 'client-id', - 'redirect_uri' => 'http://third-party-app.com/callback', - 'response_type' => 'token', - 'scope' => '', - 'state' => $state, - ]); + $query = http_build_query([ + 'client_id' => 'your-client-id', + 'redirect_uri' => 'https://third-party-app.com/callback', + 'response_type' => 'token', + 'scope' => 'user:read orders:create', + 'state' => $state, + // 'prompt' => '', // "none", "consent", or "login" + ]); - return redirect('http://passport-app.test/oauth/authorize?'.$query); - }); + return redirect('https://passport-app.test/oauth/authorize?'.$query); +}); +``` -> {tip} Remember, the `/oauth/authorize` route is already defined by the `Passport::routes` method. You do not need to manually define this route. +> [!NOTE] +> Remember, the `/oauth/authorize` route is already defined by Passport. You do not need to manually define this route. - -## Client Credentials Grant Tokens + +## Client Credentials Grant The client credentials grant is suitable for machine-to-machine authentication. For example, you might use this grant in a scheduled job which is performing maintenance tasks over an API. @@ -832,51 +954,52 @@ Before your application can issue tokens via the client credentials grant, you w php artisan passport:client --client ``` -Next, to use this grant type, you need to add the `CheckClientCredentials` middleware to the `$routeMiddleware` property of your `app/Http/Kernel.php` file: - - use Laravel\Passport\Http\Middleware\CheckClientCredentials; +Next, assign the `Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner` middleware to a route: - protected $routeMiddleware = [ - 'client' => CheckClientCredentials::class, - ]; +```php +use Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner; -Then, attach the middleware to a route: - - Route::get('/orders', function (Request $request) { - ... - })->middleware('client'); +Route::get('/orders', function (Request $request) { + // Access token is valid and the client is resource owner... +})->middleware(EnsureClientIsResourceOwner::class); +``` -To restrict access to the route to specific scopes, you may provide a comma-delimited list of the required scopes when attaching the `client` middleware to the route: +To restrict access to the route to specific scopes, you may provide a list of the required scopes to the `using` method`: - Route::get('/orders', function (Request $request) { - ... - })->middleware('client:check-status,your-scope'); +```php +Route::get('/orders', function (Request $request) { + // Access token is valid, the client is resource owner, and has both "servers:read" and "servers:create" scopes... +})->middleware(EnsureClientIsResourceOwner::using('servers:read', 'servers:create')); +``` ### Retrieving Tokens To retrieve a token using this grant type, make a request to the `oauth/token` endpoint: - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Support\Facades\Http; - $response = Http::asForm()->post('http://passport-app.test/oauth/token', [ - 'grant_type' => 'client_credentials', - 'client_id' => 'client-id', - 'client_secret' => 'client-secret', - 'scope' => 'your-scope', - ]); +$response = Http::asForm()->post('https://passport-app.test/oauth/token', [ + 'grant_type' => 'client_credentials', + 'client_id' => 'your-client-id', + 'client_secret' => 'your-client-secret', + 'scope' => 'servers:read servers:create', +]); - return $response->json()['access_token']; +return $response->json()['access_token']; +``` ## Personal Access Tokens Sometimes, your users may want to issue access tokens to themselves without going through the typical authorization code redirect flow. Allowing users to issue tokens to themselves via your application's UI can be useful for allowing users to experiment with your API or may serve as a simpler approach to issuing access tokens in general. -> {tip} If your application is primarily using Passport to issue personal access tokens, consider using [Laravel Sanctum](/docs/{{version}}/sanctum), Laravel's light-weight first-party library for issuing API access tokens. +> [!NOTE] +> If your application is using Passport primarily to issue personal access tokens, consider using [Laravel Sanctum](/docs/{{version}}/sanctum), Laravel's light-weight first-party library for issuing API access tokens. -### Creating A Personal Access Client +### Creating a Personal Access Client Before your application can issue personal access tokens, you will need to create a personal access client. You may do this by executing the `passport:client` Artisan command with the `--personal` option. If you have already run the `passport:install` command, you do not need to run this command: @@ -884,86 +1007,39 @@ Before your application can issue personal access tokens, you will need to creat php artisan passport:client --personal ``` -After creating your personal access client, place the client's ID and plain-text secret value in your application's `.env` file: + +### Customizing the User Provider -```ini -PASSPORT_PERSONAL_ACCESS_CLIENT_ID="client-id-value" -PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET="unhashed-client-secret-value" -``` +If your application uses more than one [authentication user provider](/docs/{{version}}/authentication#introduction), you may specify which user provider the personal access grant client uses by providing a `--provider` option when creating the client via the `artisan passport:client --personal` command. The given provider name should match a valid provider defined in your application's `config/auth.php` configuration file. You can then [protect your route using middleware](#multiple-authentication-guards) to ensure that only users from the guard's specified provider are authorized. ### Managing Personal Access Tokens Once you have created a personal access client, you may issue tokens for a given user using the `createToken` method on the `App\Models\User` model instance. The `createToken` method accepts the name of the token as its first argument and an optional array of [scopes](#token-scopes) as its second argument: - use App\Models\User; - - $user = User::find(1); - - // Creating a token without scopes... - $token = $user->createToken('Token Name')->accessToken; - - // Creating a token with scopes... - $token = $user->createToken('My Token', ['place-orders'])->accessToken; - - -#### JSON API - -Passport also includes a JSON API for managing personal access tokens. You may pair this with your own frontend to offer your users a dashboard for managing personal access tokens. Below, we'll review all of the API endpoints for managing personal access tokens. For convenience, we'll use [Axios](https://github.com/mzabriskie/axios) to demonstrate making HTTP requests to the endpoints. - -The JSON API is guarded by the `web` and `auth` middleware; therefore, it may only be called from your own application. It is not able to be called from an external source. - - -#### `GET /oauth/scopes` - -This route returns all of the [scopes](#token-scopes) defined for your application. You may use this route to list the scopes a user may assign to a personal access token: - -```js -axios.get('/oauth/scopes') - .then(response => { - console.log(response.data); - }); -``` - - -#### `GET /oauth/personal-access-tokens` - -This route returns all of the personal access tokens that the authenticated user has created. This is primarily useful for listing all of the user's tokens so that they may edit or revoke them: - -```js -axios.get('/oauth/personal-access-tokens') - .then(response => { - console.log(response.data); - }); -``` - - -#### `POST /oauth/personal-access-tokens` +```php +use App\Models\User; +use Illuminate\Support\Facades\Date; +use Laravel\Passport\Token; -This route creates new personal access tokens. It requires two pieces of data: the token's `name` and the `scopes` that should be assigned to the token: +$user = User::find($userId); -```js -const data = { - name: 'Token Name', - scopes: [] -}; +// Creating a token without scopes... +$token = $user->createToken('My Token')->accessToken; -axios.post('/oauth/personal-access-tokens', data) - .then(response => { - console.log(response.data.accessToken); - }) - .catch (response => { - // List errors on response... - }); -``` +// Creating a token with scopes... +$token = $user->createToken('My Token', ['user:read', 'orders:create'])->accessToken; - -#### `DELETE /oauth/personal-access-tokens/{token-id}` +// Creating a token with all scopes... +$token = $user->createToken('My Token', ['*'])->accessToken; -This route may be used to revoke personal access tokens: - -```js -axios.delete('/oauth/personal-access-tokens/' + tokenId); +// Retrieving all the valid personal access tokens that belong to the user... +$tokens = $user->tokens() + ->with('client') + ->where('revoked', false) + ->where('expires_at', '>', Date::now()) + ->get() + ->filter(fn (Token $token) => $token->client->hasGrantType('personal_access')); ``` @@ -974,17 +1050,22 @@ axios.delete('/oauth/personal-access-tokens/' + tokenId); Passport includes an [authentication guard](/docs/{{version}}/authentication#adding-custom-guards) that will validate access tokens on incoming requests. Once you have configured the `api` guard to use the `passport` driver, you only need to specify the `auth:api` middleware on any routes that should require a valid access token: - Route::get('/user', function () { - // - })->middleware('auth:api'); +```php +Route::get('/user', function () { + // Only API authenticated users may access this route... +})->middleware('auth:api'); +``` -> {note} If you are using the [client credentials grant](#client-credentials-grant-tokens), you should use [the `client` middleware](#client-credentials-grant-tokens) to protect your routes instead of the `auth:api` middleware. +> [!WARNING] +> If you are using the [client credentials grant](#client-credentials-grant), you should use [the `Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner` middleware](#client-credentials-grant) to protect your routes instead of the `auth:api` middleware. #### Multiple Authentication Guards If your application authenticates different types of users that perhaps use entirely different Eloquent models, you will likely need to define a guard configuration for each user provider type in your application. This allows you to protect requests intended for specific user providers. For example, given the following guard configuration the `config/auth.php` configuration file: +```php +'guards' => [ 'api' => [ 'driver' => 'passport', 'provider' => 'users', @@ -994,28 +1075,35 @@ If your application authenticates different types of users that perhaps use enti 'driver' => 'passport', 'provider' => 'customers', ], +], +``` The following route will utilize the `api-customers` guard, which uses the `customers` user provider, to authenticate incoming requests: - Route::get('/customer', function () { - // - })->middleware('auth:api-customers'); +```php +Route::get('/customer', function () { + // ... +})->middleware('auth:api-customers'); +``` -> {tip} For more information on using multiple user providers with Passport, please consult the [password grant documentation](#customizing-the-user-provider). +> [!NOTE] +> For more information on using multiple user providers with Passport, please consult the [personal access tokens documentation](#customizing-the-user-provider-for-pat) and [password grant documentation](#customizing-the-user-provider). -### Passing The Access Token +### Passing the Access Token -When calling routes that are protected by Passport, your application's API consumers should specify their access token as a `Bearer` token in the `Authorization` header of their request. For example, when using the Guzzle HTTP library: +When calling routes that are protected by Passport, your application's API consumers should specify their access token as a `Bearer` token in the `Authorization` header of their request. For example, when using the `Http` Facade: - use Illuminate\Support\Facades\Http; +```php +use Illuminate\Support\Facades\Http; - $response = Http::withHeaders([ - 'Accept' => 'application/json', - 'Authorization' => 'Bearer '.$accessToken, - ])->get('https://passport-app.test/api/user'); +$response = Http::withHeaders([ + 'Accept' => 'application/json', + 'Authorization' => "Bearer $accessToken", +])->get('https://passport-app.test/api/user'); - return $response->json(); +return $response->json(); +``` ## Token Scopes @@ -1025,228 +1113,283 @@ Scopes allow your API clients to request a specific set of permissions when requ ### Defining Scopes -You may define your API's scopes using the `Passport::tokensCan` method in the `boot` method of your application's `App\Providers\AuthServiceProvider` class. The `tokensCan` method accepts an array of scope names and scope descriptions. The scope description may be anything you wish and will be displayed to users on the authorization approval screen: - - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - Passport::routes(); +You may define your API's scopes using the `Passport::tokensCan` method in the `boot` method of your application's `App\Providers\AppServiceProvider` class. The `tokensCan` method accepts an array of scope names and scope descriptions. The scope description may be anything you wish and will be displayed to users on the authorization approval screen: - Passport::tokensCan([ - 'place-orders' => 'Place orders', - 'check-status' => 'Check order status', - ]); - } +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Passport::tokensCan([ + 'user:read' => 'Retrieve the user info', + 'orders:create' => 'Place orders', + 'orders:read:status' => 'Check order status', + ]); +} +``` ### Default Scope -If a client does not request any specific scopes, you may configure your Passport server to attach default scope(s) to the token using the `setDefaultScope` method. Typically, you should call this method from the `boot` method of your application's `App\Providers\AuthServiceProvider` class: +If a client does not request any specific scopes, you may configure your Passport server to attach default scopes to the token using the `defaultScopes` method. Typically, you should call this method from the `boot` method of your application's `App\Providers\AppServiceProvider` class: - use Laravel\Passport\Passport; +```php +use Laravel\Passport\Passport; - Passport::tokensCan([ - 'place-orders' => 'Place orders', - 'check-status' => 'Check order status', - ]); +Passport::tokensCan([ + 'user:read' => 'Retrieve the user info', + 'orders:create' => 'Place orders', + 'orders:read:status' => 'Check order status', +]); - Passport::setDefaultScope([ - 'check-status', - 'place-orders', - ]); +Passport::defaultScopes([ + 'user:read', + 'orders:create', +]); +``` -### Assigning Scopes To Tokens +### Assigning Scopes to Tokens #### When Requesting Authorization Codes When requesting an access token using the authorization code grant, consumers should specify their desired scopes as the `scope` query string parameter. The `scope` parameter should be a space-delimited list of scopes: - Route::get('/redirect', function () { - $query = http_build_query([ - 'client_id' => 'client-id', - 'redirect_uri' => 'http://example.com/callback', - 'response_type' => 'code', - 'scope' => 'place-orders check-status', - ]); +```php +Route::get('/redirect', function () { + $query = http_build_query([ + 'client_id' => 'your-client-id', + 'redirect_uri' => 'https://third-party-app.com/callback', + 'response_type' => 'code', + 'scope' => 'user:read orders:create', + ]); - return redirect('http://passport-app.test/oauth/authorize?'.$query); - }); + return redirect('https://passport-app.test/oauth/authorize?'.$query); +}); +``` #### When Issuing Personal Access Tokens If you are issuing personal access tokens using the `App\Models\User` model's `createToken` method, you may pass the array of desired scopes as the second argument to the method: - $token = $user->createToken('My Token', ['place-orders'])->accessToken; +```php +$token = $user->createToken('My Token', ['orders:create'])->accessToken; +``` ### Checking Scopes -Passport includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given scope. To get started, add the following middleware to the `$routeMiddleware` property of your `app/Http/Kernel.php` file: - - 'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class, - 'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class, +Passport includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given scope. #### Check For All Scopes -The `scopes` middleware may be assigned to a route to verify that the incoming request's access token has all of the listed scopes: +The `Laravel\Passport\Http\Middleware\CheckToken` middleware may be assigned to a route to verify that the incoming request's access token has all the listed scopes: - Route::get('/orders', function () { - // Access token has both "check-status" and "place-orders" scopes... - })->middleware(['auth:api', 'scopes:check-status,place-orders']); +```php +use Laravel\Passport\Http\Middleware\CheckToken; + +Route::get('/orders', function () { + // Access token has both "orders:read" and "orders:create" scopes... +})->middleware(['auth:api', CheckToken::using('orders:read', 'orders:create')]); +``` -#### Check For Any Scopes +#### Check for Any Scopes -The `scope` middleware may be assigned to a route to verify that the incoming request's access token has *at least one* of the listed scopes: +The `Laravel\Passport\Http\Middleware\CheckTokenForAnyScope` middleware may be assigned to a route to verify that the incoming request's access token has *at least one* of the listed scopes: - Route::get('/orders', function () { - // Access token has either "check-status" or "place-orders" scope... - })->middleware(['auth:api', 'scope:check-status,place-orders']); +```php +use Laravel\Passport\Http\Middleware\CheckTokenForAnyScope; + +Route::get('/orders', function () { + // Access token has either "orders:read" or "orders:create" scope... +})->middleware(['auth:api', CheckTokenForAnyScope::using('orders:read', 'orders:create')]); +``` -#### Checking Scopes On A Token Instance +#### Checking Scopes on a Token Instance Once an access token authenticated request has entered your application, you may still check if the token has a given scope using the `tokenCan` method on the authenticated `App\Models\User` instance: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/orders', function (Request $request) { - if ($request->user()->tokenCan('place-orders')) { - // - } - }); +Route::get('/orders', function (Request $request) { + if ($request->user()->tokenCan('orders:create')) { + // ... + } +}); +``` #### Additional Scope Methods The `scopeIds` method will return an array of all defined IDs / names: - use Laravel\Passport\Passport; +```php +use Laravel\Passport\Passport; - Passport::scopeIds(); +Passport::scopeIds(); +``` The `scopes` method will return an array of all defined scopes as instances of `Laravel\Passport\Scope`: - Passport::scopes(); +```php +Passport::scopes(); +``` The `scopesFor` method will return an array of `Laravel\Passport\Scope` instances matching the given IDs / names: - Passport::scopesFor(['place-orders', 'check-status']); +```php +Passport::scopesFor(['user:read', 'orders:create']); +``` You may determine if a given scope has been defined using the `hasScope` method: - Passport::hasScope('place-orders'); +```php +Passport::hasScope('orders:create'); +``` - -## Consuming Your API With JavaScript + +## SPA Authentication When building an API, it can be extremely useful to be able to consume your own API from your JavaScript application. This approach to API development allows your own application to consume the same API that you are sharing with the world. The same API may be consumed by your web application, mobile applications, third-party applications, and any SDKs that you may publish on various package managers. -Typically, if you want to consume your API from your JavaScript application, you would need to manually send an access token to the application and pass it with each request to your application. However, Passport includes a middleware that can handle this for you. All you need to do is add the `CreateFreshApiToken` middleware to your `web` middleware group in your `app/Http/Kernel.php` file: +Typically, if you want to consume your API from your JavaScript application, you would need to manually send an access token to the application and pass it with each request to your application. However, Passport includes a middleware that can handle this for you. All you need to do is append the `CreateFreshApiToken` middleware to the `web` middleware group in your application's `bootstrap/app.php` file: - 'web' => [ - // Other middleware... - \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, - ], +```php +use Laravel\Passport\Http\Middleware\CreateFreshApiToken; -> {note} You should ensure that the `CreateFreshApiToken` middleware is the last middleware listed in your middleware stack. +->withMiddleware(function (Middleware $middleware): void { + $middleware->web(append: [ + CreateFreshApiToken::class, + ]); +}) +``` + +> [!WARNING] +> You should ensure that the `CreateFreshApiToken` middleware is the last middleware listed in your middleware stack. This middleware will attach a `laravel_token` cookie to your outgoing responses. This cookie contains an encrypted JWT that Passport will use to authenticate API requests from your JavaScript application. The JWT has a lifetime equal to your `session.lifetime` configuration value. Now, since the browser will automatically send the cookie with all subsequent requests, you may make requests to your application's API without explicitly passing an access token: - axios.get('/api/user') - .then(response => { - console.log(response.data); - }); +```js +axios.get('/api/user') + .then(response => { + console.log(response.data); + }); +``` -#### Customizing The Cookie Name - -If needed, you can customize the `laravel_token` cookie's name using the `Passport::cookie` method. Typically, this method should be called from the `boot` method of your application's `App\Providers\AuthServiceProvider` class: - - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - Passport::routes(); - - Passport::cookie('custom_name'); - } +#### Customizing the Cookie Name + +If needed, you can customize the `laravel_token` cookie's name using the `Passport::cookie` method. Typically, this method should be called from the `boot` method of your application's `App\Providers\AppServiceProvider` class: + +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Passport::cookie('custom_name'); +} +``` #### CSRF Protection -When using this method of authentication, you will need to ensure a valid CSRF token header is included in your requests. The default Laravel JavaScript scaffolding includes an Axios instance, which will automatically use the encrypted `XSRF-TOKEN` cookie value to send an `X-XSRF-TOKEN` header on same-origin requests. +When using this method of authentication, you will need to ensure a valid CSRF token header is included in your requests. The default Laravel JavaScript scaffolding included with the skeleton application and all starter kits includes an [Axios](https://github.com/axios/axios) instance, which will automatically use the encrypted `XSRF-TOKEN` cookie value to send an `X-XSRF-TOKEN` header on same-origin requests. -> {tip} If you choose to send the `X-CSRF-TOKEN` header instead of `X-XSRF-TOKEN`, you will need to use the unencrypted token provided by `csrf_token()`. +> [!NOTE] +> If you choose to send the `X-CSRF-TOKEN` header instead of `X-XSRF-TOKEN`, you will need to use the unencrypted token provided by `csrf_token()`. ## Events -Passport raises events when issuing access tokens and refresh tokens. You may use these events to prune or revoke other access tokens in your database. If you would like, you may attach listeners to these events in your application's `App\Providers\EventServiceProvider` class: +Passport raises events when issuing access tokens and refresh tokens. You may [listen for these events](/docs/{{version}}/events) to prune or revoke other access tokens in your database: - /** - * The event listener mappings for the application. - * - * @var array - */ - protected $listen = [ - 'Laravel\Passport\Events\AccessTokenCreated' => [ - 'App\Listeners\RevokeOldTokens', - ], +
+ +| Event Name | +| --------------------------------------------- | +| `Laravel\Passport\Events\AccessTokenCreated` | +| `Laravel\Passport\Events\AccessTokenRevoked` | +| `Laravel\Passport\Events\RefreshTokenCreated` | - 'Laravel\Passport\Events\RefreshTokenCreated' => [ - 'App\Listeners\PruneOldTokens', - ], - ]; +
## Testing Passport's `actingAs` method may be used to specify the currently authenticated user as well as its scopes. The first argument given to the `actingAs` method is the user instance and the second is an array of scopes that should be granted to the user's token: - use App\Models\User; - use Laravel\Passport\Passport; +```php tab=Pest +use App\Models\User; +use Laravel\Passport\Passport; - public function test_servers_can_be_created() - { - Passport::actingAs( - User::factory()->create(), - ['create-servers'] - ); +test('orders can be created', function () { + Passport::actingAs( + User::factory()->create(), + ['orders:create'] + ); - $response = $this->post('/api/create-server'); + $response = $this->post('/api/orders'); - $response->assertStatus(201); - } + $response->assertStatus(201); +}); +``` + +```php tab=PHPUnit +use App\Models\User; +use Laravel\Passport\Passport; + +public function test_orders_can_be_created(): void +{ + Passport::actingAs( + User::factory()->create(), + ['orders:create'] + ); + + $response = $this->post('/api/orders'); + + $response->assertStatus(201); +} +``` Passport's `actingAsClient` method may be used to specify the currently authenticated client as well as its scopes. The first argument given to the `actingAsClient` method is the client instance and the second is an array of scopes that should be granted to the client's token: - use Laravel\Passport\Client; - use Laravel\Passport\Passport; +```php tab=Pest +use Laravel\Passport\Client; +use Laravel\Passport\Passport; - public function test_orders_can_be_retrieved() - { - Passport::actingAsClient( - Client::factory()->create(), - ['check-status'] - ); +test('servers can be retrieved', function () { + Passport::actingAsClient( + Client::factory()->create(), + ['servers:read'] + ); - $response = $this->get('/api/orders'); + $response = $this->get('/api/servers'); - $response->assertStatus(200); - } + $response->assertStatus(200); +}); +``` + +```php tab=PHPUnit +use Laravel\Passport\Client; +use Laravel\Passport\Passport; + +public function test_servers_can_be_retrieved(): void +{ + Passport::actingAsClient( + Client::factory()->create(), + ['servers:read'] + ); + + $response = $this->get('/api/servers'); + + $response->assertStatus(200); +} +``` diff --git a/passwords.md b/passwords.md index 1aa2e2ea0c0..150d5f0c8b4 100644 --- a/passwords.md +++ b/passwords.md @@ -1,12 +1,13 @@ # Resetting Passwords - [Introduction](#introduction) + - [Configuration](#configuration) + - [Driver Prerequisites](#driver-prerequisites) - [Model Preparation](#model-preparation) - - [Database Preparation](#database-preparation) - [Configuring Trusted Hosts](#configuring-trusted-hosts) - [Routing](#routing) - - [Requesting The Password Reset Link](#requesting-the-password-reset-link) - - [Resetting The Password](#resetting-the-password) + - [Requesting the Password Reset Link](#requesting-the-password-reset-link) + - [Resetting the Password](#resetting-the-password) - [Deleting Expired Tokens](#deleting-expired-tokens) - [Customization](#password-customization) @@ -15,32 +16,65 @@ Most web applications provide a way for users to reset their forgotten passwords. Rather than forcing you to re-implement this by hand for every application you create, Laravel provides convenient services for sending password reset links and secure resetting passwords. -> {tip} Want to get started fast? Install a Laravel [application starter kit](/docs/{{version}}/starter-kits) in a fresh Laravel application. Laravel's starter kits will take care of scaffolding your entire authentication system, including resetting forgotten passwords. +> [!NOTE] +> Want to get started fast? Install a Laravel [application starter kit](/docs/{{version}}/starter-kits) in a fresh Laravel application. Laravel's starter kits will take care of scaffolding your entire authentication system, including resetting forgotten passwords. - -### Model Preparation + +### Configuration -Before using the password reset features of Laravel, your application's `App\Models\User` model must use the `Illuminate\Notifications\Notifiable` trait. Typically, this trait is already included on the default `App\Models\User` model that is created with new Laravel applications. +Your application's password reset configuration file is stored at `config/auth.php`. Be sure to review the options available to you in this file. By default, Laravel is configured to use the `database` password reset driver. -Next, verify that your `App\Models\User` model implements the `Illuminate\Contracts\Auth\CanResetPassword` contract. The `App\Models\User` model included with the framework already implements this interface, and uses the `Illuminate\Auth\Passwords\CanResetPassword` trait to include the methods needed to implement the interface. +The password reset `driver` configuration option defines where password reset data will be stored. Laravel includes two drivers: - -### Database Preparation +
-A table must be created to store your application's password reset tokens. The migration for this table is included in the default Laravel application, so you only need to migrate your database to create this table: +- `database` - password reset data is stored in a relational database. +- `cache` - password reset data is stored in one of your cache-based stores. -```shell -php artisan migrate +
+ + +### Driver Prerequisites + + +#### Database + +When using the default `database` driver, a table must be created to store your application's password reset tokens. Typically, this is included in Laravel's default `0001_01_01_000000_create_users_table.php` database migration. + + +#### Cache + +There is also a cache driver available for handling password resets, which does not require a dedicated database table. Entries are keyed by the user's email address, so ensure you are not using email addresses as a cache key elsewhere in your application: + +```php +'passwords' => [ + 'users' => [ + 'driver' => 'cache', + 'provider' => 'users', + 'store' => 'passwords', // Optional... + 'expire' => 60, + 'throttle' => 60, + ], +], ``` +To prevent a call to `artisan cache:clear` from flushing your password reset data, you can optionally specify a separate cache store with the `store` configuration key. The value should correspond to a store configured in your `config/cache.php` configuration value. + + +### Model Preparation + +Before using the password reset features of Laravel, your application's `App\Models\User` model must use the `Illuminate\Notifications\Notifiable` trait. Typically, this trait is already included on the default `App\Models\User` model that is created with new Laravel applications. + +Next, verify that your `App\Models\User` model implements the `Illuminate\Contracts\Auth\CanResetPassword` contract. The `App\Models\User` model included with the framework already implements this interface, and uses the `Illuminate\Auth\Passwords\CanResetPassword` trait to include the methods needed to implement the interface. + ### Configuring Trusted Hosts By default, Laravel will respond to all requests it receives regardless of the content of the HTTP request's `Host` header. In addition, the `Host` header's value will be used when generating absolute URLs to your application during a web request. -Typically, you should configure your web server, such as Nginx or Apache, to only send requests to your application that match a given host name. However, if you do not have the ability to customize your web server directly and need to instruct Laravel to only respond to certain host names, you may do so by enabling the `App\Http\Middleware\TrustHosts` middleware for your application. This is particularly important when your application offers password reset functionality. +Typically, you should configure your web server, such as Nginx or Apache, to only send requests to your application that match a given hostname. However, if you do not have the ability to customize your web server directly and need to instruct Laravel to only respond to certain hostnames, you may do so by using the `trustHosts` middleware method in your application's `bootstrap/app.php` file. This is particularly important when your application offers password reset functionality. -To learn more about this middleware, please consult the [`TrustHosts` middleware documentation](/docs/{{version}}/requests#configuring-trusted-hosts). +To learn more about this middleware method, please consult the [TrustHosts middleware documentation](/docs/{{version}}/requests#configuring-trusted-hosts). ## Routing @@ -48,109 +82,122 @@ To learn more about this middleware, please consult the [`TrustHosts` middleware To properly implement support for allowing users to reset their passwords, we will need to define several routes. First, we will need a pair of routes to handle allowing the user to request a password reset link via their email address. Second, we will need a pair of routes to handle actually resetting the password once the user visits the password reset link that is emailed to them and completes the password reset form. -### Requesting The Password Reset Link +### Requesting the Password Reset Link #### The Password Reset Link Request Form First, we will define the routes that are needed to request password reset links. To get started, we will define a route that returns a view with the password reset link request form: - Route::get('/forgot-password', function () { - return view('auth.forgot-password'); - })->middleware('guest')->name('password.request'); +```php +Route::get('/forgot-password', function () { + return view('auth.forgot-password'); +})->middleware('guest')->name('password.request'); +``` The view that is returned by this route should have a form containing an `email` field, which will allow the user to request a password reset link for a given email address. -#### Handling The Form Submission +#### Handling the Form Submission Next, we will define a route that handles the form submission request from the "forgot password" view. This route will be responsible for validating the email address and sending the password reset request to the corresponding user: - use Illuminate\Http\Request; - use Illuminate\Support\Facades\Password; +```php +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Password; - Route::post('/forgot-password', function (Request $request) { - $request->validate(['email' => 'required|email']); +Route::post('/forgot-password', function (Request $request) { + $request->validate(['email' => 'required|email']); - $status = Password::sendResetLink( - $request->only('email') - ); + $status = Password::sendResetLink( + $request->only('email') + ); - return $status === Password::RESET_LINK_SENT - ? back()->with(['status' => __($status)]) - : back()->withErrors(['email' => __($status)]); - })->middleware('guest')->name('password.email'); + return $status === Password::ResetLinkSent + ? back()->with(['status' => __($status)]) + : back()->withErrors(['email' => __($status)]); +})->middleware('guest')->name('password.email'); +``` Before moving on, let's examine this route in more detail. First, the request's `email` attribute is validated. Next, we will use Laravel's built-in "password broker" (via the `Password` facade) to send a password reset link to the user. The password broker will take care of retrieving the user by the given field (in this case, the email address) and sending the user a password reset link via Laravel's built-in [notification system](/docs/{{version}}/notifications). The `sendResetLink` method returns a "status" slug. This status may be translated using Laravel's [localization](/docs/{{version}}/localization) helpers in order to display a user-friendly message to the user regarding the status of their request. The translation of the password reset status is determined by your application's `lang/{lang}/passwords.php` language file. An entry for each possible value of the status slug is located within the `passwords` language file. +> [!NOTE] +> By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. + You may be wondering how Laravel knows how to retrieve the user record from your application's database when calling the `Password` facade's `sendResetLink` method. The Laravel password broker utilizes your authentication system's "user providers" to retrieve database records. The user provider used by the password broker is configured within the `passwords` configuration array of your `config/auth.php` configuration file. To learn more about writing custom user providers, consult the [authentication documentation](/docs/{{version}}/authentication#adding-custom-user-providers). -> {tip} When manually implementing password resets, you are required to define the contents of the views and routes yourself. If you would like scaffolding that includes all necessary authentication and verification logic, check out the [Laravel application starter kits](/docs/{{version}}/starter-kits). +> [!NOTE] +> When manually implementing password resets, you are required to define the contents of the views and routes yourself. If you would like scaffolding that includes all necessary authentication and verification logic, check out the [Laravel application starter kits](/docs/{{version}}/starter-kits). -### Resetting The Password +### Resetting the Password #### The Password Reset Form Next, we will define the routes necessary to actually reset the password once the user clicks on the password reset link that has been emailed to them and provides a new password. First, let's define the route that will display the reset password form that is displayed when the user clicks the reset password link. This route will receive a `token` parameter that we will use later to verify the password reset request: - Route::get('/reset-password/{token}', function ($token) { - return view('auth.reset-password', ['token' => $token]); - })->middleware('guest')->name('password.reset'); +```php +Route::get('/reset-password/{token}', function (string $token) { + return view('auth.reset-password', ['token' => $token]); +})->middleware('guest')->name('password.reset'); +``` The view that is returned by this route should display a form containing an `email` field, a `password` field, a `password_confirmation` field, and a hidden `token` field, which should contain the value of the secret `$token` received by our route. -#### Handling The Form Submission +#### Handling the Form Submission Of course, we need to define a route to actually handle the password reset form submission. This route will be responsible for validating the incoming request and updating the user's password in the database: - use Illuminate\Auth\Events\PasswordReset; - use Illuminate\Http\Request; - use Illuminate\Support\Facades\Hash; - use Illuminate\Support\Facades\Password; - use Illuminate\Support\Str; - - Route::post('/reset-password', function (Request $request) { - $request->validate([ - 'token' => 'required', - 'email' => 'required|email', - 'password' => 'required|min:8|confirmed', - ]); - - $status = Password::reset( - $request->only('email', 'password', 'password_confirmation', 'token'), - function ($user, $password) { - $user->forceFill([ - 'password' => Hash::make($password) - ])->setRememberToken(Str::random(60)); - - $user->save(); - - event(new PasswordReset($user)); - } - ); - - return $status === Password::PASSWORD_RESET - ? redirect()->route('login')->with('status', __($status)) - : back()->withErrors(['email' => [__($status)]]); - })->middleware('guest')->name('password.update'); +```php +use App\Models\User; +use Illuminate\Auth\Events\PasswordReset; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Facades\Password; +use Illuminate\Support\Str; + +Route::post('/reset-password', function (Request $request) { + $request->validate([ + 'token' => 'required', + 'email' => 'required|email', + 'password' => 'required|min:8|confirmed', + ]); + + $status = Password::reset( + $request->only('email', 'password', 'password_confirmation', 'token'), + function (User $user, string $password) { + $user->forceFill([ + 'password' => Hash::make($password) + ])->setRememberToken(Str::random(60)); + + $user->save(); + + event(new PasswordReset($user)); + } + ); + + return $status === Password::PasswordReset + ? redirect()->route('login')->with('status', __($status)) + : back()->withErrors(['email' => [__($status)]]); +})->middleware('guest')->name('password.update'); +``` Before moving on, let's examine this route in more detail. First, the request's `token`, `email`, and `password` attributes are validated. Next, we will use Laravel's built-in "password broker" (via the `Password` facade) to validate the password reset request credentials. If the token, email address, and password given to the password broker are valid, the closure passed to the `reset` method will be invoked. Within this closure, which receives the user instance and the plain-text password provided to the password reset form, we may update the user's password in the database. -The `reset` method returns a "status" slug. This status may be translated using Laravel's [localization](/docs/{{version}}/localization) helpers in order to display a user-friendly message to the user regarding the status of their request. The translation of the password reset status is determined by your application's `lang/{lang}/passwords.php` language file. An entry for each possible value of the status slug is located within the `passwords` language file. +The `reset` method returns a "status" slug. This status may be translated using Laravel's [localization](/docs/{{version}}/localization) helpers in order to display a user-friendly message to the user regarding the status of their request. The translation of the password reset status is determined by your application's `lang/{lang}/passwords.php` language file. An entry for each possible value of the status slug is located within the `passwords` language file. If your application does not contain a `lang` directory, you may create it using the `lang:publish` Artisan command. Before moving on, you may be wondering how Laravel knows how to retrieve the user record from your application's database when calling the `Password` facade's `reset` method. The Laravel password broker utilizes your authentication system's "user providers" to retrieve database records. The user provider used by the password broker is configured within the `passwords` configuration array of your `config/auth.php` configuration file. To learn more about writing custom user providers, consult the [authentication documentation](/docs/{{version}}/authentication#adding-custom-user-providers). ## Deleting Expired Tokens -Password reset tokens that have expired will still be present within your database. However, you may easily delete these records using the `auth:clear-resets` Artisan command: +If you are using the `database` driver, password reset tokens that have expired will still be present within your database. However, you may easily delete these records using the `auth:clear-resets` Artisan command: ```shell php artisan auth:clear-resets @@ -158,7 +205,11 @@ php artisan auth:clear-resets If you would like to automate this process, consider adding the command to your application's [scheduler](/docs/{{version}}/scheduling): - $schedule->command('auth:clear-resets')->everyFifteenMinutes(); +```php +use Illuminate\Support\Facades\Schedule; + +Schedule::command('auth:clear-resets')->everyFifteenMinutes(); +``` ## Customization @@ -166,40 +217,40 @@ If you would like to automate this process, consider adding the command to your #### Reset Link Customization -You may customize the password reset link URL using the `createUrlUsing` method provided by the `ResetPassword` notification class. This method accepts a closure which receives the user instance that is receiving the notification as well as the password reset link token. Typically, you should call this method from your `App\Providers\AuthServiceProvider` service provider's `boot` method: - - use Illuminate\Auth\Notifications\ResetPassword; - - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - $this->registerPolicies(); - - ResetPassword::createUrlUsing(function ($user, string $token) { - return 'https://example.com/reset-password?token='.$token; - }); - } +You may customize the password reset link URL using the `createUrlUsing` method provided by the `ResetPassword` notification class. This method accepts a closure which receives the user instance that is receiving the notification as well as the password reset link token. Typically, you should call this method from the `boot` method of your application's `AppServiceProvider`: + +```php +use App\Models\User; +use Illuminate\Auth\Notifications\ResetPassword; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + ResetPassword::createUrlUsing(function (User $user, string $token) { + return 'https://example.com/reset-password?token='.$token; + }); +} +``` #### Reset Email Customization You may easily modify the notification class used to send the password reset link to the user. To get started, override the `sendPasswordResetNotification` method on your `App\Models\User` model. Within this method, you may send the notification using any [notification class](/docs/{{version}}/notifications) of your own creation. The password reset `$token` is the first argument received by the method. You may use this `$token` to build the password reset URL of your choice and send your notification to the user: - use App\Notifications\ResetPasswordNotification; +```php +use App\Notifications\ResetPasswordNotification; - /** - * Send a password reset notification to the user. - * - * @param string $token - * @return void - */ - public function sendPasswordResetNotification($token) - { - $url = 'https://example.com/reset-password?token='.$token; +/** + * Send a password reset notification to the user. + * + * @param string $token + */ +public function sendPasswordResetNotification($token): void +{ + $url = 'https://example.com/reset-password?token='.$token; - $this->notify(new ResetPasswordNotification($url)); - } + $this->notify(new ResetPasswordNotification($url)); +} +``` diff --git a/pennant.md b/pennant.md new file mode 100644 index 00000000000..a0c593c2e5d --- /dev/null +++ b/pennant.md @@ -0,0 +1,1201 @@ +# Laravel Pennant + +- [Introduction](#introduction) +- [Installation](#installation) +- [Configuration](#configuration) +- [Defining Features](#defining-features) + - [Class Based Features](#class-based-features) +- [Checking Features](#checking-features) + - [Conditional Execution](#conditional-execution) + - [The `HasFeatures` Trait](#the-has-features-trait) + - [Blade Directive](#blade-directive) + - [Middleware](#middleware) + - [Intercepting Feature Checks](#intercepting-feature-checks) + - [In-Memory Cache](#in-memory-cache) +- [Scope](#scope) + - [Specifying the Scope](#specifying-the-scope) + - [Default Scope](#default-scope) + - [Nullable Scope](#nullable-scope) + - [Identifying Scope](#identifying-scope) + - [Serializing Scope](#serializing-scope) +- [Rich Feature Values](#rich-feature-values) +- [Retrieving Multiple Features](#retrieving-multiple-features) +- [Eager Loading](#eager-loading) +- [Updating Values](#updating-values) + - [Bulk Updates](#bulk-updates) + - [Purging Features](#purging-features) +- [Testing](#testing) +- [Adding Custom Pennant Drivers](#adding-custom-pennant-drivers) + - [Implementing the Driver](#implementing-the-driver) + - [Registering the Driver](#registering-the-driver) + - [Defining Features Externally](#defining-features-externally) +- [Events](#events) + + +## Introduction + +[Laravel Pennant](https://github.com/laravel/pennant) is a simple and light-weight feature flag package - without the cruft. Feature flags enable you to incrementally roll out new application features with confidence, A/B test new interface designs, complement a trunk-based development strategy, and much more. + + +## Installation + +First, install Pennant into your project using the Composer package manager: + +```shell +composer require laravel/pennant +``` + +Next, you should publish the Pennant configuration and migration files using the `vendor:publish` Artisan command: + +```shell +php artisan vendor:publish --provider="Laravel\Pennant\PennantServiceProvider" +``` + +Finally, you should run your application's database migrations. This will create a `features` table that Pennant uses to power its `database` driver: + +```shell +php artisan migrate +``` + + +## Configuration + +After publishing Pennant's assets, its configuration file will be located at `config/pennant.php`. This configuration file allows you to specify the default storage mechanism that will be used by Pennant to store resolved feature flag values. + +Pennant includes support for storing resolved feature flag values in an in-memory array via the `array` driver. Or, Pennant can store resolved feature flag values persistently in a relational database via the `database` driver, which is the default storage mechanism used by Pennant. + + +## Defining Features + +To define a feature, you may use the `define` method offered by the `Feature` facade. You will need to provide a name for the feature, as well as a closure that will be invoked to resolve the feature's initial value. + +Typically, features are defined in a service provider using the `Feature` facade. The closure will receive the "scope" for the feature check. Most commonly, the scope is the currently authenticated user. In this example, we will define a feature for incrementally rolling out a new API to our application's users: + +```php + match (true) { + $user->isInternalTeamMember() => true, + $user->isHighTrafficCustomer() => false, + default => Lottery::odds(1 / 100), + }); + } +} +``` + +As you can see, we have the following rules for our feature: + +- All internal team members should be using the new API. +- Any high traffic customers should not be using the new API. +- Otherwise, the feature should be randomly assigned to users with a 1 in 100 chance of being active. + +The first time the `new-api` feature is checked for a given user, the result of the closure will be stored by the storage driver. The next time the feature is checked against the same user, the value will be retrieved from storage and the closure will not be invoked. + +For convenience, if a feature definition only returns a lottery, you may omit the closure completely: + + Feature::define('site-redesign', Lottery::odds(1, 1000)); + + +### Class Based Features + +Pennant also allows you to define class-based features. Unlike closure-based feature definitions, there is no need to register a class-based feature in a service provider. To create a class-based feature, you may invoke the `pennant:feature` Artisan command. By default, the feature class will be placed in your application's `app/Features` directory: + +```shell +php artisan pennant:feature NewApi +``` + +When writing a feature class, you only need to define a `resolve` method, which will be invoked to resolve the feature's initial value for a given scope. Again, the scope will typically be the currently authenticated user: + +```php +isInternalTeamMember() => true, + $user->isHighTrafficCustomer() => false, + default => Lottery::odds(1 / 100), + }; + } +} +``` + +If you would like to manually resolve an instance of a class-based feature, you may invoke the `instance` method on the `Feature` facade: + +```php +use Illuminate\Support\Facades\Feature; + +$instance = Feature::instance(NewApi::class); +``` + +> [!NOTE] +> Feature classes are resolved via the [container](/docs/{{version}}/container), so you may inject dependencies into the feature class's constructor when needed. + +#### Customizing the Stored Feature Name + +By default, Pennant will store the feature class's fully qualified class name. If you would like to decouple the stored feature name from the application's internal structure, you may specify a `$name` property on the feature class. The value of this property will be stored in place of the class name: + +```php + +## Checking Features + +To determine if a feature is active, you may use the `active` method on the `Feature` facade. By default, features are checked against the currently authenticated user: + +```php +resolveNewApiResponse($request) + : $this->resolveLegacyApiResponse($request); + } + + // ... +} +``` + +Although features are checked against the currently authenticated user by default, you may easily check the feature against another user or [scope](#scope). To accomplish this, use the `for` method offered by the `Feature` facade: + +```php +return Feature::for($user)->active('new-api') + ? $this->resolveNewApiResponse($request) + : $this->resolveLegacyApiResponse($request); +``` + +Pennant also offers some additional convenience methods that may prove useful when determining if a feature is active or not: + +```php +// Determine if all of the given features are active... +Feature::allAreActive(['new-api', 'site-redesign']); + +// Determine if any of the given features are active... +Feature::someAreActive(['new-api', 'site-redesign']); + +// Determine if a feature is inactive... +Feature::inactive('new-api'); + +// Determine if all of the given features are inactive... +Feature::allAreInactive(['new-api', 'site-redesign']); + +// Determine if any of the given features are inactive... +Feature::someAreInactive(['new-api', 'site-redesign']); +``` + +> [!NOTE] +> When using Pennant outside of an HTTP context, such as in an Artisan command or a queued job, you should typically [explicitly specify the feature's scope](#specifying-the-scope). Alternatively, you may define a [default scope](#default-scope) that accounts for both authenticated HTTP contexts and unauthenticated contexts. + + +#### Checking Class Based Features + +For class-based features, you should provide the class name when checking the feature: + +```php +resolveNewApiResponse($request) + : $this->resolveLegacyApiResponse($request); + } + + // ... +} +``` + + +### Conditional Execution + +The `when` method may be used to fluently execute a given closure if a feature is active. Additionally, a second closure may be provided and will be executed if the feature is inactive: + +```php + $this->resolveNewApiResponse($request), + fn () => $this->resolveLegacyApiResponse($request), + ); + } + + // ... +} +``` + +The `unless` method serves as the inverse of the `when` method, executing the first closure if the feature is inactive: + +```php +return Feature::unless(NewApi::class, + fn () => $this->resolveLegacyApiResponse($request), + fn () => $this->resolveNewApiResponse($request), +); +``` + + +### The `HasFeatures` Trait + +Pennant's `HasFeatures` trait may be added to your application's `User` model (or any other model that has features) to provide a fluent, convenient way to check features directly from the model: + +```php +features()->active('new-api')) { + // ... +} +``` + +Of course, the `features` method provides access to many other convenient methods for interacting with features: + +```php +// Values... +$value = $user->features()->value('purchase-button') +$values = $user->features()->values(['new-api', 'purchase-button']); + +// State... +$user->features()->active('new-api'); +$user->features()->allAreActive(['new-api', 'server-api']); +$user->features()->someAreActive(['new-api', 'server-api']); + +$user->features()->inactive('new-api'); +$user->features()->allAreInactive(['new-api', 'server-api']); +$user->features()->someAreInactive(['new-api', 'server-api']); + +// Conditional execution... +$user->features()->when('new-api', + fn () => /* ... */, + fn () => /* ... */, +); + +$user->features()->unless('new-api', + fn () => /* ... */, + fn () => /* ... */, +); +``` + + +### Blade Directive + +To make checking features in Blade a seamless experience, Pennant offers the `@feature` and `@featureany` directive: + +```blade +@feature('site-redesign') + +@else + +@endfeature + +@featureany(['site-redesign', 'beta']) + +@endfeatureany +``` + + +### Middleware + +Pennant also includes a [middleware](/docs/{{version}}/middleware) that may be used to verify the currently authenticated user has access to a feature before a route is even invoked. You may assign the middleware to a route and specify the features that are required to access the route. If any of the specified features are inactive for the currently authenticated user, a `400 Bad Request` HTTP response will be returned by the route. Multiple features may be passed to the static `using` method. + +```php +use Illuminate\Support\Facades\Route; +use Laravel\Pennant\Middleware\EnsureFeaturesAreActive; + +Route::get('/api/servers', function () { + // ... +})->middleware(EnsureFeaturesAreActive::using('new-api', 'servers-api')); +``` + + +#### Customizing the Response + +If you would like to customize the response that is returned by the middleware when one of the listed features is inactive, you may use the `whenInactive` method provided by the `EnsureFeaturesAreActive` middleware. Typically, this method should be invoked within the `boot` method of one of your application's service providers: + +```php +use Illuminate\Http\Request; +use Illuminate\Http\Response; +use Laravel\Pennant\Middleware\EnsureFeaturesAreActive; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + EnsureFeaturesAreActive::whenInactive( + function (Request $request, array $features) { + return new Response(status: 403); + } + ); + + // ... +} +``` + + +### Intercepting Feature Checks + +Sometimes it can be useful to perform some in-memory checks before retrieving the stored value of a given feature. Imagine you are developing a new API behind a feature flag and want the ability to disable the new API without losing any of the resolved feature values in storage. If you notice a bug in the new API, you could easily disable it for everyone except internal team members, fix the bug, and then re-enable the new API for the users that previously had access to the feature. + +You can achieve this with a [class-based feature's](#class-based-features) `before` method. When present, the `before` method is always run in-memory before retrieving the value from storage. If a non-`null` value is returned from the method, it will be used in place of the feature's stored value for the duration of the request: + +```php +isInternalTeamMember(); + } + } + + /** + * Resolve the feature's initial value. + */ + public function resolve(User $user): mixed + { + return match (true) { + $user->isInternalTeamMember() => true, + $user->isHighTrafficCustomer() => false, + default => Lottery::odds(1 / 100), + }; + } +} +``` + +You could also use this feature to schedule the global rollout of a feature that was previously behind a feature flag: + +```php +isInternalTeamMember(); + } + + if (Carbon::parse(Config::get('features.new-api.rollout-date'))->isPast()) { + return true; + } + } + + // ... +} +``` + + +### In-Memory Cache + +When checking a feature, Pennant will create an in-memory cache of the result. If you are using the `database` driver, this means that re-checking the same feature flag within a single request will not trigger additional database queries. This also ensures that the feature has a consistent result for the duration of the request. + +If you need to manually flush the in-memory cache, you may use the `flushCache` method offered by the `Feature` facade: + +```php +Feature::flushCache(); +``` + + +## Scope + + +### Specifying the Scope + +As discussed, features are typically checked against the currently authenticated user. However, this may not always suit your needs. Therefore, it is possible to specify the scope you would like to check a given feature against via the `Feature` facade's `for` method: + +```php +return Feature::for($user)->active('new-api') + ? $this->resolveNewApiResponse($request) + : $this->resolveLegacyApiResponse($request); +``` + +Of course, feature scopes are not limited to "users". Imagine you have built a new billing experience that you are rolling out to entire teams rather than individual users. Perhaps you would like the oldest teams to have a slower rollout than the newer teams. Your feature resolution closure might look something like the following: + +```php +use App\Models\Team; +use Illuminate\Support\Carbon; +use Illuminate\Support\Lottery; +use Laravel\Pennant\Feature; + +Feature::define('billing-v2', function (Team $team) { + if ($team->created_at->isAfter(new Carbon('1st Jan, 2023'))) { + return true; + } + + if ($team->created_at->isAfter(new Carbon('1st Jan, 2019'))) { + return Lottery::odds(1 / 100); + } + + return Lottery::odds(1 / 1000); +}); +``` + +You will notice that the closure we have defined is not expecting a `User`, but is instead expecting a `Team` model. To determine if this feature is active for a user's team, you should pass the team to the `for` method offered by the `Feature` facade: + +```php +if (Feature::for($user->team)->active('billing-v2')) { + return redirect('/billing/v2'); +} + +// ... +``` + + +### Default Scope + +It is also possible to customize the default scope Pennant uses to check features. For example, maybe all of your features are checked against the currently authenticated user's team instead of the user. Instead of having to call `Feature::for($user->team)` every time you check a feature, you may instead specify the team as the default scope. Typically, this should be done in one of your application's service providers: + +```php + Auth::user()?->team); + + // ... + } +} +``` + +If no scope is explicitly provided via the `for` method, the feature check will now use the currently authenticated user's team as the default scope: + +```php +Feature::active('billing-v2'); + +// Is now equivalent to... + +Feature::for($user->team)->active('billing-v2'); +``` + + +### Nullable Scope + +If the scope you provide when checking a feature is `null` and the feature's definition does not support `null` via a nullable type or by including `null` in a union type, Pennant will automatically return `false` as the feature's result value. + +So, if the scope you are passing to a feature is potentially `null` and you want the feature's value resolver to be invoked, you should account for that in your feature's definition. A `null` scope may occur if you check a feature within an Artisan command, queued job, or unauthenticated route. Since there is usually not an authenticated user in these contexts, the default scope will be `null`. + +If you do not always [explicitly specify your feature scope](#specifying-the-scope) then you should ensure the scope's type is "nullable" and handle the `null` scope value within your feature definition logic: + +```php +use App\Models\User; +use Illuminate\Support\Lottery; +use Laravel\Pennant\Feature; + +Feature::define('new-api', fn (User $user) => match (true) {// [tl! remove] +Feature::define('new-api', fn (User|null $user) => match (true) {// [tl! add] + $user === null => true,// [tl! add] + $user->isInternalTeamMember() => true, + $user->isHighTrafficCustomer() => false, + default => Lottery::odds(1 / 100), +}); +``` + + +### Identifying Scope + +Pennant's built-in `array` and `database` storage drivers know how to properly store scope identifiers for all PHP data types as well as Eloquent models. However, if your application utilizes a third-party Pennant driver, that driver may not know how to properly store an identifier for an Eloquent model or other custom types in your application. + +In light of this, Pennant allows you to format scope values for storage by implementing the `FeatureScopeable` contract on the objects in your application that are used as Pennant scopes. + +For example, imagine you are using two different feature drivers in a single application: the built-in `database` driver and a third-party "Flag Rocket" driver. The "Flag Rocket" driver does not know how to properly store an Eloquent model. Instead, it requires a `FlagRocketUser` instance. By implementing the `toFeatureIdentifier` defined by the `FeatureScopeable` contract, we can customize the storable scope value provided to each driver used by our application: + +```php + $this, + 'flag-rocket' => FlagRocketUser::fromId($this->flag_rocket_id), + }; + } +} +``` + + +### Serializing Scope + +By default, Pennant will use a fully qualified class name when storing a feature associated with an Eloquent model. If you are already using an [Eloquent morph map](/docs/{{version}}/eloquent-relationships#custom-polymorphic-types), you may choose to have Pennant also use the morph map to decouple the stored feature from your application structure. + +To achieve this, after defining your Eloquent morph map in a service provider, you may invoke the `Feature` facade's `useMorphMap` method: + +```php +use Illuminate\Database\Eloquent\Relations\Relation; +use Laravel\Pennant\Feature; + +Relation::enforceMorphMap([ + 'post' => 'App\Models\Post', + 'video' => 'App\Models\Video', +]); + +Feature::useMorphMap(); +``` + + +## Rich Feature Values + +Until now, we have primarily shown features as being in a binary state, meaning they are either "active" or "inactive", but Pennant also allows you to store rich values as well. + +For example, imagine you are testing three new colors for the "Buy now" button of your application. Instead of returning `true` or `false` from the feature definition, you may instead return a string: + +```php +use Illuminate\Support\Arr; +use Laravel\Pennant\Feature; + +Feature::define('purchase-button', fn (User $user) => Arr::random([ + 'blue-sapphire', + 'seafoam-green', + 'tart-orange', +])); +``` + +You may retrieve the value of the `purchase-button` feature using the `value` method: + +```php +$color = Feature::value('purchase-button'); +``` + +Pennant's included Blade directive also makes it easy to conditionally render content based on the current value of the feature: + +```blade +@feature('purchase-button', 'blue-sapphire') + +@elsefeature('purchase-button', 'seafoam-green') + +@elsefeature('purchase-button', 'tart-orange') + +@endfeature +``` + +> [!NOTE] +> When using rich values, it is important to know that a feature is considered "active" when it has any value other than `false`. + +When calling the [conditional `when`](#conditional-execution) method, the feature's rich value will be provided to the first closure: + +```php +Feature::when('purchase-button', + fn ($color) => /* ... */, + fn () => /* ... */, +); +``` + +Likewise, when calling the conditional `unless` method, the feature's rich value will be provided to the optional second closure: + +```php +Feature::unless('purchase-button', + fn () => /* ... */, + fn ($color) => /* ... */, +); +``` + + +## Retrieving Multiple Features + +The `values` method allows the retrieval of multiple features for a given scope: + +```php +Feature::values(['billing-v2', 'purchase-button']); + +// [ +// 'billing-v2' => false, +// 'purchase-button' => 'blue-sapphire', +// ] +``` + +Or, you may use the `all` method to retrieve the values of all defined features for a given scope: + +```php +Feature::all(); + +// [ +// 'billing-v2' => false, +// 'purchase-button' => 'blue-sapphire', +// 'site-redesign' => true, +// ] +``` + +However, class-based features are dynamically registered and are not known by Pennant until they are explicitly checked. This means your application's class-based features may not appear in the results returned by the `all` method if they have not already been checked during the current request. + +If you would like to ensure that feature classes are always included when using the `all` method, you may use Pennant's feature discovery capabilities. To get started, invoke the `discover` method in one of your application's service providers: + +```php + true, +// 'billing-v2' => false, +// 'purchase-button' => 'blue-sapphire', +// 'site-redesign' => true, +// ] +``` + + +## Eager Loading + +Although Pennant keeps an in-memory cache of all resolved features for a single request, it is still possible to encounter performance issues. To alleviate this, Pennant offers the ability to eager load feature values. + +To illustrate this, imagine that we are checking if a feature is active within a loop: + +```php +use Laravel\Pennant\Feature; + +foreach ($users as $user) { + if (Feature::for($user)->active('notifications-beta')) { + $user->notify(new RegistrationSuccess); + } +} +``` + +Assuming we are using the database driver, this code will execute a database query for every user in the loop - executing potentially hundreds of queries. However, using Pennant's `load` method, we can remove this potential performance bottleneck by eager loading the feature values for a collection of users or scopes: + +```php +Feature::for($users)->load(['notifications-beta']); + +foreach ($users as $user) { + if (Feature::for($user)->active('notifications-beta')) { + $user->notify(new RegistrationSuccess); + } +} +``` + +To load feature values only when they have not already been loaded, you may use the `loadMissing` method: + +```php +Feature::for($users)->loadMissing([ + 'new-api', + 'purchase-button', + 'notifications-beta', +]); +``` + +You may load all defined features using the `loadAll` method: + +```php +Feature::for($users)->loadAll(); +``` + + +## Updating Values + +When a feature's value is resolved for the first time, the underlying driver will store the result in storage. This is often necessary to ensure a consistent experience for your users across requests. However, at times, you may want to manually update the feature's stored value. + +To accomplish this, you may use the `activate` and `deactivate` methods to toggle a feature "on" or "off": + +```php +use Laravel\Pennant\Feature; + +// Activate the feature for the default scope... +Feature::activate('new-api'); + +// Deactivate the feature for the given scope... +Feature::for($user->team)->deactivate('billing-v2'); +``` + +It is also possible to manually set a rich value for a feature by providing a second argument to the `activate` method: + +```php +Feature::activate('purchase-button', 'seafoam-green'); +``` + +To instruct Pennant to forget the stored value for a feature, you may use the `forget` method. When the feature is checked again, Pennant will resolve the feature's value from its feature definition: + +```php +Feature::forget('purchase-button'); +``` + + +### Bulk Updates + +To update stored feature values in bulk, you may use the `activateForEveryone` and `deactivateForEveryone` methods. + +For example, imagine you are now confident in the `new-api` feature's stability and have landed on the best `'purchase-button'` color for your checkout flow - you can update the stored value for all users accordingly: + +```php +use Laravel\Pennant\Feature; + +Feature::activateForEveryone('new-api'); + +Feature::activateForEveryone('purchase-button', 'seafoam-green'); +``` + +Alternatively, you may deactivate the feature for all users: + +```php +Feature::deactivateForEveryone('new-api'); +``` + +> [!NOTE] +> This will only update the resolved feature values that have been stored by Pennant's storage driver. You will also need to update the feature definition in your application. + + +### Purging Features + +Sometimes, it can be useful to purge an entire feature from storage. This is typically necessary if you have removed the feature from your application or you have made adjustments to the feature's definition that you would like to rollout to all users. + +You may remove all stored values for a feature using the `purge` method: + +```php +// Purging a single feature... +Feature::purge('new-api'); + +// Purging multiple features... +Feature::purge(['new-api', 'purchase-button']); +``` + +If you would like to purge _all_ features from storage, you may invoke the `purge` method without any arguments: + +```php +Feature::purge(); +``` + +As it can be useful to purge features as part of your application's deployment pipeline, Pennant includes a `pennant:purge` Artisan command which will purge the provided features from storage: + +```shell +php artisan pennant:purge new-api + +php artisan pennant:purge new-api purchase-button +``` + +It is also possible to purge all features _except_ those in a given feature list. For example, imagine you wanted to purge all features but keep the values for the "new-api" and "purchase-button" features in storage. To accomplish this, you can pass those feature names to the `--except` option: + +```shell +php artisan pennant:purge --except=new-api --except=purchase-button +``` + +For convenience, the `pennant:purge` command also supports an `--except-registered` flag. This flag indicates that all features except those explicitly registered in a service provider should be purged: + +```shell +php artisan pennant:purge --except-registered +``` + + +## Testing + +When testing code that interacts with feature flags, the easiest way to control the feature flag's returned value in your tests is to simply re-define the feature. For example, imagine you have the following feature defined in one of your application's service provider: + +```php +use Illuminate\Support\Arr; +use Laravel\Pennant\Feature; + +Feature::define('purchase-button', fn () => Arr::random([ + 'blue-sapphire', + 'seafoam-green', + 'tart-orange', +])); +``` + +To modify the feature's returned value in your tests, you may re-define the feature at the beginning of the test. The following test will always pass, even though the `Arr::random()` implementation is still present in the service provider: + +```php tab=Pest +use Laravel\Pennant\Feature; + +test('it can control feature values', function () { + Feature::define('purchase-button', 'seafoam-green'); + + expect(Feature::value('purchase-button'))->toBe('seafoam-green'); +}); +``` + +```php tab=PHPUnit +use Laravel\Pennant\Feature; + +public function test_it_can_control_feature_values() +{ + Feature::define('purchase-button', 'seafoam-green'); + + $this->assertSame('seafoam-green', Feature::value('purchase-button')); +} +``` + +The same approach may be used for class-based features: + +```php tab=Pest +use Laravel\Pennant\Feature; + +test('it can control feature values', function () { + Feature::define(NewApi::class, true); + + expect(Feature::value(NewApi::class))->toBeTrue(); +}); +``` + +```php tab=PHPUnit +use App\Features\NewApi; +use Laravel\Pennant\Feature; + +public function test_it_can_control_feature_values() +{ + Feature::define(NewApi::class, true); + + $this->assertTrue(Feature::value(NewApi::class)); +} +``` + +If your feature is returning a `Lottery` instance, there are a handful of useful [testing helpers available](/docs/{{version}}/helpers#testing-lotteries). + + +#### Store Configuration + +You may configure the store that Pennant will use during testing by defining the `PENNANT_STORE` environment variable in your application's `phpunit.xml` file: + +```xml + + + + + + + + +``` + + +## Adding Custom Pennant Drivers + + +#### Implementing the Driver + +If none of Pennant's existing storage drivers fit your application's needs, you may write your own storage driver. Your custom driver should implement the `Laravel\Pennant\Contracts\Driver` interface: + +```php + [!NOTE] +> Laravel does not ship with a directory to contain your extensions. You are free to place them anywhere you like. In this example, we have created an `Extensions` directory to house the `RedisFeatureDriver`. + + +#### Registering the Driver + +Once your driver has been implemented, you are ready to register it with Laravel. To add additional drivers to Pennant, you may use the `extend` method provided by the `Feature` facade. You should call the `extend` method from the `boot` method of one of your application's [service provider](/docs/{{version}}/providers): + +```php +make('redis'), $app->make('events'), []); + }); + } +} +``` + +Once the driver has been registered, you may use the `redis` driver in your application's `config/pennant.php` configuration file: + +```php +'stores' => [ + + 'redis' => [ + 'driver' => 'redis', + 'connection' => null, + ], + + // ... + +], +``` + + +### Defining Features Externally + +If your driver is a wrapper around a third-party feature flag platform, you will likely define features on the platform rather than using Pennant's `Feature::define` method. If that is the case, your custom driver should also implement the `Laravel\Pennant\Contracts\DefinesFeaturesExternally` interface: + +```php + +## Events + +Pennant dispatches a variety of events that can be useful when tracking feature flags throughout your application. + +### `Laravel\Pennant\Events\FeatureRetrieved` + +This event is dispatched whenever a [feature is checked](#checking-features). This event may be useful for creating and tracking metrics against a feature flag's usage throughout your application. + +### `Laravel\Pennant\Events\FeatureResolved` + +This event is dispatched the first time a feature's value is resolved for a specific scope. + +### `Laravel\Pennant\Events\UnknownFeatureResolved` + +This event is dispatched the first time an unknown feature is resolved for a specific scope. Listening to this event may be useful if you have intended to remove a feature flag but have accidentally left stray references to it throughout your application: + +```php +feature}]."); + }); + } +} +``` + +### `Laravel\Pennant\Events\DynamicallyRegisteringFeatureClass` + +This event is dispatched when a [class-based feature](#class-based-features) is dynamically checked for the first time during a request. + +### `Laravel\Pennant\Events\UnexpectedNullScopeEncountered` + +This event is dispatched when a `null` scope is passed to a feature definition that [doesn't support null](#nullable-scope). + +This situation is handled gracefully and the feature will return `false`. However, if you would like to opt out of this feature's default graceful behavior, you may register a listener for this event in the `boot` method of your application's `AppServiceProvider`: + +```php +use Illuminate\Support\Facades\Log; +use Laravel\Pennant\Events\UnexpectedNullScopeEncountered; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Event::listen(UnexpectedNullScopeEncountered::class, fn () => abort(500)); +} +``` + +### `Laravel\Pennant\Events\FeatureUpdated` + +This event is dispatched when updating a feature for a scope, usually by calling `activate` or `deactivate`. + +### `Laravel\Pennant\Events\FeatureUpdatedForAllScopes` + +This event is dispatched when updating a feature for all scopes, usually by calling `activateForEveryone` or `deactivateForEveryone`. + +### `Laravel\Pennant\Events\FeatureDeleted` + +This event is dispatched when deleting a feature for a scope, usually by calling `forget`. + +### `Laravel\Pennant\Events\FeaturesPurged` + +This event is dispatched when purging specific features. + +### `Laravel\Pennant\Events\AllFeaturesPurged` + +This event is dispatched when purging all features. diff --git a/pint.md b/pint.md new file mode 100644 index 00000000000..353bad01dbf --- /dev/null +++ b/pint.md @@ -0,0 +1,216 @@ +# Laravel Pint + +- [Introduction](#introduction) +- [Installation](#installation) +- [Running Pint](#running-pint) +- [Configuring Pint](#configuring-pint) + - [Presets](#presets) + - [Rules](#rules) + - [Excluding Files / Folders](#excluding-files-or-folders) +- [Continuous Integration](#continuous-integration) + - [GitHub Actions](#running-tests-on-github-actions) + + +## Introduction + +[Laravel Pint](https://github.com/laravel/pint) is an opinionated PHP code style fixer for minimalists. Pint is built on top of [PHP CS Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) and makes it simple to ensure that your code style stays clean and consistent. + +Pint is automatically installed with all new Laravel applications so you may start using it immediately. By default, Pint does not require any configuration and will fix code style issues in your code by following the opinionated coding style of Laravel. + + +## Installation + +Pint is included in recent releases of the Laravel framework, so installation is typically unnecessary. However, for older applications, you may install Laravel Pint via Composer: + +```shell +composer require laravel/pint --dev +``` + + +## Running Pint + +You can instruct Pint to fix code style issues by invoking the `pint` binary that is available in your project's `vendor/bin` directory: + +```shell +./vendor/bin/pint +``` + +If you would like Pint to run in parallel mode (experimental) for improved performance, you may use the `--parallel` option: + +```shell +./vendor/bin/pint --parallel +``` + +Parallel mode also allows you to specify the maximum number of processes to run via the `--max-processes` option. If this option is not provided, Pint will use every available core on your machine: + +```shell +./vendor/bin/pint --parallel --max-processes=4 +``` + +You may also run Pint on specific files or directories: + +```shell +./vendor/bin/pint app/Models + +./vendor/bin/pint app/Models/User.php +``` + +Pint will display a thorough list of all of the files that it updates. You can view even more detail about Pint's changes by providing the `-v` option when invoking Pint: + +```shell +./vendor/bin/pint -v +``` + +If you would like Pint to simply inspect your code for style errors without actually changing the files, you may use the `--test` option. Pint will return a non-zero exit code if any code style errors are found: + +```shell +./vendor/bin/pint --test +``` + +If you would like Pint to only modify the files that differ from the provided branch according to Git, you may use the `--diff=[branch]` option. This can be effectively used in your CI environment (like GitHub actions) to save time by only inspecting new or modified files: + +```shell +./vendor/bin/pint --diff=main +``` + +If you would like Pint to only modify the files that have uncommitted changes according to Git, you may use the `--dirty` option: + +```shell +./vendor/bin/pint --dirty +``` + +If you would like Pint to fix any files with code style errors but also exit with a non-zero exit code if any errors were fixed, you may use the `--repair` option: + +```shell +./vendor/bin/pint --repair +``` + + +## Configuring Pint + +As previously mentioned, Pint does not require any configuration. However, if you wish to customize the presets, rules, or inspected folders, you may do so by creating a `pint.json` file in your project's root directory: + +```json +{ + "preset": "laravel" +} +``` + +In addition, if you wish to use a `pint.json` from a specific directory, you may provide the `--config` option when invoking Pint: + +```shell +./vendor/bin/pint --config vendor/my-company/coding-style/pint.json +``` + + +### Presets + +Presets define a set of rules that can be used to fix code style issues in your code. By default, Pint uses the `laravel` preset, which fixes issues by following the opinionated coding style of Laravel. However, you may specify a different preset by providing the `--preset` option to Pint: + +```shell +./vendor/bin/pint --preset psr12 +``` + +If you wish, you may also set the preset in your project's `pint.json` file: + +```json +{ + "preset": "psr12" +} +``` + +Pint's currently supported presets are: `laravel`, `per`, `psr12`, `symfony`, and `empty`. + + +### Rules + +Rules are style guidelines that Pint will use to fix code style issues in your code. As mentioned above, presets are predefined groups of rules that should be perfect for most PHP projects, so you typically will not need to worry about the individual rules they contain. + +However, if you wish, you may enable or disable specific rules in your `pint.json` file or use the `empty` preset and define the rules from scratch: + +```json +{ + "preset": "laravel", + "rules": { + "simplified_null_return": true, + "array_indentation": false, + "new_with_parentheses": { + "anonymous_class": true, + "named_class": true + } + } +} +``` + +Pint is built on top of [PHP CS Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer). Therefore, you may use any of its rules to fix code style issues in your project: [PHP CS Fixer Configurator](https://mlocati.github.io/php-cs-fixer-configurator). + + +### Excluding Files / Folders + +By default, Pint will inspect all `.php` files in your project except those in the `vendor` directory. If you wish to exclude more folders, you may do so using the `exclude` configuration option: + +```json +{ + "exclude": [ + "my-specific/folder" + ] +} +``` + +If you wish to exclude all files that contain a given name pattern, you may do so using the `notName` configuration option: + +```json +{ + "notName": [ + "*-my-file.php" + ] +} +``` + +If you would like to exclude a file by providing an exact path to the file, you may do so using the `notPath` configuration option: + +```json +{ + "notPath": [ + "path/to/excluded-file.php" + ] +} +``` + + +## Continuous Integration + + +### GitHub Actions + +To automate linting your project with Laravel Pint, you can configure [GitHub Actions](https://github.com/features/actions) to run Pint whenever new code is pushed to GitHub. First, be sure to grant "Read and write permissions" to workflows within GitHub at **Settings > Actions > General > Workflow permissions**. Then, create a `.github/workflows/lint.yml` file with the following content: + +```yaml +name: Fix Code Style + +on: [push] + +jobs: + lint: + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + php: [8.4] + + steps: + - name: Checkout code + uses: actions/checkout@v5 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + tools: pint + + - name: Run Pint + run: pint + + - name: Commit linted files + uses: stefanzweifel/git-auto-commit-action@v6 +``` diff --git a/precognition.md b/precognition.md new file mode 100644 index 00000000000..cb0407f3ab5 --- /dev/null +++ b/precognition.md @@ -0,0 +1,755 @@ +# Precognition + +- [Introduction](#introduction) +- [Live Validation](#live-validation) + - [Using Vue](#using-vue) + - [Using Vue and Inertia](#using-vue-and-inertia) + - [Using React](#using-react) + - [Using React and Inertia](#using-react-and-inertia) + - [Using Alpine and Blade](#using-alpine) + - [Configuring Axios](#configuring-axios) +- [Customizing Validation Rules](#customizing-validation-rules) +- [Handling File Uploads](#handling-file-uploads) +- [Managing Side-Effects](#managing-side-effects) +- [Testing](#testing) + + +## Introduction + +Laravel Precognition allows you to anticipate the outcome of a future HTTP request. One of the primary use cases of Precognition is the ability to provide "live" validation for your frontend JavaScript application without having to duplicate your application's backend validation rules. Precognition pairs especially well with Laravel's Inertia-based [starter kits](/docs/{{version}}/starter-kits). + +When Laravel receives a "precognitive request", it will execute all of the route's middleware and resolve the route's controller dependencies, including validating [form requests](/docs/{{version}}/validation#form-request-validation) - but it will not actually execute the route's controller method. + + +## Live Validation + + +### Using Vue + +Using Laravel Precognition, you can offer live validation experiences to your users without having to duplicate your validation rules in your frontend Vue application. To illustrate how it works, let's build a form for creating new users within our application. + +First, to enable Precognition for a route, the `HandlePrecognitiveRequests` middleware should be added to the route definition. You should also create a [form request](/docs/{{version}}/validation#form-request-validation) to house the route's validation rules: + +```php +use App\Http\Requests\StoreUserRequest; +use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests; + +Route::post('/users', function (StoreUserRequest $request) { + // ... +})->middleware([HandlePrecognitiveRequests::class]); +``` + +Next, you should install the Laravel Precognition frontend helpers for Vue via NPM: + +```shell +npm install laravel-precognition-vue +``` + +With the Laravel Precognition package installed, you can now create a form object using Precognition's `useForm` function, providing the HTTP method (`post`), the target URL (`/users`), and the initial form data. + +Then, to enable live validation, invoke the form's `validate` method on each input's `change` event, providing the input's name: + +```vue + + + +``` + +Now, as the form is filled by the user, Precognition will provide live validation output powered by the validation rules in the route's form request. When the form's inputs are changed, a debounced "precognitive" validation request will be sent to your Laravel application. You may configure the debounce timeout by calling the form's `setValidationTimeout` function: + +```js +form.setValidationTimeout(3000); +``` + +When a validation request is in-flight, the form's `validating` property will be `true`: + +```html +
+ Validating... +
+``` + +Any validation errors returned during a validation request or a form submission will automatically populate the form's `errors` object: + +```html +
+ {{ form.errors.email }} +
+``` + +You can determine if the form has any errors using the form's `hasErrors` property: + +```html +
+ +
+``` + +You may also determine if an input has passed or failed validation by passing the input's name to the form's `valid` and `invalid` functions, respectively: + +```html + + ✅ + + + + ❌ + +``` + +> [!WARNING] +> A form input will only appear as valid or invalid once it has changed and a validation response has been received. + +If you are validating a subset of a form's inputs with Precognition, it can be useful to manually clear errors. You may use the form's `forgetError` function to achieve this: + +```html + +``` + +As we have seen, you can hook into an input's `change` event and validate individual inputs as the user interacts with them; however, you may need to validate inputs that the user has not yet interacted with. This is common when building a "wizard", where you want to validate all visible inputs, whether the user has interacted with them or not, before moving to the next step. + +To do this with Precognition, you should call the `validate` method passing the field names you wish to validate to the `only` configuration key. You may handle the validation result with `onSuccess` or `onValidationError` callbacks: + +```html + +``` + +Of course, you may also execute code in reaction to the response to the form submission. The form's `submit` function returns an Axios request promise. This provides a convenient way to access the response payload, reset the form inputs on successful submission, or handle a failed request: + +```js +const submit = () => form.submit() + .then(response => { + form.reset(); + + alert('User created.'); + }) + .catch(error => { + alert('An error occurred.'); + }); +``` + +You may determine if a form submission request is in-flight by inspecting the form's `processing` property: + +```html + +``` + + +### Using Vue and Inertia + +> [!NOTE] +> If you would like a head start when developing your Laravel application with Vue and Inertia, consider using one of our [starter kits](/docs/{{version}}/starter-kits). Laravel's starter kits provide backend and frontend authentication scaffolding for your new Laravel application. + +Before using Precognition with Vue and Inertia, be sure to review our general documentation on [using Precognition with Vue](#using-vue). When using Vue with Inertia, you will need to install the Inertia compatible Precognition library via NPM: + +```shell +npm install laravel-precognition-vue-inertia +``` + +Once installed, Precognition's `useForm` function will return an Inertia [form helper](https://inertiajs.com/forms#form-helper) augmented with the validation features discussed above. + +The form helper's `submit` method has been streamlined, removing the need to specify the HTTP method or URL. Instead, you may pass Inertia's [visit options](https://inertiajs.com/manual-visits) as the first and only argument. In addition, the `submit` method does not return a Promise as seen in the Vue example above. Instead, you may provide any of Inertia's supported [event callbacks](https://inertiajs.com/manual-visits#event-callbacks) in the visit options given to the `submit` method: + +```vue + +``` + + +### Using React + +Using Laravel Precognition, you can offer live validation experiences to your users without having to duplicate your validation rules in your frontend React application. To illustrate how it works, let's build a form for creating new users within our application. + +First, to enable Precognition for a route, the `HandlePrecognitiveRequests` middleware should be added to the route definition. You should also create a [form request](/docs/{{version}}/validation#form-request-validation) to house the route's validation rules: + +```php +use App\Http\Requests\StoreUserRequest; +use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests; + +Route::post('/users', function (StoreUserRequest $request) { + // ... +})->middleware([HandlePrecognitiveRequests::class]); +``` + +Next, you should install the Laravel Precognition frontend helpers for React via NPM: + +```shell +npm install laravel-precognition-react +``` + +With the Laravel Precognition package installed, you can now create a form object using Precognition's `useForm` function, providing the HTTP method (`post`), the target URL (`/users`), and the initial form data. + +To enable live validation, you should listen to each input's `change` and `blur` event. In the `change` event handler, you should set the form's data with the `setData` function, passing the input's name and new value. Then, in the `blur` event handler invoke the form's `validate` method, providing the input's name: + +```jsx +import { useForm } from 'laravel-precognition-react'; + +export default function Form() { + const form = useForm('post', '/users', { + name: '', + email: '', + }); + + const submit = (e) => { + e.preventDefault(); + + form.submit(); + }; + + return ( +
+ + form.setData('name', e.target.value)} + onBlur={() => form.validate('name')} + /> + {form.invalid('name') &&
{form.errors.name}
} + + + form.setData('email', e.target.value)} + onBlur={() => form.validate('email')} + /> + {form.invalid('email') &&
{form.errors.email}
} + + +
+ ); +}; +``` + +Now, as the form is filled by the user, Precognition will provide live validation output powered by the validation rules in the route's form request. When the form's inputs are changed, a debounced "precognitive" validation request will be sent to your Laravel application. You may configure the debounce timeout by calling the form's `setValidationTimeout` function: + +```js +form.setValidationTimeout(3000); +``` + +When a validation request is in-flight, the form's `validating` property will be `true`: + +```jsx +{form.validating &&
Validating...
} +``` + +Any validation errors returned during a validation request or a form submission will automatically populate the form's `errors` object: + +```jsx +{form.invalid('email') &&
{form.errors.email}
} +``` + +You can determine if the form has any errors using the form's `hasErrors` property: + +```jsx +{form.hasErrors &&
} +``` + +You may also determine if an input has passed or failed validation by passing the input's name to the form's `valid` and `invalid` functions, respectively: + +```jsx +{form.valid('email') && } + +{form.invalid('email') && } +``` + +> [!WARNING] +> A form input will only appear as valid or invalid once it has changed and a validation response has been received. + +If you are validating a subset of a form's inputs with Precognition, it can be useful to manually clear errors. You may use the form's `forgetError` function to achieve this: + +```jsx + { + form.setData('avatar', e.target.files[0]); + + form.forgetError('avatar'); + }} +> +``` + +As we have seen, you can hook into an input's `blur` event and validate individual inputs as the user interacts with them; however, you may need to validate inputs that the user has not yet interacted with. This is common when building a "wizard", where you want to validate all visible inputs, whether the user has interacted with them or not, before moving to the next step. + +To do this with Precognition, you should call the `validate` method passing the field names you wish to validate to the `only` configuration key. You may handle the validation result with `onSuccess` or `onValidationError` callbacks: + +```jsx + +``` + +Of course, you may also execute code in reaction to the response to the form submission. The form's `submit` function returns an Axios request promise. This provides a convenient way to access the response payload, reset the form's inputs on a successful form submission, or handle a failed request: + +```js +const submit = (e) => { + e.preventDefault(); + + form.submit() + .then(response => { + form.reset(); + + alert('User created.'); + }) + .catch(error => { + alert('An error occurred.'); + }); +}; +``` + +You may determine if a form submission request is in-flight by inspecting the form's `processing` property: + +```html + +``` + + +### Using React and Inertia + +> [!NOTE] +> If you would like a head start when developing your Laravel application with React and Inertia, consider using one of our [starter kits](/docs/{{version}}/starter-kits). Laravel's starter kits provide backend and frontend authentication scaffolding for your new Laravel application. + +Before using Precognition with React and Inertia, be sure to review our general documentation on [using Precognition with React](#using-react). When using React with Inertia, you will need to install the Inertia compatible Precognition library via NPM: + +```shell +npm install laravel-precognition-react-inertia +``` + +Once installed, Precognition's `useForm` function will return an Inertia [form helper](https://inertiajs.com/forms#form-helper) augmented with the validation features discussed above. + +The form helper's `submit` method has been streamlined, removing the need to specify the HTTP method or URL. Instead, you may pass Inertia's [visit options](https://inertiajs.com/manual-visits) as the first and only argument. In addition, the `submit` method does not return a Promise as seen in the React example above. Instead, you may provide any of Inertia's supported [event callbacks](https://inertiajs.com/manual-visits#event-callbacks) in the visit options given to the `submit` method: + +```js +import { useForm } from 'laravel-precognition-react-inertia'; + +const form = useForm('post', '/users', { + name: '', + email: '', +}); + +const submit = (e) => { + e.preventDefault(); + + form.submit({ + preserveScroll: true, + onSuccess: () => form.reset(), + }); +}; +``` + + +### Using Alpine and Blade + +Using Laravel Precognition, you can offer live validation experiences to your users without having to duplicate your validation rules in your frontend Alpine application. To illustrate how it works, let's build a form for creating new users within our application. + +First, to enable Precognition for a route, the `HandlePrecognitiveRequests` middleware should be added to the route definition. You should also create a [form request](/docs/{{version}}/validation#form-request-validation) to house the route's validation rules: + +```php +use App\Http\Requests\CreateUserRequest; +use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests; + +Route::post('/users', function (CreateUserRequest $request) { + // ... +})->middleware([HandlePrecognitiveRequests::class]); +``` + +Next, you should install the Laravel Precognition frontend helpers for Alpine via NPM: + +```shell +npm install laravel-precognition-alpine +``` + +Then, register the Precognition plugin with Alpine in your `resources/js/app.js` file: + +```js +import Alpine from 'alpinejs'; +import Precognition from 'laravel-precognition-alpine'; + +window.Alpine = Alpine; + +Alpine.plugin(Precognition); +Alpine.start(); +``` + +With the Laravel Precognition package installed and registered, you can now create a form object using Precognition's `$form` "magic", providing the HTTP method (`post`), the target URL (`/users`), and the initial form data. + +To enable live validation, you should bind the form's data to its relevant input and then listen to each input's `change` event. In the `change` event handler, you should invoke the form's `validate` method, providing the input's name: + +```html +
+ @csrf + + + + + + + + + +
+``` + +Now, as the form is filled by the user, Precognition will provide live validation output powered by the validation rules in the route's form request. When the form's inputs are changed, a debounced "precognitive" validation request will be sent to your Laravel application. You may configure the debounce timeout by calling the form's `setValidationTimeout` function: + +```js +form.setValidationTimeout(3000); +``` + +When a validation request is in-flight, the form's `validating` property will be `true`: + +```html + +``` + +Any validation errors returned during a validation request or a form submission will automatically populate the form's `errors` object: + +```html + +``` + +You can determine if the form has any errors using the form's `hasErrors` property: + +```html + +``` + +You may also determine if an input has passed or failed validation by passing the input's name to the form's `valid` and `invalid` functions, respectively: + +```html + + + +``` + +> [!WARNING] +> A form input will only appear as valid or invalid once it has changed and a validation response has been received. + +As we have seen, you can hook into an input's `change` event and validate individual inputs as the user interacts with them; however, you may need to validate inputs that the user has not yet interacted with. This is common when building a "wizard", where you want to validate all visible inputs, whether the user has interacted with them or not, before moving to the next step. + +To do this with Precognition, you should call the `validate` method passing the field names you wish to validate to the `only` configuration key. You may handle the validation result with `onSuccess` or `onValidationError` callbacks: + +```html + +``` + +You may determine if a form submission request is in-flight by inspecting the form's `processing` property: + +```html + +``` + + +#### Repopulating Old Form Data + +In the user creation example discussed above, we are using Precognition to perform live validation; however, we are performing a traditional server-side form submission to submit the form. So, the form should be populated with any "old" input and validation errors returned from the server-side form submission: + +```html +
+``` + +Alternatively, if you would like to submit the form via XHR you may use the form's `submit` function, which returns an Axios request promise: + +```html + +``` + + +### Configuring Axios + +The Precognition validation libraries use the [Axios](https://github.com/axios/axios) HTTP client to send requests to your application's backend. For convenience, the Axios instance may be customized if required by your application. For example, when using the `laravel-precognition-vue` library, you may add additional request headers to each outgoing request in your application's `resources/js/app.js` file: + +```js +import { client } from 'laravel-precognition-vue'; + +client.axios().defaults.headers.common['Authorization'] = authToken; +``` + +Or, if you already have a configured Axios instance for your application, you may tell Precognition to use that instance instead: + +```js +import Axios from 'axios'; +import { client } from 'laravel-precognition-vue'; + +window.axios = Axios.create() +window.axios.defaults.headers.common['Authorization'] = authToken; + +client.use(window.axios) +``` + +> [!WARNING] +> The Inertia flavored Precognition libraries will only use the configured Axios instance for validation requests. Form submissions will always be sent by Inertia. + + +## Customizing Validation Rules + +It is possible to customize the validation rules executed during a precognitive request by using the request's `isPrecognitive` method. + +For example, on a user creation form, we may want to validate that a password is "uncompromised" only on the final form submission. For precognitive validation requests, we will simply validate that the password is required and has a minimum of 8 characters. Using the `isPrecognitive` method, we can customize the rules defined by our form request: + +```php + [ + 'required', + $this->isPrecognitive() + ? Password::min(8) + : Password::min(8)->uncompromised(), + ], + // ... + ]; + } +} +``` + + +## Handling File Uploads + +By default, Laravel Precognition does not upload or validate files during a precognitive validation request. This ensure that large files are not unnecessarily uploaded multiple times. + +Because of this behavior, you should ensure that your application [customizes the corresponding form request's validation rules](#customizing-validation-rules) to specify the field is only required for full form submissions: + +```php +/** + * Get the validation rules that apply to the request. + * + * @return array + */ +protected function rules() +{ + return [ + 'avatar' => [ + ...$this->isPrecognitive() ? [] : ['required'], + 'image', + 'mimes:jpg,png', + 'dimensions:ratio=3/2', + ], + // ... + ]; +} +``` + +If you would like to include files in every validation request, you may invoke the `validateFiles` function on your client-side form instance: + +```js +form.validateFiles(); +``` + + +## Managing Side-Effects + +When adding the `HandlePrecognitiveRequests` middleware to a route, you should consider if there are any side-effects in _other_ middleware that should be skipped during a precognitive request. + +For example, you may have a middleware that increments the total number of "interactions" each user has with your application, but you may not want precognitive requests to be counted as an interaction. To accomplish this, we may check the request's `isPrecognitive` method before incrementing the interaction count: + +```php +isPrecognitive()) { + Interaction::incrementFor($request->user()); + } + + return $next($request); + } +} +``` + + +## Testing + +If you would like to make precognitive requests in your tests, Laravel's `TestCase` includes a `withPrecognition` helper which will add the `Precognition` request header. + +Additionally, if you would like to assert that a precognitive request was successful, e.g., did not return any validation errors, you may use the `assertSuccessfulPrecognition` method on the response: + +```php tab=Pest +it('validates registration form with precognition', function () { + $response = $this->withPrecognition() + ->post('/register', [ + 'name' => 'Taylor Otwell', + ]); + + $response->assertSuccessfulPrecognition(); + + expect(User::count())->toBe(0); +}); +``` + +```php tab=PHPUnit +public function test_it_validates_registration_form_with_precognition() +{ + $response = $this->withPrecognition() + ->post('/register', [ + 'name' => 'Taylor Otwell', + ]); + + $response->assertSuccessfulPrecognition(); + $this->assertSame(0, User::count()); +} +``` diff --git a/processes.md b/processes.md new file mode 100644 index 00000000000..acd0f392752 --- /dev/null +++ b/processes.md @@ -0,0 +1,657 @@ +# Processes + +- [Introduction](#introduction) +- [Invoking Processes](#invoking-processes) + - [Process Options](#process-options) + - [Process Output](#process-output) + - [Pipelines](#process-pipelines) +- [Asynchronous Processes](#asynchronous-processes) + - [Process IDs and Signals](#process-ids-and-signals) + - [Asynchronous Process Output](#asynchronous-process-output) + - [Asynchronous Process Timeouts](#asynchronous-process-timeouts) +- [Concurrent Processes](#concurrent-processes) + - [Naming Pool Processes](#naming-pool-processes) + - [Pool Process IDs and Signals](#pool-process-ids-and-signals) +- [Testing](#testing) + - [Faking Processes](#faking-processes) + - [Faking Specific Processes](#faking-specific-processes) + - [Faking Process Sequences](#faking-process-sequences) + - [Faking Asynchronous Process Lifecycles](#faking-asynchronous-process-lifecycles) + - [Available Assertions](#available-assertions) + - [Preventing Stray Processes](#preventing-stray-processes) + + +## Introduction + +Laravel provides an expressive, minimal API around the [Symfony Process component](https://symfony.com/doc/current/components/process.html), allowing you to conveniently invoke external processes from your Laravel application. Laravel's process features are focused on the most common use cases and a wonderful developer experience. + + +## Invoking Processes + +To invoke a process, you may use the `run` and `start` methods offered by the `Process` facade. The `run` method will invoke a process and wait for the process to finish executing, while the `start` method is used for asynchronous process execution. We'll examine both approaches within this documentation. First, let's examine how to invoke a basic, synchronous process and inspect its result: + +```php +use Illuminate\Support\Facades\Process; + +$result = Process::run('ls -la'); + +return $result->output(); +``` + +Of course, the `Illuminate\Contracts\Process\ProcessResult` instance returned by the `run` method offers a variety of helpful methods that may be used to inspect the process result: + +```php +$result = Process::run('ls -la'); + +$result->command(); +$result->successful(); +$result->failed(); +$result->output(); +$result->errorOutput(); +$result->exitCode(); +``` + + +#### Throwing Exceptions + +If you have a process result and would like to throw an instance of `Illuminate\Process\Exceptions\ProcessFailedException` if the exit code is greater than zero (thus indicating failure), you may use the `throw` and `throwIf` methods. If the process did not fail, the `ProcessResult` instance will be returned: + +```php +$result = Process::run('ls -la')->throw(); + +$result = Process::run('ls -la')->throwIf($condition); +``` + + +### Process Options + +Of course, you may need to customize the behavior of a process before invoking it. Thankfully, Laravel allows you to tweak a variety of process features, such as the working directory, timeout, and environment variables. + + +#### Working Directory Path + +You may use the `path` method to specify the working directory of the process. If this method is not invoked, the process will inherit the working directory of the currently executing PHP script: + +```php +$result = Process::path(__DIR__)->run('ls -la'); +``` + + +#### Input + +You may provide input via the "standard input" of the process using the `input` method: + +```php +$result = Process::input('Hello World')->run('cat'); +``` + + +#### Timeouts + +By default, processes will throw an instance of `Illuminate\Process\Exceptions\ProcessTimedOutException` after executing for more than 60 seconds. However, you can customize this behavior via the `timeout` method: + +```php +$result = Process::timeout(120)->run('bash import.sh'); +``` + +Or, if you would like to disable the process timeout entirely, you may invoke the `forever` method: + +```php +$result = Process::forever()->run('bash import.sh'); +``` + +The `idleTimeout` method may be used to specify the maximum number of seconds the process may run without returning any output: + +```php +$result = Process::timeout(60)->idleTimeout(30)->run('bash import.sh'); +``` + + +#### Environment Variables + +Environment variables may be provided to the process via the `env` method. The invoked process will also inherit all of the environment variables defined by your system: + +```php +$result = Process::forever() + ->env(['IMPORT_PATH' => __DIR__]) + ->run('bash import.sh'); +``` + +If you wish to remove an inherited environment variable from the invoked process, you may provide that environment variable with a value of `false`: + +```php +$result = Process::forever() + ->env(['LOAD_PATH' => false]) + ->run('bash import.sh'); +``` + + +#### TTY Mode + +The `tty` method may be used to enable TTY mode for your process. TTY mode connects the input and output of the process to the input and output of your program, allowing your process to open an editor like Vim or Nano as a process: + +```php +Process::forever()->tty()->run('vim'); +``` + +> [!WARNING] +> TTY mode is not supported on Windows. + + +### Process Output + +As previously discussed, process output may be accessed using the `output` (stdout) and `errorOutput` (stderr) methods on a process result: + +```php +use Illuminate\Support\Facades\Process; + +$result = Process::run('ls -la'); + +echo $result->output(); +echo $result->errorOutput(); +``` + +However, output may also be gathered in real-time by passing a closure as the second argument to the `run` method. The closure will receive two arguments: the "type" of output (`stdout` or `stderr`) and the output string itself: + +```php +$result = Process::run('ls -la', function (string $type, string $output) { + echo $output; +}); +``` + +Laravel also offers the `seeInOutput` and `seeInErrorOutput` methods, which provide a convenient way to determine if a given string was contained in the process' output: + +```php +if (Process::run('ls -la')->seeInOutput('laravel')) { + // ... +} +``` + + +#### Disabling Process Output + +If your process is writing a significant amount of output that you are not interested in, you can conserve memory by disabling output retrieval entirely. To accomplish this, invoke the `quietly` method while building the process: + +```php +use Illuminate\Support\Facades\Process; + +$result = Process::quietly()->run('bash import.sh'); +``` + + +### Pipelines + +Sometimes you may want to make the output of one process the input of another process. This is often referred to as "piping" the output of a process into another. The `pipe` method provided by the `Process` facades makes this easy to accomplish. The `pipe` method will execute the piped processes synchronously and return the process result for the last process in the pipeline: + +```php +use Illuminate\Process\Pipe; +use Illuminate\Support\Facades\Process; + +$result = Process::pipe(function (Pipe $pipe) { + $pipe->command('cat example.txt'); + $pipe->command('grep -i "laravel"'); +}); + +if ($result->successful()) { + // ... +} +``` + +If you do not need to customize the individual processes that make up the pipeline, you may simply pass an array of command strings to the `pipe` method: + +```php +$result = Process::pipe([ + 'cat example.txt', + 'grep -i "laravel"', +]); +``` + +The process output may be gathered in real-time by passing a closure as the second argument to the `pipe` method. The closure will receive two arguments: the "type" of output (`stdout` or `stderr`) and the output string itself: + +```php +$result = Process::pipe(function (Pipe $pipe) { + $pipe->command('cat example.txt'); + $pipe->command('grep -i "laravel"'); +}, function (string $type, string $output) { + echo $output; +}); +``` + +Laravel also allows you to assign string keys to each process within a pipeline via the `as` method. This key will also be passed to the output closure provided to the `pipe` method, allowing you to determine which process the output belongs to: + +```php +$result = Process::pipe(function (Pipe $pipe) { + $pipe->as('first')->command('cat example.txt'); + $pipe->as('second')->command('grep -i "laravel"'); +}, function (string $type, string $output, string $key) { + // ... +}); +``` + + +## Asynchronous Processes + +While the `run` method invokes processes synchronously, the `start` method may be used to invoke a process asynchronously. This allows your application to continue performing other tasks while the process runs in the background. Once the process has been invoked, you may utilize the `running` method to determine if the process is still running: + +```php +$process = Process::timeout(120)->start('bash import.sh'); + +while ($process->running()) { + // ... +} + +$result = $process->wait(); +``` + +As you may have noticed, you may invoke the `wait` method to wait until the process is finished executing and retrieve the `ProcessResult` instance: + +```php +$process = Process::timeout(120)->start('bash import.sh'); + +// ... + +$result = $process->wait(); +``` + + +### Process IDs and Signals + +The `id` method may be used to retrieve the operating system assigned process ID of the running process: + +```php +$process = Process::start('bash import.sh'); + +return $process->id(); +``` + +You may use the `signal` method to send a "signal" to the running process. A list of predefined signal constants can be found within the [PHP documentation](https://www.php.net/manual/en/pcntl.constants.php): + +```php +$process->signal(SIGUSR2); +``` + + +### Asynchronous Process Output + +While an asynchronous process is running, you may access its entire current output using the `output` and `errorOutput` methods; however, you may utilize the `latestOutput` and `latestErrorOutput` to access the output from the process that has occurred since the output was last retrieved: + +```php +$process = Process::timeout(120)->start('bash import.sh'); + +while ($process->running()) { + echo $process->latestOutput(); + echo $process->latestErrorOutput(); + + sleep(1); +} +``` + +Like the `run` method, output may also be gathered in real-time from asynchronous processes by passing a closure as the second argument to the `start` method. The closure will receive two arguments: the "type" of output (`stdout` or `stderr`) and the output string itself: + +```php +$process = Process::start('bash import.sh', function (string $type, string $output) { + echo $output; +}); + +$result = $process->wait(); +``` + +Instead of waiting until the process has finished, you may use the `waitUntil` method to stop waiting based on the output of the process. Laravel will stop waiting for the process to finish when the closure given to the `waitUntil` method returns `true`: + +```php +$process = Process::start('bash import.sh'); + +$process->waitUntil(function (string $type, string $output) { + return $output === 'Ready...'; +}); +``` + + +### Asynchronous Process Timeouts + +While an asynchronous process is running, you may verify that the process has not timed out using the `ensureNotTimedOut` method. This method will throw a [timeout exception](#timeouts) if the process has timed out: + +```php +$process = Process::timeout(120)->start('bash import.sh'); + +while ($process->running()) { + $process->ensureNotTimedOut(); + + // ... + + sleep(1); +} +``` + + +## Concurrent Processes + +Laravel also makes it a breeze to manage a pool of concurrent, asynchronous processes, allowing you to easily execute many tasks simultaneously. To get started, invoke the `pool` method, which accepts a closure that receives an instance of `Illuminate\Process\Pool`. + +Within this closure, you may define the processes that belong to the pool. Once a process pool is started via the `start` method, you may access the [collection](/docs/{{version}}/collections) of running processes via the `running` method: + +```php +use Illuminate\Process\Pool; +use Illuminate\Support\Facades\Process; + +$pool = Process::pool(function (Pool $pool) { + $pool->path(__DIR__)->command('bash import-1.sh'); + $pool->path(__DIR__)->command('bash import-2.sh'); + $pool->path(__DIR__)->command('bash import-3.sh'); +})->start(function (string $type, string $output, int $key) { + // ... +}); + +while ($pool->running()->isNotEmpty()) { + // ... +} + +$results = $pool->wait(); +``` + +As you can see, you may wait for all of the pool processes to finish executing and resolve their results via the `wait` method. The `wait` method returns an array accessible object that allows you to access the `ProcessResult` instance of each process in the pool by its key: + +```php +$results = $pool->wait(); + +echo $results[0]->output(); +``` + +Or, for convenience, the `concurrently` method may be used to start an asynchronous process pool and immediately wait on its results. This can provide particularly expressive syntax when combined with PHP's array destructuring capabilities: + +```php +[$first, $second, $third] = Process::concurrently(function (Pool $pool) { + $pool->path(__DIR__)->command('ls -la'); + $pool->path(app_path())->command('ls -la'); + $pool->path(storage_path())->command('ls -la'); +}); + +echo $first->output(); +``` + + +### Naming Pool Processes + +Accessing process pool results via a numeric key is not very expressive; therefore, Laravel allows you to assign string keys to each process within a pool via the `as` method. This key will also be passed to the closure provided to the `start` method, allowing you to determine which process the output belongs to: + +```php +$pool = Process::pool(function (Pool $pool) { + $pool->as('first')->command('bash import-1.sh'); + $pool->as('second')->command('bash import-2.sh'); + $pool->as('third')->command('bash import-3.sh'); +})->start(function (string $type, string $output, string $key) { + // ... +}); + +$results = $pool->wait(); + +return $results['first']->output(); +``` + + +### Pool Process IDs and Signals + +Since the process pool's `running` method provides a collection of all invoked processes within the pool, you may easily access the underlying pool process IDs: + +```php +$processIds = $pool->running()->each->id(); +``` + +And, for convenience, you may invoke the `signal` method on a process pool to send a signal to every process within the pool: + +```php +$pool->signal(SIGUSR2); +``` + + +## Testing + +Many Laravel services provide functionality to help you easily and expressively write tests, and Laravel's process service is no exception. The `Process` facade's `fake` method allows you to instruct Laravel to return stubbed / dummy results when processes are invoked. + + +### Faking Processes + +To explore Laravel's ability to fake processes, let's imagine a route that invokes a process: + +```php +use Illuminate\Support\Facades\Process; +use Illuminate\Support\Facades\Route; + +Route::get('/import', function () { + Process::run('bash import.sh'); + + return 'Import complete!'; +}); +``` + +When testing this route, we can instruct Laravel to return a fake, successful process result for every invoked process by calling the `fake` method on the `Process` facade with no arguments. In addition, we can even [assert](#available-assertions) that a given process was "run": + +```php tab=Pest +get('/import'); + + // Simple process assertion... + Process::assertRan('bash import.sh'); + + // Or, inspecting the process configuration... + Process::assertRan(function (PendingProcess $process, ProcessResult $result) { + return $process->command === 'bash import.sh' && + $process->timeout === 60; + }); +}); +``` + +```php tab=PHPUnit +get('/import'); + + // Simple process assertion... + Process::assertRan('bash import.sh'); + + // Or, inspecting the process configuration... + Process::assertRan(function (PendingProcess $process, ProcessResult $result) { + return $process->command === 'bash import.sh' && + $process->timeout === 60; + }); + } +} +``` + +As discussed, invoking the `fake` method on the `Process` facade will instruct Laravel to always return a successful process result with no output. However, you may easily specify the output and exit code for faked processes using the `Process` facade's `result` method: + +```php +Process::fake([ + '*' => Process::result( + output: 'Test output', + errorOutput: 'Test error output', + exitCode: 1, + ), +]); +``` + + +### Faking Specific Processes + +As you may have noticed in a previous example, the `Process` facade allows you to specify different fake results per process by passing an array to the `fake` method. + +The array's keys should represent command patterns that you wish to fake and their associated results. The `*` character may be used as a wildcard character. Any process commands that have not been faked will actually be invoked. You may use the `Process` facade's `result` method to construct stub / fake results for these commands: + +```php +Process::fake([ + 'cat *' => Process::result( + output: 'Test "cat" output', + ), + 'ls *' => Process::result( + output: 'Test "ls" output', + ), +]); +``` + +If you do not need to customize the exit code or error output of a faked process, you may find it more convenient to specify the fake process results as simple strings: + +```php +Process::fake([ + 'cat *' => 'Test "cat" output', + 'ls *' => 'Test "ls" output', +]); +``` + + +### Faking Process Sequences + +If the code you are testing invokes multiple processes with the same command, you may wish to assign a different fake process result to each process invocation. You may accomplish this via the `Process` facade's `sequence` method: + +```php +Process::fake([ + 'ls *' => Process::sequence() + ->push(Process::result('First invocation')) + ->push(Process::result('Second invocation')), +]); +``` + + +### Faking Asynchronous Process Lifecycles + +Thus far, we have primarily discussed faking processes which are invoked synchronously using the `run` method. However, if you are attempting to test code that interacts with asynchronous processes invoked via `start`, you may need a more sophisticated approach to describing your fake processes. + +For example, let's imagine the following route which interacts with an asynchronous process: + +```php +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Route; + +Route::get('/import', function () { + $process = Process::start('bash import.sh'); + + while ($process->running()) { + Log::info($process->latestOutput()); + Log::info($process->latestErrorOutput()); + } + + return 'Done'; +}); +``` + +To properly fake this process, we need to be able to describe how many times the `running` method should return `true`. In addition, we may want to specify multiple lines of output that should be returned in sequence. To accomplish this, we can use the `Process` facade's `describe` method: + +```php +Process::fake([ + 'bash import.sh' => Process::describe() + ->output('First line of standard output') + ->errorOutput('First line of error output') + ->output('Second line of standard output') + ->exitCode(0) + ->iterations(3), +]); +``` + +Let's dig into the example above. Using the `output` and `errorOutput` methods, we may specify multiple lines of output that will be returned in sequence. The `exitCode` method may be used to specify the final exit code of the fake process. Finally, the `iterations` method may be used to specify how many times the `running` method should return `true`. + + +### Available Assertions + +As [previously discussed](#faking-processes), Laravel provides several process assertions for your feature tests. We'll discuss each of these assertions below. + + +#### assertRan + +Assert that a given process was invoked: + +```php +use Illuminate\Support\Facades\Process; + +Process::assertRan('ls -la'); +``` + +The `assertRan` method also accepts a closure, which will receive an instance of a process and a process result, allowing you to inspect the process' configured options. If this closure returns `true`, the assertion will "pass": + +```php +Process::assertRan(fn ($process, $result) => + $process->command === 'ls -la' && + $process->path === __DIR__ && + $process->timeout === 60 +); +``` + +The `$process` passed to the `assertRan` closure is an instance of `Illuminate\Process\PendingProcess`, while the `$result` is an instance of `Illuminate\Contracts\Process\ProcessResult`. + + +#### assertDidntRun + +Assert that a given process was not invoked: + +```php +use Illuminate\Support\Facades\Process; + +Process::assertDidntRun('ls -la'); +``` + +Like the `assertRan` method, the `assertDidntRun` method also accepts a closure, which will receive an instance of a process and a process result, allowing you to inspect the process' configured options. If this closure returns `true`, the assertion will "fail": + +```php +Process::assertDidntRun(fn (PendingProcess $process, ProcessResult $result) => + $process->command === 'ls -la' +); +``` + + +#### assertRanTimes + +Assert that a given process was invoked a given number of times: + +```php +use Illuminate\Support\Facades\Process; + +Process::assertRanTimes('ls -la', times: 3); +``` + +The `assertRanTimes` method also accepts a closure, which will receive an instance of `PendingProcess` and `ProcessResult`, allowing you to inspect the process' configured options. If this closure returns `true` and the process was invoked the specified number of times, the assertion will "pass": + +```php +Process::assertRanTimes(function (PendingProcess $process, ProcessResult $result) { + return $process->command === 'ls -la'; +}, times: 3); +``` + + +### Preventing Stray Processes + +If you would like to ensure that all invoked processes have been faked throughout your individual test or complete test suite, you can call the `preventStrayProcesses` method. After calling this method, any processes that do not have a corresponding fake result will throw an exception rather than starting an actual process: + +```php +use Illuminate\Support\Facades\Process; + +Process::preventStrayProcesses(); + +Process::fake([ + 'ls *' => 'Test output...', +]); + +// Fake response is returned... +Process::run('ls -la'); + +// An exception is thrown... +Process::run('bash import.sh'); +``` diff --git a/prompts.md b/prompts.md new file mode 100644 index 00000000000..2f377a67592 --- /dev/null +++ b/prompts.md @@ -0,0 +1,1050 @@ +# Prompts + +- [Introduction](#introduction) +- [Installation](#installation) +- [Available Prompts](#available-prompts) + - [Text](#text) + - [Textarea](#textarea) + - [Password](#password) + - [Confirm](#confirm) + - [Select](#select) + - [Multi-select](#multiselect) + - [Suggest](#suggest) + - [Search](#search) + - [Multi-search](#multisearch) + - [Pause](#pause) +- [Transforming Input Before Validation](#transforming-input-before-validation) +- [Forms](#forms) +- [Informational Messages](#informational-messages) +- [Tables](#tables) +- [Spin](#spin) +- [Progress Bar](#progress) +- [Clearing the Terminal](#clear) +- [Terminal Considerations](#terminal-considerations) +- [Unsupported Environments and Fallbacks](#fallbacks) +- [Testing](#testing) + + +## Introduction + +[Laravel Prompts](https://github.com/laravel/prompts) is a PHP package for adding beautiful and user-friendly forms to your command-line applications, with browser-like features including placeholder text and validation. + + + +Laravel Prompts is perfect for accepting user input in your [Artisan console commands](/docs/{{version}}/artisan#writing-commands), but it may also be used in any command-line PHP project. + +> [!NOTE] +> Laravel Prompts supports macOS, Linux, and Windows with WSL. For more information, please see our documentation on [unsupported environments & fallbacks](#fallbacks). + + +## Installation + +Laravel Prompts is already included with the latest release of Laravel. + +Laravel Prompts may also be installed in your other PHP projects by using the Composer package manager: + +```shell +composer require laravel/prompts +``` + + +## Available Prompts + + +### Text + +The `text` function will prompt the user with the given question, accept their input, and then return it: + +```php +use function Laravel\Prompts\text; + +$name = text('What is your name?'); +``` + +You may also include placeholder text, a default value, and an informational hint: + +```php +$name = text( + label: 'What is your name?', + placeholder: 'E.g. Taylor Otwell', + default: $user?->name, + hint: 'This will be displayed on your profile.' +); +``` + + +#### Required Values + +If you require a value to be entered, you may pass the `required` argument: + +```php +$name = text( + label: 'What is your name?', + required: true +); +``` + +If you would like to customize the validation message, you may also pass a string: + +```php +$name = text( + label: 'What is your name?', + required: 'Your name is required.' +); +``` + + +#### Additional Validation + +Finally, if you would like to perform additional validation logic, you may pass a closure to the `validate` argument: + +```php +$name = text( + label: 'What is your name?', + validate: fn (string $value) => match (true) { + strlen($value) < 3 => 'The name must be at least 3 characters.', + strlen($value) > 255 => 'The name must not exceed 255 characters.', + default => null + } +); +``` + +The closure will receive the value that has been entered and may return an error message, or `null` if the validation passes. + +Alternatively, you may leverage the power of Laravel's [validator](/docs/{{version}}/validation). To do so, provide an array containing the name of the attribute and the desired validation rules to the `validate` argument: + +```php +$name = text( + label: 'What is your name?', + validate: ['name' => 'required|max:255|unique:users'] +); +``` + + +### Textarea + +The `textarea` function will prompt the user with the given question, accept their input via a multi-line textarea, and then return it: + +```php +use function Laravel\Prompts\textarea; + +$story = textarea('Tell me a story.'); +``` + +You may also include placeholder text, a default value, and an informational hint: + +```php +$story = textarea( + label: 'Tell me a story.', + placeholder: 'This is a story about...', + hint: 'This will be displayed on your profile.' +); +``` + + +#### Required Values + +If you require a value to be entered, you may pass the `required` argument: + +```php +$story = textarea( + label: 'Tell me a story.', + required: true +); +``` + +If you would like to customize the validation message, you may also pass a string: + +```php +$story = textarea( + label: 'Tell me a story.', + required: 'A story is required.' +); +``` + + +#### Additional Validation + +Finally, if you would like to perform additional validation logic, you may pass a closure to the `validate` argument: + +```php +$story = textarea( + label: 'Tell me a story.', + validate: fn (string $value) => match (true) { + strlen($value) < 250 => 'The story must be at least 250 characters.', + strlen($value) > 10000 => 'The story must not exceed 10,000 characters.', + default => null + } +); +``` + +The closure will receive the value that has been entered and may return an error message, or `null` if the validation passes. + +Alternatively, you may leverage the power of Laravel's [validator](/docs/{{version}}/validation). To do so, provide an array containing the name of the attribute and the desired validation rules to the `validate` argument: + +```php +$story = textarea( + label: 'Tell me a story.', + validate: ['story' => 'required|max:10000'] +); +``` + + +### Password + +The `password` function is similar to the `text` function, but the user's input will be masked as they type in the console. This is useful when asking for sensitive information such as passwords: + +```php +use function Laravel\Prompts\password; + +$password = password('What is your password?'); +``` + +You may also include placeholder text and an informational hint: + +```php +$password = password( + label: 'What is your password?', + placeholder: 'password', + hint: 'Minimum 8 characters.' +); +``` + + +#### Required Values + +If you require a value to be entered, you may pass the `required` argument: + +```php +$password = password( + label: 'What is your password?', + required: true +); +``` + +If you would like to customize the validation message, you may also pass a string: + +```php +$password = password( + label: 'What is your password?', + required: 'The password is required.' +); +``` + + +#### Additional Validation + +Finally, if you would like to perform additional validation logic, you may pass a closure to the `validate` argument: + +```php +$password = password( + label: 'What is your password?', + validate: fn (string $value) => match (true) { + strlen($value) < 8 => 'The password must be at least 8 characters.', + default => null + } +); +``` + +The closure will receive the value that has been entered and may return an error message, or `null` if the validation passes. + +Alternatively, you may leverage the power of Laravel's [validator](/docs/{{version}}/validation). To do so, provide an array containing the name of the attribute and the desired validation rules to the `validate` argument: + +```php +$password = password( + label: 'What is your password?', + validate: ['password' => 'min:8'] +); +``` + + +### Confirm + +If you need to ask the user for a "yes or no" confirmation, you may use the `confirm` function. Users may use the arrow keys or press `y` or `n` to select their response. This function will return either `true` or `false`. + +```php +use function Laravel\Prompts\confirm; + +$confirmed = confirm('Do you accept the terms?'); +``` + +You may also include a default value, customized wording for the "Yes" and "No" labels, and an informational hint: + +```php +$confirmed = confirm( + label: 'Do you accept the terms?', + default: false, + yes: 'I accept', + no: 'I decline', + hint: 'The terms must be accepted to continue.' +); +``` + + +#### Requiring "Yes" + +If necessary, you may require your users to select "Yes" by passing the `required` argument: + +```php +$confirmed = confirm( + label: 'Do you accept the terms?', + required: true +); +``` + +If you would like to customize the validation message, you may also pass a string: + +```php +$confirmed = confirm( + label: 'Do you accept the terms?', + required: 'You must accept the terms to continue.' +); +``` + + +### Select + +If you need the user to select from a predefined set of choices, you may use the `select` function: + +```php +use function Laravel\Prompts\select; + +$role = select( + label: 'What role should the user have?', + options: ['Member', 'Contributor', 'Owner'] +); +``` + +You may also specify the default choice and an informational hint: + +```php +$role = select( + label: 'What role should the user have?', + options: ['Member', 'Contributor', 'Owner'], + default: 'Owner', + hint: 'The role may be changed at any time.' +); +``` + +You may also pass an associative array to the `options` argument to have the selected key returned instead of its value: + +```php +$role = select( + label: 'What role should the user have?', + options: [ + 'member' => 'Member', + 'contributor' => 'Contributor', + 'owner' => 'Owner', + ], + default: 'owner' +); +``` + +Up to five options will be displayed before the list begins to scroll. You may customize this by passing the `scroll` argument: + +```php +$role = select( + label: 'Which category would you like to assign?', + options: Category::pluck('name', 'id'), + scroll: 10 +); +``` + + +#### Additional Validation + +Unlike other prompt functions, the `select` function doesn't accept the `required` argument because it is not possible to select nothing. However, you may pass a closure to the `validate` argument if you need to present an option but prevent it from being selected: + +```php +$role = select( + label: 'What role should the user have?', + options: [ + 'member' => 'Member', + 'contributor' => 'Contributor', + 'owner' => 'Owner', + ], + validate: fn (string $value) => + $value === 'owner' && User::where('role', 'owner')->exists() + ? 'An owner already exists.' + : null +); +``` + +If the `options` argument is an associative array, then the closure will receive the selected key, otherwise it will receive the selected value. The closure may return an error message, or `null` if the validation passes. + + +### Multi-select + +If you need the user to be able to select multiple options, you may use the `multiselect` function: + +```php +use function Laravel\Prompts\multiselect; + +$permissions = multiselect( + label: 'What permissions should be assigned?', + options: ['Read', 'Create', 'Update', 'Delete'] +); +``` + +You may also specify default choices and an informational hint: + +```php +use function Laravel\Prompts\multiselect; + +$permissions = multiselect( + label: 'What permissions should be assigned?', + options: ['Read', 'Create', 'Update', 'Delete'], + default: ['Read', 'Create'], + hint: 'Permissions may be updated at any time.' +); +``` + +You may also pass an associative array to the `options` argument to return the selected options' keys instead of their values: + +```php +$permissions = multiselect( + label: 'What permissions should be assigned?', + options: [ + 'read' => 'Read', + 'create' => 'Create', + 'update' => 'Update', + 'delete' => 'Delete', + ], + default: ['read', 'create'] +); +``` + +Up to five options will be displayed before the list begins to scroll. You may customize this by passing the `scroll` argument: + +```php +$categories = multiselect( + label: 'What categories should be assigned?', + options: Category::pluck('name', 'id'), + scroll: 10 +); +``` + + +#### Requiring a Value + +By default, the user may select zero or more options. You may pass the `required` argument to enforce one or more options instead: + +```php +$categories = multiselect( + label: 'What categories should be assigned?', + options: Category::pluck('name', 'id'), + required: true +); +``` + +If you would like to customize the validation message, you may provide a string to the `required` argument: + +```php +$categories = multiselect( + label: 'What categories should be assigned?', + options: Category::pluck('name', 'id'), + required: 'You must select at least one category' +); +``` + + +#### Additional Validation + +You may pass a closure to the `validate` argument if you need to present an option but prevent it from being selected: + +```php +$permissions = multiselect( + label: 'What permissions should the user have?', + options: [ + 'read' => 'Read', + 'create' => 'Create', + 'update' => 'Update', + 'delete' => 'Delete', + ], + validate: fn (array $values) => ! in_array('read', $values) + ? 'All users require the read permission.' + : null +); +``` + +If the `options` argument is an associative array then the closure will receive the selected keys, otherwise it will receive the selected values. The closure may return an error message, or `null` if the validation passes. + + +### Suggest + +The `suggest` function can be used to provide auto-completion for possible choices. The user can still provide any answer, regardless of the auto-completion hints: + +```php +use function Laravel\Prompts\suggest; + +$name = suggest('What is your name?', ['Taylor', 'Dayle']); +``` + +Alternatively, you may pass a closure as the second argument to the `suggest` function. The closure will be called each time the user types an input character. The closure should accept a string parameter containing the user's input so far and return an array of options for auto-completion: + +```php +$name = suggest( + label: 'What is your name?', + options: fn ($value) => collect(['Taylor', 'Dayle']) + ->filter(fn ($name) => Str::contains($name, $value, ignoreCase: true)) +) +``` + +You may also include placeholder text, a default value, and an informational hint: + +```php +$name = suggest( + label: 'What is your name?', + options: ['Taylor', 'Dayle'], + placeholder: 'E.g. Taylor', + default: $user?->name, + hint: 'This will be displayed on your profile.' +); +``` + + +#### Required Values + +If you require a value to be entered, you may pass the `required` argument: + +```php +$name = suggest( + label: 'What is your name?', + options: ['Taylor', 'Dayle'], + required: true +); +``` + +If you would like to customize the validation message, you may also pass a string: + +```php +$name = suggest( + label: 'What is your name?', + options: ['Taylor', 'Dayle'], + required: 'Your name is required.' +); +``` + + +#### Additional Validation + +Finally, if you would like to perform additional validation logic, you may pass a closure to the `validate` argument: + +```php +$name = suggest( + label: 'What is your name?', + options: ['Taylor', 'Dayle'], + validate: fn (string $value) => match (true) { + strlen($value) < 3 => 'The name must be at least 3 characters.', + strlen($value) > 255 => 'The name must not exceed 255 characters.', + default => null + } +); +``` + +The closure will receive the value that has been entered and may return an error message, or `null` if the validation passes. + +Alternatively, you may leverage the power of Laravel's [validator](/docs/{{version}}/validation). To do so, provide an array containing the name of the attribute and the desired validation rules to the `validate` argument: + +```php +$name = suggest( + label: 'What is your name?', + options: ['Taylor', 'Dayle'], + validate: ['name' => 'required|min:3|max:255'] +); +``` + + +### Search + +If you have a lot of options for the user to select from, the `search` function allows the user to type a search query to filter the results before using the arrow keys to select an option: + +```php +use function Laravel\Prompts\search; + +$id = search( + label: 'Search for the user that should receive the mail', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [] +); +``` + +The closure will receive the text that has been typed by the user so far and must return an array of options. If you return an associative array then the selected option's key will be returned, otherwise its value will be returned instead. + +When filtering an array where you intend to return the value, you should use the `array_values` function or the `values` Collection method to ensure the array doesn't become associative: + +```php +$names = collect(['Taylor', 'Abigail']); + +$selected = search( + label: 'Search for the user that should receive the mail', + options: fn (string $value) => $names + ->filter(fn ($name) => Str::contains($name, $value, ignoreCase: true)) + ->values() + ->all(), +); +``` + +You may also include placeholder text and an informational hint: + +```php +$id = search( + label: 'Search for the user that should receive the mail', + placeholder: 'E.g. Taylor Otwell', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [], + hint: 'The user will receive an email immediately.' +); +``` + +Up to five options will be displayed before the list begins to scroll. You may customize this by passing the `scroll` argument: + +```php +$id = search( + label: 'Search for the user that should receive the mail', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [], + scroll: 10 +); +``` + + +#### Additional Validation + +If you would like to perform additional validation logic, you may pass a closure to the `validate` argument: + +```php +$id = search( + label: 'Search for the user that should receive the mail', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [], + validate: function (int|string $value) { + $user = User::findOrFail($value); + + if ($user->opted_out) { + return 'This user has opted-out of receiving mail.'; + } + } +); +``` + +If the `options` closure returns an associative array, then the closure will receive the selected key, otherwise, it will receive the selected value. The closure may return an error message, or `null` if the validation passes. + + +### Multi-search + +If you have a lot of searchable options and need the user to be able to select multiple items, the `multisearch` function allows the user to type a search query to filter the results before using the arrow keys and space-bar to select options: + +```php +use function Laravel\Prompts\multisearch; + +$ids = multisearch( + 'Search for the users that should receive the mail', + fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [] +); +``` + +The closure will receive the text that has been typed by the user so far and must return an array of options. If you return an associative array then the selected options' keys will be returned; otherwise, their values will be returned instead. + +When filtering an array where you intend to return the value, you should use the `array_values` function or the `values` Collection method to ensure the array doesn't become associative: + +```php +$names = collect(['Taylor', 'Abigail']); + +$selected = multisearch( + label: 'Search for the users that should receive the mail', + options: fn (string $value) => $names + ->filter(fn ($name) => Str::contains($name, $value, ignoreCase: true)) + ->values() + ->all(), +); +``` + +You may also include placeholder text and an informational hint: + +```php +$ids = multisearch( + label: 'Search for the users that should receive the mail', + placeholder: 'E.g. Taylor Otwell', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [], + hint: 'The user will receive an email immediately.' +); +``` + +Up to five options will be displayed before the list begins to scroll. You may customize this by providing the `scroll` argument: + +```php +$ids = multisearch( + label: 'Search for the users that should receive the mail', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [], + scroll: 10 +); +``` + + +#### Requiring a Value + +By default, the user may select zero or more options. You may pass the `required` argument to enforce one or more options instead: + +```php +$ids = multisearch( + label: 'Search for the users that should receive the mail', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [], + required: true +); +``` + +If you would like to customize the validation message, you may also provide a string to the `required` argument: + +```php +$ids = multisearch( + label: 'Search for the users that should receive the mail', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [], + required: 'You must select at least one user.' +); +``` + + +#### Additional Validation + +If you would like to perform additional validation logic, you may pass a closure to the `validate` argument: + +```php +$ids = multisearch( + label: 'Search for the users that should receive the mail', + options: fn (string $value) => strlen($value) > 0 + ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() + : [], + validate: function (array $values) { + $optedOut = User::whereLike('name', '%a%')->findMany($values); + + if ($optedOut->isNotEmpty()) { + return $optedOut->pluck('name')->join(', ', ', and ').' have opted out.'; + } + } +); +``` + +If the `options` closure returns an associative array, then the closure will receive the selected keys; otherwise, it will receive the selected values. The closure may return an error message, or `null` if the validation passes. + + +### Pause + +The `pause` function may be used to display informational text to the user and wait for them to confirm their desire to proceed by pressing the Enter / Return key: + +```php +use function Laravel\Prompts\pause; + +pause('Press ENTER to continue.'); +``` + + +## Transforming Input Before Validation + +Sometimes you may want to transform the prompt input before validation takes place. For example, you may wish to remove white space from any provided strings. To accomplish this, many of the prompt functions provide a `transform` argument, which accepts a closure: + +```php +$name = text( + label: 'What is your name?', + transform: fn (string $value) => trim($value), + validate: fn (string $value) => match (true) { + strlen($value) < 3 => 'The name must be at least 3 characters.', + strlen($value) > 255 => 'The name must not exceed 255 characters.', + default => null + } +); +``` + + +## Forms + +Often, you will have multiple prompts that will be displayed in sequence to collect information before performing additional actions. You may use the `form` function to create a grouped set of prompts for the user to complete: + +```php +use function Laravel\Prompts\form; + +$responses = form() + ->text('What is your name?', required: true) + ->password('What is your password?', validate: ['password' => 'min:8']) + ->confirm('Do you accept the terms?') + ->submit(); +``` + +The `submit` method will return a numerically indexed array containing all of the responses from the form's prompts. However, you may provide a name for each prompt via the `name` argument. When a name is provided, the named prompt's response may be accessed via that name: + +```php +use App\Models\User; +use function Laravel\Prompts\form; + +$responses = form() + ->text('What is your name?', required: true, name: 'name') + ->password( + label: 'What is your password?', + validate: ['password' => 'min:8'], + name: 'password' + ) + ->confirm('Do you accept the terms?') + ->submit(); + +User::create([ + 'name' => $responses['name'], + 'password' => $responses['password'], +]); +``` + +The primary benefit of using the `form` function is the ability for the user to return to previous prompts in the form using `CTRL + U`. This allows the user to fix mistakes or alter selections without needing to cancel and restart the entire form. + +If you need more granular control over a prompt in a form, you may invoke the `add` method instead of calling one of the prompt functions directly. The `add` method is passed all previous responses provided by the user: + +```php +use function Laravel\Prompts\form; +use function Laravel\Prompts\outro; +use function Laravel\Prompts\text; + +$responses = form() + ->text('What is your name?', required: true, name: 'name') + ->add(function ($responses) { + return text("How old are you, {$responses['name']}?"); + }, name: 'age') + ->submit(); + +outro("Your name is {$responses['name']} and you are {$responses['age']} years old."); +``` + + +## Informational Messages + +The `note`, `info`, `warning`, `error`, and `alert` functions may be used to display informational messages: + +```php +use function Laravel\Prompts\info; + +info('Package installed successfully.'); +``` + + +## Tables + +The `table` function makes it easy to display multiple rows and columns of data. All you need to do is provide the column names and the data for the table: + +```php +use function Laravel\Prompts\table; + +table( + headers: ['Name', 'Email'], + rows: User::all(['name', 'email'])->toArray() +); +``` + + +## Spin + +The `spin` function displays a spinner along with an optional message while executing a specified callback. It serves to indicate ongoing processes and returns the callback's results upon completion: + +```php +use function Laravel\Prompts\spin; + +$response = spin( + callback: fn () => Http::get('http://example.com/'), + message: 'Fetching response...' +); +``` + +> [!WARNING] +> The `spin` function requires the [PCNTL](https://www.php.net/manual/en/book.pcntl.php) PHP extension to animate the spinner. When this extension is not available, a static version of the spinner will appear instead. + + +## Progress Bars + +For long running tasks, it can be helpful to show a progress bar that informs users how complete the task is. Using the `progress` function, Laravel will display a progress bar and advance its progress for each iteration over a given iterable value: + +```php +use function Laravel\Prompts\progress; + +$users = progress( + label: 'Updating users', + steps: User::all(), + callback: fn ($user) => $this->performTask($user) +); +``` + +The `progress` function acts like a map function and will return an array containing the return value of each iteration of your callback. + +The callback may also accept the `Laravel\Prompts\Progress` instance, allowing you to modify the label and hint on each iteration: + +```php +$users = progress( + label: 'Updating users', + steps: User::all(), + callback: function ($user, $progress) { + $progress + ->label("Updating {$user->name}") + ->hint("Created on {$user->created_at}"); + + return $this->performTask($user); + }, + hint: 'This may take some time.' +); +``` + +Sometimes, you may need more manual control over how a progress bar is advanced. First, define the total number of steps the process will iterate through. Then, advance the progress bar via the `advance` method after processing each item: + +```php +$progress = progress(label: 'Updating users', steps: 10); + +$users = User::all(); + +$progress->start(); + +foreach ($users as $user) { + $this->performTask($user); + + $progress->advance(); +} + +$progress->finish(); +``` + + +## Clearing the Terminal + +The `clear` function may be used to clear the user's terminal: + +```php +use function Laravel\Prompts\clear; + +clear(); +``` + + +## Terminal Considerations + + +#### Terminal Width + +If the length of any label, option, or validation message exceeds the number of "columns" in the user's terminal, it will be automatically truncated to fit. Consider minimizing the length of these strings if your users may be using narrower terminals. A typically safe maximum length is 74 characters to support an 80-character terminal. + + +#### Terminal Height + +For any prompts that accept the `scroll` argument, the configured value will automatically be reduced to fit the height of the user's terminal, including space for a validation message. + + +## Unsupported Environments and Fallbacks + +Laravel Prompts supports macOS, Linux, and Windows with WSL. Due to limitations in the Windows version of PHP, it is not currently possible to use Laravel Prompts on Windows outside of WSL. + +For this reason, Laravel Prompts supports falling back to an alternative implementation such as the [Symfony Console Question Helper](https://symfony.com/doc/current/components/console/helpers/questionhelper.html). + +> [!NOTE] +> When using Laravel Prompts with the Laravel framework, fallbacks for each prompt have been configured for you and will be automatically enabled in unsupported environments. + + +#### Fallback Conditions + +If you are not using Laravel or need to customize when the fallback behavior is used, you may pass a boolean to the `fallbackWhen` static method on the `Prompt` class: + +```php +use Laravel\Prompts\Prompt; + +Prompt::fallbackWhen( + ! $input->isInteractive() || windows_os() || app()->runningUnitTests() +); +``` + + +#### Fallback Behavior + +If you are not using Laravel or need to customize the fallback behavior, you may pass a closure to the `fallbackUsing` static method on each prompt class: + +```php +use Laravel\Prompts\TextPrompt; +use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Style\SymfonyStyle; + +TextPrompt::fallbackUsing(function (TextPrompt $prompt) use ($input, $output) { + $question = (new Question($prompt->label, $prompt->default ?: null)) + ->setValidator(function ($answer) use ($prompt) { + if ($prompt->required && $answer === null) { + throw new \RuntimeException( + is_string($prompt->required) ? $prompt->required : 'Required.' + ); + } + + if ($prompt->validate) { + $error = ($prompt->validate)($answer ?? ''); + + if ($error) { + throw new \RuntimeException($error); + } + } + + return $answer; + }); + + return (new SymfonyStyle($input, $output)) + ->askQuestion($question); +}); +``` + +Fallbacks must be configured individually for each prompt class. The closure will receive an instance of the prompt class and must return an appropriate type for the prompt. + + +## Testing + +Laravel provides a variety of methods for testing that your command displays the expected Prompt messages: + +```php tab=Pest +test('report generation', function () { + $this->artisan('report:generate') + ->expectsPromptsInfo('Welcome to the application!') + ->expectsPromptsWarning('This action cannot be undone') + ->expectsPromptsError('Something went wrong') + ->expectsPromptsAlert('Important notice!') + ->expectsPromptsIntro('Starting process...') + ->expectsPromptsOutro('Process completed!') + ->expectsPromptsTable( + headers: ['Name', 'Email'], + rows: [ + ['Taylor Otwell', 'taylor@example.com'], + ['Jason Beggs', 'jason@example.com'], + ] + ) + ->assertExitCode(0); +}); +``` + +```php tab=PHPUnit +public function test_report_generation(): void +{ + $this->artisan('report:generate') + ->expectsPromptsInfo('Welcome to the application!') + ->expectsPromptsWarning('This action cannot be undone') + ->expectsPromptsError('Something went wrong') + ->expectsPromptsAlert('Important notice!') + ->expectsPromptsIntro('Starting process...') + ->expectsPromptsOutro('Process completed!') + ->expectsPromptsTable( + headers: ['Name', 'Email'], + rows: [ + ['Taylor Otwell', 'taylor@example.com'], + ['Jason Beggs', 'jason@example.com'], + ] + ) + ->assertExitCode(0); +} +``` diff --git a/providers.md b/providers.md index 8fc544bfd09..7928f11ba54 100644 --- a/providers.md +++ b/providers.md @@ -14,18 +14,19 @@ Service providers are the central place of all Laravel application bootstrapping But, what do we mean by "bootstrapped"? In general, we mean **registering** things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application. -If you open the `config/app.php` file included with Laravel, you will see a `providers` array. These are all of the service provider classes that will be loaded for your application. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel components, such as the mailer, queue, cache, and others. Many of these providers are "deferred" providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed. +Laravel uses dozens of service providers internally to bootstrap its core services, such as the mailer, queue, cache, and others. Many of these providers are "deferred" providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed. -In this overview, you will learn how to write your own service providers and register them with your Laravel application. +All user-defined service providers are registered in the `bootstrap/providers.php` file. In the following documentation, you will learn how to write your own service providers and register them with your Laravel application. -> {tip} If you would like to learn more about how Laravel handles requests and works internally, check out our documentation on the Laravel [request lifecycle](/docs/{{version}}/lifecycle). +> [!NOTE] +> If you would like to learn more about how Laravel handles requests and works internally, check out our documentation on the Laravel [request lifecycle](/docs/{{version}}/lifecycle). ## Writing Service Providers All service providers extend the `Illuminate\Support\ServiceProvider` class. Most service providers contain a `register` and a `boot` method. Within the `register` method, you should **only bind things into the [service container](/docs/{{version}}/container)**. You should never attempt to register any event listeners, routes, or any other piece of functionality within the `register` method. -The Artisan CLI can generate a new provider via the `make:provider` command: +The Artisan CLI can generate a new provider via the `make:provider` command. Laravel will automatically register your new provider in your application's `bootstrap/providers.php` file: ```shell php artisan make:provider RiakServiceProvider @@ -38,127 +39,140 @@ As mentioned previously, within the `register` method, you should only bind thin Let's take a look at a basic service provider. Within any of your service provider methods, you always have access to the `$app` property which provides access to the service container: - app->singleton(Connection::class, function ($app) { - return new Connection(config('riak')); - }); - } + $this->app->singleton(Connection::class, function (Application $app) { + return new Connection(config('riak')); + }); } +} +``` This service provider only defines a `register` method, and uses that method to define an implementation of `App\Services\Riak\Connection` in the service container. If you're not yet familiar with Laravel's service container, check out [its documentation](/docs/{{version}}/container). -#### The `bindings` And `singletons` Properties +#### The `bindings` and `singletons` Properties If your service provider registers many simple bindings, you may wish to use the `bindings` and `singletons` properties instead of manually registering each container binding. When the service provider is loaded by the framework, it will automatically check for these properties and register their bindings: - DigitalOceanServerProvider::class, - ]; - - /** - * All of the container singletons that should be registered. - * - * @var array - */ - public $singletons = [ - DowntimeNotifier::class => PingdomDowntimeNotifier::class, - ServerProvider::class => ServerToolsProvider::class, - ]; - } +class AppServiceProvider extends ServiceProvider +{ + /** + * All of the container bindings that should be registered. + * + * @var array + */ + public $bindings = [ + ServerProvider::class => DigitalOceanServerProvider::class, + ]; + + /** + * All of the container singletons that should be registered. + * + * @var array + */ + public $singletons = [ + DowntimeNotifier::class => PingdomDowntimeNotifier::class, + ServerProvider::class => ServerToolsProvider::class, + ]; +} +``` ### The Boot Method So, what if we need to register a [view composer](/docs/{{version}}/views#view-composers) within our service provider? This should be done within the `boot` method. **This method is called after all other service providers have been registered**, meaning you have access to all other services that have been registered by the framework: - #### Boot Method Dependency Injection You may type-hint dependencies for your service provider's `boot` method. The [service container](/docs/{{version}}/container) will automatically inject any dependencies you need: - use Illuminate\Contracts\Routing\ResponseFactory; - - /** - * Bootstrap any application services. - * - * @param \Illuminate\Contracts\Routing\ResponseFactory $response - * @return void - */ - public function boot(ResponseFactory $response) - { - $response->macro('serialized', function ($value) { - // - }); - } +```php +use Illuminate\Contracts\Routing\ResponseFactory; + +/** + * Bootstrap any application services. + */ +public function boot(ResponseFactory $response): void +{ + $response->macro('serialized', function (mixed $value) { + // ... + }); +} +``` ## Registering Providers -All service providers are registered in the `config/app.php` configuration file. This file contains a `providers` array where you can list the class names of your service providers. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel components, such as the mailer, queue, cache, and others. +All service providers are registered in the `bootstrap/providers.php` configuration file. This file returns an array that contains the class names of your application's service providers: + +```php + [ - // Other Service Providers +When you invoke the `make:provider` Artisan command, Laravel will automatically add the generated provider to the `bootstrap/providers.php` file. However, if you have manually created the provider class, you should manually add the provider class to the array: - App\Providers\ComposerServiceProvider::class, - ], +```php + ## Deferred Providers @@ -169,35 +183,36 @@ Laravel compiles and stores a list of all of the services supplied by deferred s To defer the loading of a provider, implement the `\Illuminate\Contracts\Support\DeferrableProvider` interface and define a `provides` method. The `provides` method should return the service container bindings registered by the provider: - app->singleton(Connection::class, function (Application $app) { + return new Connection($app['config']['riak']); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides(): array { - /** - * Register any application services. - * - * @return void - */ - public function register() - { - $this->app->singleton(Connection::class, function ($app) { - return new Connection($app['config']['riak']); - }); - } - - /** - * Get the services provided by the provider. - * - * @return array - */ - public function provides() - { - return [Connection::class]; - } + return [Connection::class]; } +} +``` diff --git a/pulse.md b/pulse.md new file mode 100644 index 00000000000..177b6911d93 --- /dev/null +++ b/pulse.md @@ -0,0 +1,830 @@ +# Laravel Pulse + +- [Introduction](#introduction) +- [Installation](#installation) + - [Configuration](#configuration) +- [Dashboard](#dashboard) + - [Authorization](#dashboard-authorization) + - [Customization](#dashboard-customization) + - [Resolving Users](#dashboard-resolving-users) + - [Cards](#dashboard-cards) +- [Capturing Entries](#capturing-entries) + - [Recorders](#recorders) + - [Filtering](#filtering) +- [Performance](#performance) + - [Using a Different Database](#using-a-different-database) + - [Redis Ingest](#ingest) + - [Sampling](#sampling) + - [Trimming](#trimming) + - [Handling Pulse Exceptions](#pulse-exceptions) +- [Custom Cards](#custom-cards) + - [Card Components](#custom-card-components) + - [Styling](#custom-card-styling) + - [Data Capture and Aggregation](#custom-card-data) + + +## Introduction + +[Laravel Pulse](https://github.com/laravel/pulse) delivers at-a-glance insights into your application's performance and usage. With Pulse, you can track down bottlenecks like slow jobs and endpoints, find your most active users, and more. + +For in-depth debugging of individual events, check out [Laravel Telescope](/docs/{{version}}/telescope). + + +## Installation + +> [!WARNING] +> Pulse's first-party storage implementation currently requires a MySQL, MariaDB, or PostgreSQL database. If you are using a different database engine, you will need a separate MySQL, MariaDB, or PostgreSQL database for your Pulse data. + +You may install Pulse using the Composer package manager: + +```shell +composer require laravel/pulse +``` + +Next, you should publish the Pulse configuration and migration files using the `vendor:publish` Artisan command: + +```shell +php artisan vendor:publish --provider="Laravel\Pulse\PulseServiceProvider" +``` + +Finally, you should run the `migrate` command in order to create the tables needed to store Pulse's data: + +```shell +php artisan migrate +``` + +Once Pulse's database migrations have been run, you may access the Pulse dashboard via the `/pulse` route. + +> [!NOTE] +> If you do not want to store Pulse data in your application's primary database, you may [specify a dedicated database connection](#using-a-different-database). + + +### Configuration + +Many of Pulse's configuration options can be controlled using environment variables. To see the available options, register new recorders, or configure advanced options, you may publish the `config/pulse.php` configuration file: + +```shell +php artisan vendor:publish --tag=pulse-config +``` + + +## Dashboard + + +### Authorization + +The Pulse dashboard may be accessed via the `/pulse` route. By default, you will only be able to access this dashboard in the `local` environment, so you will need to configure authorization for your production environments by customizing the `'viewPulse'` authorization gate. You can accomplish this within your application's `app/Providers/AppServiceProvider.php` file: + +```php +use App\Models\User; +use Illuminate\Support\Facades\Gate; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Gate::define('viewPulse', function (User $user) { + return $user->isAdmin(); + }); + + // ... +} +``` + + +### Customization + +The Pulse dashboard cards and layout may be configured by publishing the dashboard view. The dashboard view will be published to `resources/views/vendor/pulse/dashboard.blade.php`: + +```shell +php artisan vendor:publish --tag=pulse-dashboard +``` + +The dashboard is powered by [Livewire](https://livewire.laravel.com/), and allows you to customize the cards and layout without needing to rebuild any JavaScript assets. + +Within this file, the `` component is responsible for rendering the dashboard and provides a grid layout for the cards. If you would like the dashboard to span the full width of the screen, you may provide the `full-width` prop to the component: + +```blade + + ... + +``` + +By default, the `` component will create a 12 column grid, but you may customize this using the `cols` prop: + +```blade + + ... + +``` + +Each card accepts a `cols` and `rows` prop to control the space and positioning: + +```blade + +``` + +Most cards also accept an `expand` prop to show the full card instead of scrolling: + +```blade + +``` + + +### Resolving Users + +For cards that display information about your users, such as the Application Usage card, Pulse will only record the user's ID. When rendering the dashboard, Pulse will resolve the `name` and `email` fields from your default `Authenticatable` model and display avatars using the Gravatar web service. + +You may customize the fields and avatar by invoking the `Pulse::user` method within your application's `App\Providers\AppServiceProvider` class. + +The `user` method accepts a closure which will receive the `Authenticatable` model to be displayed and should return an array containing `name`, `extra`, and `avatar` information for the user: + +```php +use Laravel\Pulse\Facades\Pulse; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Pulse::user(fn ($user) => [ + 'name' => $user->name, + 'extra' => $user->email, + 'avatar' => $user->avatar_url, + ]); + + // ... +} +``` + +> [!NOTE] +> You may completely customize how the authenticated user is captured and retrieved by implementing the `Laravel\Pulse\Contracts\ResolvesUsers` contract and binding it in Laravel's [service container](/docs/{{version}}/container#binding-a-singleton). + + +### Cards + + +#### Servers + +The `` card displays system resource usage for all servers running the `pulse:check` command. Please refer to the documentation regarding the [servers recorder](#servers-recorder) for more information on system resource reporting. + +If you replace a server in your infrastructure, you may wish to stop displaying the inactive server in the Pulse dashboard after a given duration. You may accomplish this using the `ignore-after` prop, which accepts the number of seconds after which inactive servers should be removed from the Pulse dashboard. Alternatively, you may provide a relative time formatted string, such as `1 hour` or `3 days and 1 hour`: + +```blade + +``` + + +#### Application Usage + +The `` card displays the top 10 users making requests to your application, dispatching jobs, and experiencing slow requests. + +If you wish to view all usage metrics on screen at the same time, you may include the card multiple times and specify the `type` attribute: + +```blade + + + +``` + +To learn how to customize how Pulse retrieves and displays user information, consult our documentation on [resolving users](#dashboard-resolving-users). + +> [!NOTE] +> If your application receives a lot of requests or dispatches a lot of jobs, you may wish to enable [sampling](#sampling). See the [user requests recorder](#user-requests-recorder), [user jobs recorder](#user-jobs-recorder), and [slow jobs recorder](#slow-jobs-recorder) documentation for more information. + + +#### Exceptions + +The `` card shows the frequency and recency of exceptions occurring in your application. By default, exceptions are grouped based on the exception class and location where it occurred. See the [exceptions recorder](#exceptions-recorder) documentation for more information. + + +#### Queues + +The `` card shows the throughput of the queues in your application, including the number of jobs queued, processing, processed, released, and failed. See the [queues recorder](#queues-recorder) documentation for more information. + + +#### Slow Requests + +The `` card shows incoming requests to your application that exceed the configured threshold, which is 1,000ms by default. See the [slow requests recorder](#slow-requests-recorder) documentation for more information. + + +#### Slow Jobs + +The `` card shows the queued jobs in your application that exceed the configured threshold, which is 1,000ms by default. See the [slow jobs recorder](#slow-jobs-recorder) documentation for more information. + + +#### Slow Queries + +The `` card shows the database queries in your application that exceed the configured threshold, which is 1,000ms by default. + +By default, slow queries are grouped based on the SQL query (without bindings) and the location where it occurred, but you may choose to not capture the location if you wish to group solely on the SQL query. + +If you encounter rendering performance issues due to extremely large SQL queries receiving syntax highlighting, you may disable highlighting by adding the `without-highlighting` prop: + +```blade + +``` + +See the [slow queries recorder](#slow-queries-recorder) documentation for more information. + + +#### Slow Outgoing Requests + +The `` card shows outgoing requests made using Laravel's [HTTP client](/docs/{{version}}/http-client) that exceed the configured threshold, which is 1,000ms by default. + +By default, entries will be grouped by the full URL. However, you may wish to normalize or group similar outgoing requests using regular expressions. See the [slow outgoing requests recorder](#slow-outgoing-requests-recorder) documentation for more information. + + +#### Cache + +The `` card shows the cache hit and miss statistics for your application, both globally and for individual keys. + +By default, entries will be grouped by key. However, you may wish to normalize or group similar keys using regular expressions. See the [cache interactions recorder](#cache-interactions-recorder) documentation for more information. + + +## Capturing Entries + +Most Pulse recorders will automatically capture entries based on framework events dispatched by Laravel. However, the [servers recorder](#servers-recorder) and some third-party cards must poll for information regularly. To use these cards, you must run the `pulse:check` daemon on all of your individual application servers: + +```php +php artisan pulse:check +``` + +> [!NOTE] +> To keep the `pulse:check` process running permanently in the background, you should use a process monitor such as Supervisor to ensure that the command does not stop running. + +As the `pulse:check` command is a long-lived process, it will not see changes to your codebase without being restarted. You should gracefully restart the command by calling the `pulse:restart` command during your application's deployment process: + +```shell +php artisan pulse:restart +``` + +> [!NOTE] +> Pulse uses the [cache](/docs/{{version}}/cache) to store restart signals, so you should verify that a cache driver is properly configured for your application before using this feature. + + +### Recorders + +Recorders are responsible for capturing entries from your application to be recorded in the Pulse database. Recorders are registered and configured in the `recorders` section of the [Pulse configuration file](#configuration). + + +#### Cache Interactions + +The `CacheInteractions` recorder captures information about the [cache](/docs/{{version}}/cache) hits and misses occurring in your application for display on the [Cache](#cache-card) card. + +You may optionally adjust the [sample rate](#sampling) and ignored key patterns. + +You may also configure key grouping so that similar keys are grouped as a single entry. For example, you may wish to remove unique IDs from keys caching the same type of information. Groups are configured using a regular expression to "find and replace" parts of the key. An example is included in the configuration file: + +```php +Recorders\CacheInteractions::class => [ + // ... + 'groups' => [ + // '/:\d+/' => ':*', + ], +], +``` + +The first pattern that matches will be used. If no patterns match, then the key will be captured as-is. + + +#### Exceptions + +The `Exceptions` recorder captures information about reportable exceptions occurring in your application for display on the [Exceptions](#exceptions-card) card. + +You may optionally adjust the [sample rate](#sampling) and ignored exception patterns. You may also configure whether to capture the location that the exception originated from. The captured location will be displayed on the Pulse dashboard which can help to track down the exception origin; however, if the same exception occurs in multiple locations then it will appear multiple times for each unique location. + + +#### Queues + +The `Queues` recorder captures information about your application's queues for display on the [Queues](#queues-card). + +You may optionally adjust the [sample rate](#sampling) and ignored jobs patterns. + + +#### Slow Jobs + +The `SlowJobs` recorder captures information about slow jobs occurring in your application for display on the [Slow Jobs](#slow-jobs-recorder) card. + +You may optionally adjust the slow job threshold, [sample rate](#sampling), and ignored job patterns. + +You may have some jobs that you expect to take longer than others. In those cases, you may configure per-job thresholds: + +```php +Recorders\SlowJobs::class => [ + // ... + 'threshold' => [ + '#^App\\Jobs\\GenerateYearlyReports$#' => 5000, + 'default' => env('PULSE_SLOW_JOBS_THRESHOLD', 1000), + ], +], +``` + +If no regular expression patterns match the job's classname, then the `'default'` value will be used. + + +#### Slow Outgoing Requests + +The `SlowOutgoingRequests` recorder captures information about outgoing HTTP requests made using Laravel's [HTTP client](/docs/{{version}}/http-client) that exceed the configured threshold for display on the [Slow Outgoing Requests](#slow-outgoing-requests-card) card. + +You may optionally adjust the slow outgoing request threshold, [sample rate](#sampling), and ignored URL patterns. + +You may have some outgoing requests that you expect to take longer than others. In those cases, you may configure per-request thresholds: + +```php +Recorders\SlowOutgoingRequests::class => [ + // ... + 'threshold' => [ + '#backup.zip$#' => 5000, + 'default' => env('PULSE_SLOW_OUTGOING_REQUESTS_THRESHOLD', 1000), + ], +], +``` + +If no regular expression patterns match the request's URL, then the `'default'` value will be used. + +You may also configure URL grouping so that similar URLs are grouped as a single entry. For example, you may wish to remove unique IDs from URL paths or group by domain only. Groups are configured using a regular expression to "find and replace" parts of the URL. Some examples are included in the configuration file: + +```php +Recorders\SlowOutgoingRequests::class => [ + // ... + 'groups' => [ + // '#^https://api\.github\.com/repos/.*$#' => 'api.github.com/repos/*', + // '#^https?://([^/]*).*$#' => '\1', + // '#/\d+#' => '/*', + ], +], +``` + +The first pattern that matches will be used. If no patterns match, then the URL will be captured as-is. + + +#### Slow Queries + +The `SlowQueries` recorder captures any database queries in your application that exceed the configured threshold for display on the [Slow Queries](#slow-queries-card) card. + +You may optionally adjust the slow query threshold, [sample rate](#sampling), and ignored query patterns. You may also configure whether to capture the query location. The captured location will be displayed on the Pulse dashboard which can help to track down the query origin; however, if the same query is made in multiple locations then it will appear multiple times for each unique location. + +You may have some queries that you expect to take longer than others. In those cases, you may configure per-query thresholds: + +```php +Recorders\SlowQueries::class => [ + // ... + 'threshold' => [ + '#^insert into `yearly_reports`#' => 5000, + 'default' => env('PULSE_SLOW_QUERIES_THRESHOLD', 1000), + ], +], +``` + +If no regular expression patterns match the query's SQL, then the `'default'` value will be used. + + +#### Slow Requests + +The `Requests` recorder captures information about requests made to your application for display on the [Slow Requests](#slow-requests-card) and [Application Usage](#application-usage-card) cards. + +You may optionally adjust the slow route threshold, [sample rate](#sampling), and ignored paths. + +You may have some requests that you expect to take longer than others. In those cases, you may configure per-request thresholds: + +```php +Recorders\SlowRequests::class => [ + // ... + 'threshold' => [ + '#^/admin/#' => 5000, + 'default' => env('PULSE_SLOW_REQUESTS_THRESHOLD', 1000), + ], +], +``` + +If no regular expression patterns match the request's URL, then the `'default'` value will be used. + + +#### Servers + +The `Servers` recorder captures CPU, memory, and storage usage of the servers that power your application for display on the [Servers](#servers-card) card. This recorder requires the [pulse:check command](#capturing-entries) to be running on each of the servers you wish to monitor. + +Each reporting server must have a unique name. By default, Pulse will use the value returned by PHP's `gethostname` function. If you wish to customize this, you may set the `PULSE_SERVER_NAME` environment variable: + +```env +PULSE_SERVER_NAME=load-balancer +``` + +The Pulse configuration file also allows you to customize the directories that are monitored. + + +#### User Jobs + +The `UserJobs` recorder captures information about the users dispatching jobs in your application for display on the [Application Usage](#application-usage-card) card. + +You may optionally adjust the [sample rate](#sampling) and ignored job patterns. + + +#### User Requests + +The `UserRequests` recorder captures information about the users making requests to your application for display on the [Application Usage](#application-usage-card) card. + +You may optionally adjust the [sample rate](#sampling) and ignored URL patterns. + + +### Filtering + +As we have seen, many [recorders](#recorders) offer the ability to, via configuration, "ignore" incoming entries based on their value, such as a request's URL. But, sometimes it may be useful to filter out records based on other factors, such as the currently authenticated user. To filter out these records, you may pass a closure to Pulse's `filter` method. Typically, the `filter` method should be invoked within the `boot` method of your application's `AppServiceProvider`: + +```php +use Illuminate\Support\Facades\Auth; +use Laravel\Pulse\Entry; +use Laravel\Pulse\Facades\Pulse; +use Laravel\Pulse\Value; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Pulse::filter(function (Entry|Value $entry) { + return Auth::user()->isNotAdmin(); + }); + + // ... +} +``` + + +## Performance + +Pulse has been designed to drop into an existing application without requiring any additional infrastructure. However, for high-traffic applications, there are several ways of removing any impact Pulse may have on your application's performance. + + +### Using a Different Database + +For high-traffic applications, you may prefer to use a dedicated database connection for Pulse to avoid impacting your application database. + +You may customize the [database connection](/docs/{{version}}/database#configuration) used by Pulse by setting the `PULSE_DB_CONNECTION` environment variable. + +```env +PULSE_DB_CONNECTION=pulse +``` + + +### Redis Ingest + +> [!WARNING] +> The Redis Ingest requires Redis 6.2 or greater and `phpredis` or `predis` as the application's configured Redis client driver. + +By default, Pulse will store entries directly to the [configured database connection](#using-a-different-database) after the HTTP response has been sent to the client or a job has been processed; however, you may use Pulse's Redis ingest driver to send entries to a Redis stream instead. This can be enabled by configuring the `PULSE_INGEST_DRIVER` environment variable: + +```ini +PULSE_INGEST_DRIVER=redis +``` + +Pulse will use your default [Redis connection](/docs/{{version}}/redis#configuration) by default, but you may customize this via the `PULSE_REDIS_CONNECTION` environment variable: + +```ini +PULSE_REDIS_CONNECTION=pulse +``` + +> [!WARNING] +> When using the Redis ingest driver, your Pulse installation should always use a different Redis connection than your Redis powered queue, if applicable. + +When using the Redis ingest, you will need to run the `pulse:work` command to monitor the stream and move entries from Redis into Pulse's database tables. + +```php +php artisan pulse:work +``` + +> [!NOTE] +> To keep the `pulse:work` process running permanently in the background, you should use a process monitor such as Supervisor to ensure that the Pulse worker does not stop running. + +As the `pulse:work` command is a long-lived process, it will not see changes to your codebase without being restarted. You should gracefully restart the command by calling the `pulse:restart` command during your application's deployment process: + +```shell +php artisan pulse:restart +``` + +> [!NOTE] +> Pulse uses the [cache](/docs/{{version}}/cache) to store restart signals, so you should verify that a cache driver is properly configured for your application before using this feature. + + +### Sampling + +By default, Pulse will capture every relevant event that occurs in your application. For high-traffic applications, this can result in needing to aggregate millions of database rows in the dashboard, especially for longer time periods. + +You may instead choose to enable "sampling" on certain Pulse data recorders. For example, setting the sample rate to `0.1` on the [User Requests](#user-requests-recorder) recorder will mean that you only record approximately 10% of the requests to your application. In the dashboard, the values will be scaled up and prefixed with a `~` to indicate that they are an approximation. + +In general, the more entries you have for a particular metric, the lower you can safely set the sample rate without sacrificing too much accuracy. + + +### Trimming + +Pulse will automatically trim its stored entries once they are outside of the dashboard window. Trimming occurs when ingesting data using a lottery system which may be customized in the Pulse [configuration file](#configuration). + + +### Handling Pulse Exceptions + +If an exception occurs while capturing Pulse data, such as being unable to connect to the storage database, Pulse will silently fail to avoid impacting your application. + +If you wish to customize how these exceptions are handled, you may provide a closure to the `handleExceptionsUsing` method: + +```php +use Laravel\Pulse\Facades\Pulse; +use Illuminate\Support\Facades\Log; + +Pulse::handleExceptionsUsing(function ($e) { + Log::debug('An exception happened in Pulse', [ + 'message' => $e->getMessage(), + 'stack' => $e->getTraceAsString(), + ]); +}); +``` + + +## Custom Cards + +Pulse allows you to build custom cards to display data relevant to your application's specific needs. Pulse uses [Livewire](https://livewire.laravel.com), so you may want to [review its documentation](https://livewire.laravel.com/docs) before building your first custom card. + + +### Card Components + +Creating a custom card in Laravel Pulse starts with extending the base `Card` Livewire component and defining a corresponding view: + +```php +namespace App\Livewire\Pulse; + +use Laravel\Pulse\Livewire\Card; +use Livewire\Attributes\Lazy; + +#[Lazy] +class TopSellers extends Card +{ + public function render() + { + return view('livewire.pulse.top-sellers'); + } +} +``` + +When using Livewire's [lazy loading](https://livewire.laravel.com/docs/lazy) feature, The `Card` component will automatically provide a placeholder that respects the `cols` and `rows` attributes passed to your component. + +When writing your Pulse card's corresponding view, you may leverage Pulse's Blade components for a consistent look and feel: + +```blade + + + + ... + + + + + ... + + +``` + +The `$cols`, `$rows`, `$class`, and `$expand` variables should be passed to their respective Blade components so the card layout may be customized from the dashboard view. You may also wish to include the `wire:poll.5s=""` attribute in your view to have the card automatically update. + +Once you have defined your Livewire component and template, the card may be included in your [dashboard view](#dashboard-customization): + +```blade + + ... + + + +``` + +> [!NOTE] +> If your card is included in a package, you will need to register the component with Livewire using the `Livewire::component` method. + + +### Styling + +If your card requires additional styling beyond the classes and components included with Pulse, there are a few options for including custom CSS for your cards. + + +#### Laravel Vite Integration + +If your custom card lives within your application's code base and you are using Laravel's [Vite integration](/docs/{{version}}/vite), you may update your `vite.config.js` file to include a dedicated CSS entry point for your card: + +```js +laravel({ + input: [ + 'resources/css/pulse/top-sellers.css', + // ... + ], +}), +``` + +You may then use the `@vite` Blade directive in your [dashboard view](#dashboard-customization), specifying the CSS entrypoint for your card: + +```blade + + @vite('resources/css/pulse/top-sellers.css') + + ... + +``` + + +#### CSS Files + +For other use cases, including Pulse cards contained within a package, you may instruct Pulse to load additional stylesheets by defining a `css` method on your Livewire component that returns the file path to your CSS file: + +```php +class TopSellers extends Card +{ + // ... + + protected function css() + { + return __DIR__.'/../../dist/top-sellers.css'; + } +} +``` + +When this card is included on the dashboard, Pulse will automatically include the contents of this file within a ` + + +### Strings + +
+ +[\__](#method-__) +[class_basename](#method-class-basename) +[e](#method-e) +[preg_replace_array](#method-preg-replace-array) +[Str::after](#method-str-after) +[Str::afterLast](#method-str-after-last) +[Str::apa](#method-str-apa) +[Str::ascii](#method-str-ascii) +[Str::before](#method-str-before) +[Str::beforeLast](#method-str-before-last) +[Str::between](#method-str-between) +[Str::betweenFirst](#method-str-between-first) +[Str::camel](#method-camel-case) +[Str::charAt](#method-char-at) +[Str::chopStart](#method-str-chop-start) +[Str::chopEnd](#method-str-chop-end) +[Str::contains](#method-str-contains) +[Str::containsAll](#method-str-contains-all) +[Str::doesntContain](#method-str-doesnt-contain) +[Str::doesntEndWith](#method-str-doesnt-end-with) +[Str::doesntStartWith](#method-str-doesnt-start-with) +[Str::deduplicate](#method-deduplicate) +[Str::endsWith](#method-ends-with) +[Str::excerpt](#method-excerpt) +[Str::finish](#method-str-finish) +[Str::fromBase64](#method-str-from-base64) +[Str::headline](#method-str-headline) +[Str::inlineMarkdown](#method-str-inline-markdown) +[Str::is](#method-str-is) +[Str::isAscii](#method-str-is-ascii) +[Str::isJson](#method-str-is-json) +[Str::isUlid](#method-str-is-ulid) +[Str::isUrl](#method-str-is-url) +[Str::isUuid](#method-str-is-uuid) +[Str::kebab](#method-kebab-case) +[Str::lcfirst](#method-str-lcfirst) +[Str::length](#method-str-length) +[Str::limit](#method-str-limit) +[Str::lower](#method-str-lower) +[Str::markdown](#method-str-markdown) +[Str::mask](#method-str-mask) +[Str::match](#method-str-match) +[Str::matchAll](#method-str-match-all) +[Str::orderedUuid](#method-str-ordered-uuid) +[Str::padBoth](#method-str-padboth) +[Str::padLeft](#method-str-padleft) +[Str::padRight](#method-str-padright) +[Str::password](#method-str-password) +[Str::plural](#method-str-plural) +[Str::pluralStudly](#method-str-plural-studly) +[Str::position](#method-str-position) +[Str::random](#method-str-random) +[Str::remove](#method-str-remove) +[Str::repeat](#method-str-repeat) +[Str::replace](#method-str-replace) +[Str::replaceArray](#method-str-replace-array) +[Str::replaceFirst](#method-str-replace-first) +[Str::replaceLast](#method-str-replace-last) +[Str::replaceMatches](#method-str-replace-matches) +[Str::replaceStart](#method-str-replace-start) +[Str::replaceEnd](#method-str-replace-end) +[Str::reverse](#method-str-reverse) +[Str::singular](#method-str-singular) +[Str::slug](#method-str-slug) +[Str::snake](#method-snake-case) +[Str::squish](#method-str-squish) +[Str::start](#method-str-start) +[Str::startsWith](#method-starts-with) +[Str::studly](#method-studly-case) +[Str::substr](#method-str-substr) +[Str::substrCount](#method-str-substrcount) +[Str::substrReplace](#method-str-substrreplace) +[Str::swap](#method-str-swap) +[Str::take](#method-take) +[Str::title](#method-title-case) +[Str::toBase64](#method-str-to-base64) +[Str::transliterate](#method-str-transliterate) +[Str::trim](#method-str-trim) +[Str::ltrim](#method-str-ltrim) +[Str::rtrim](#method-str-rtrim) +[Str::ucfirst](#method-str-ucfirst) +[Str::ucsplit](#method-str-ucsplit) +[Str::upper](#method-str-upper) +[Str::ulid](#method-str-ulid) +[Str::unwrap](#method-str-unwrap) +[Str::uuid](#method-str-uuid) +[Str::uuid7](#method-str-uuid7) +[Str::wordCount](#method-str-word-count) +[Str::wordWrap](#method-str-word-wrap) +[Str::words](#method-str-words) +[Str::wrap](#method-str-wrap) +[str](#method-str) +[trans](#method-trans) +[trans_choice](#method-trans-choice) + +
+ + +### Fluent Strings + +
+ +[after](#method-fluent-str-after) +[afterLast](#method-fluent-str-after-last) +[apa](#method-fluent-str-apa) +[append](#method-fluent-str-append) +[ascii](#method-fluent-str-ascii) +[basename](#method-fluent-str-basename) +[before](#method-fluent-str-before) +[beforeLast](#method-fluent-str-before-last) +[between](#method-fluent-str-between) +[betweenFirst](#method-fluent-str-between-first) +[camel](#method-fluent-str-camel) +[charAt](#method-fluent-str-char-at) +[classBasename](#method-fluent-str-class-basename) +[chopStart](#method-fluent-str-chop-start) +[chopEnd](#method-fluent-str-chop-end) +[contains](#method-fluent-str-contains) +[containsAll](#method-fluent-str-contains-all) +[decrypt](#method-fluent-str-decrypt) +[deduplicate](#method-fluent-str-deduplicate) +[dirname](#method-fluent-str-dirname) +[doesntEndWith](#method-fluent-str-doesnt-end-with) +[doesntStartWith](#method-fluent-str-doesnt-start-with) +[encrypt](#method-fluent-str-encrypt) +[endsWith](#method-fluent-str-ends-with) +[exactly](#method-fluent-str-exactly) +[excerpt](#method-fluent-str-excerpt) +[explode](#method-fluent-str-explode) +[finish](#method-fluent-str-finish) +[fromBase64](#method-fluent-str-from-base64) +[hash](#method-fluent-str-hash) +[headline](#method-fluent-str-headline) +[inlineMarkdown](#method-fluent-str-inline-markdown) +[is](#method-fluent-str-is) +[isAscii](#method-fluent-str-is-ascii) +[isEmpty](#method-fluent-str-is-empty) +[isNotEmpty](#method-fluent-str-is-not-empty) +[isJson](#method-fluent-str-is-json) +[isUlid](#method-fluent-str-is-ulid) +[isUrl](#method-fluent-str-is-url) +[isUuid](#method-fluent-str-is-uuid) +[kebab](#method-fluent-str-kebab) +[lcfirst](#method-fluent-str-lcfirst) +[length](#method-fluent-str-length) +[limit](#method-fluent-str-limit) +[lower](#method-fluent-str-lower) +[markdown](#method-fluent-str-markdown) +[mask](#method-fluent-str-mask) +[match](#method-fluent-str-match) +[matchAll](#method-fluent-str-match-all) +[isMatch](#method-fluent-str-is-match) +[newLine](#method-fluent-str-new-line) +[padBoth](#method-fluent-str-padboth) +[padLeft](#method-fluent-str-padleft) +[padRight](#method-fluent-str-padright) +[pipe](#method-fluent-str-pipe) +[plural](#method-fluent-str-plural) +[position](#method-fluent-str-position) +[prepend](#method-fluent-str-prepend) +[remove](#method-fluent-str-remove) +[repeat](#method-fluent-str-repeat) +[replace](#method-fluent-str-replace) +[replaceArray](#method-fluent-str-replace-array) +[replaceFirst](#method-fluent-str-replace-first) +[replaceLast](#method-fluent-str-replace-last) +[replaceMatches](#method-fluent-str-replace-matches) +[replaceStart](#method-fluent-str-replace-start) +[replaceEnd](#method-fluent-str-replace-end) +[scan](#method-fluent-str-scan) +[singular](#method-fluent-str-singular) +[slug](#method-fluent-str-slug) +[snake](#method-fluent-str-snake) +[split](#method-fluent-str-split) +[squish](#method-fluent-str-squish) +[start](#method-fluent-str-start) +[startsWith](#method-fluent-str-starts-with) +[stripTags](#method-fluent-str-strip-tags) +[studly](#method-fluent-str-studly) +[substr](#method-fluent-str-substr) +[substrReplace](#method-fluent-str-substrreplace) +[swap](#method-fluent-str-swap) +[take](#method-fluent-str-take) +[tap](#method-fluent-str-tap) +[test](#method-fluent-str-test) +[title](#method-fluent-str-title) +[toBase64](#method-fluent-str-to-base64) +[toHtmlString](#method-fluent-str-to-html-string) +[toUri](#method-fluent-str-to-uri) +[transliterate](#method-fluent-str-transliterate) +[trim](#method-fluent-str-trim) +[ltrim](#method-fluent-str-ltrim) +[rtrim](#method-fluent-str-rtrim) +[ucfirst](#method-fluent-str-ucfirst) +[ucsplit](#method-fluent-str-ucsplit) +[unwrap](#method-fluent-str-unwrap) +[upper](#method-fluent-str-upper) +[when](#method-fluent-str-when) +[whenContains](#method-fluent-str-when-contains) +[whenContainsAll](#method-fluent-str-when-contains-all) +[whenDoesntEndWith](#method-fluent-str-when-doesnt-end-with) +[whenDoesntStartWith](#method-fluent-str-when-doesnt-start-with) +[whenEmpty](#method-fluent-str-when-empty) +[whenNotEmpty](#method-fluent-str-when-not-empty) +[whenStartsWith](#method-fluent-str-when-starts-with) +[whenEndsWith](#method-fluent-str-when-ends-with) +[whenExactly](#method-fluent-str-when-exactly) +[whenNotExactly](#method-fluent-str-when-not-exactly) +[whenIs](#method-fluent-str-when-is) +[whenIsAscii](#method-fluent-str-when-is-ascii) +[whenIsUlid](#method-fluent-str-when-is-ulid) +[whenIsUuid](#method-fluent-str-when-is-uuid) +[whenTest](#method-fluent-str-when-test) +[wordCount](#method-fluent-str-word-count) +[words](#method-fluent-str-words) +[wrap](#method-fluent-str-wrap) + +
+ + +## Strings + + +#### `__()` {.collection-method} + +The `__` function translates the given translation string or translation key using your [language files](/docs/{{version}}/localization): + +```php +echo __('Welcome to our application'); + +echo __('messages.welcome'); +``` + +If the specified translation string or key does not exist, the `__` function will return the given value. So, using the example above, the `__` function would return `messages.welcome` if that translation key does not exist. + + +#### `class_basename()` {.collection-method} + +The `class_basename` function returns the class name of the given class with the class's namespace removed: + +```php +$class = class_basename('Foo\Bar\Baz'); + +// Baz +``` + + +#### `e()` {.collection-method} + +The `e` function runs PHP's `htmlspecialchars` function with the `double_encode` option set to `true` by default: + +```php +echo e('foo'); + +// <html>foo</html> +``` + + +#### `preg_replace_array()` {.collection-method} + +The `preg_replace_array` function replaces a given pattern in the string sequentially using an array: + +```php +$string = 'The event will take place between :start and :end'; + +$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string); + +// The event will take place between 8:30 and 9:00 +``` + + +#### `Str::after()` {.collection-method} + +The `Str::after` method returns everything after the given value in a string. The entire string will be returned if the value does not exist within the string: + +```php +use Illuminate\Support\Str; + +$slice = Str::after('This is my name', 'This is'); + +// ' my name' +``` + + +#### `Str::afterLast()` {.collection-method} + +The `Str::afterLast` method returns everything after the last occurrence of the given value in a string. The entire string will be returned if the value does not exist within the string: + +```php +use Illuminate\Support\Str; + +$slice = Str::afterLast('App\Http\Controllers\Controller', '\\'); + +// 'Controller' +``` + + +#### `Str::apa()` {.collection-method} + +The `Str::apa` method converts the given string to title case following the [APA guidelines](https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case): + +```php +use Illuminate\Support\Str; + +$title = Str::apa('Creating A Project'); + +// 'Creating a Project' +``` + + +#### `Str::ascii()` {.collection-method} + +The `Str::ascii` method will attempt to transliterate the string into an ASCII value: + +```php +use Illuminate\Support\Str; + +$slice = Str::ascii('û'); + +// 'u' +``` + + +#### `Str::before()` {.collection-method} + +The `Str::before` method returns everything before the given value in a string: + +```php +use Illuminate\Support\Str; + +$slice = Str::before('This is my name', 'my name'); + +// 'This is ' +``` + + +#### `Str::beforeLast()` {.collection-method} + +The `Str::beforeLast` method returns everything before the last occurrence of the given value in a string: + +```php +use Illuminate\Support\Str; + +$slice = Str::beforeLast('This is my name', 'is'); + +// 'This ' +``` + + +#### `Str::between()` {.collection-method} + +The `Str::between` method returns the portion of a string between two values: + +```php +use Illuminate\Support\Str; + +$slice = Str::between('This is my name', 'This', 'name'); + +// ' is my ' +``` + + +#### `Str::betweenFirst()` {.collection-method} + +The `Str::betweenFirst` method returns the smallest possible portion of a string between two values: + +```php +use Illuminate\Support\Str; + +$slice = Str::betweenFirst('[a] bc [d]', '[', ']'); + +// 'a' +``` + + +#### `Str::camel()` {.collection-method} + +The `Str::camel` method converts the given string to `camelCase`: + +```php +use Illuminate\Support\Str; + +$converted = Str::camel('foo_bar'); + +// 'fooBar' +``` + + +#### `Str::charAt()` {.collection-method} + +The `Str::charAt` method returns the character at the specified index. If the index is out of bounds, `false` is returned: + +```php +use Illuminate\Support\Str; + +$character = Str::charAt('This is my name.', 6); + +// 's' +``` + + +#### `Str::chopStart()` {.collection-method} + +The `Str::chopStart` method removes the first occurrence of the given value only if the value appears at the start of the string: + +```php +use Illuminate\Support\Str; + +$url = Str::chopStart('https://laravel.com/', 'https://'); + +// 'laravel.com' +``` + +You may also pass an array as the second argument. If the string starts with any of the values in the array then that value will be removed from string: + +```php +use Illuminate\Support\Str; + +$url = Str::chopStart('http://laravel.com/', ['https://', 'http://']); + +// 'laravel.com' +``` + + +#### `Str::chopEnd()` {.collection-method} + +The `Str::chopEnd` method removes the last occurrence of the given value only if the value appears at the end of the string: + +```php +use Illuminate\Support\Str; + +$url = Str::chopEnd('app/Models/Photograph.php', '.php'); + +// 'app/Models/Photograph' +``` + +You may also pass an array as the second argument. If the string ends with any of the values in the array then that value will be removed from string: + +```php +use Illuminate\Support\Str; + +$url = Str::chopEnd('laravel.com/index.php', ['/index.html', '/index.php']); + +// 'laravel.com' +``` + + +#### `Str::contains()` {.collection-method} + +The `Str::contains` method determines if the given string contains the given value. By default, this method is case sensitive: + +```php +use Illuminate\Support\Str; + +$contains = Str::contains('This is my name', 'my'); + +// true +``` + +You may also pass an array of values to determine if the given string contains any of the values in the array: + +```php +use Illuminate\Support\Str; + +$contains = Str::contains('This is my name', ['my', 'foo']); + +// true +``` + +You may disable case sensitivity by setting the `ignoreCase` argument to `true`: + +```php +use Illuminate\Support\Str; + +$contains = Str::contains('This is my name', 'MY', ignoreCase: true); + +// true +``` + + +#### `Str::containsAll()` {.collection-method} + +The `Str::containsAll` method determines if the given string contains all of the values in a given array: + +```php +use Illuminate\Support\Str; + +$containsAll = Str::containsAll('This is my name', ['my', 'name']); + +// true +``` + +You may disable case sensitivity by setting the `ignoreCase` argument to `true`: + +```php +use Illuminate\Support\Str; + +$containsAll = Str::containsAll('This is my name', ['MY', 'NAME'], ignoreCase: true); + +// true +``` + + +#### `Str::doesntContain()` {.collection-method} + +The `Str::doesntContain` method determines if the given string doesn't contain the given value. By default, this method is case sensitive: + +```php +use Illuminate\Support\Str; + +$doesntContain = Str::doesntContain('This is name', 'my'); + +// true +``` + +You may also pass an array of values to determine if the given string doesn't contain any of the values in the array: + +```php +use Illuminate\Support\Str; + +$doesntContain = Str::doesntContain('This is name', ['my', 'foo']); + +// true +``` + +You may disable case sensitivity by setting the `ignoreCase` argument to `true`: + +```php +use Illuminate\Support\Str; + +$doesntContain = Str::doesntContain('This is name', 'MY', ignoreCase: true); + +// true +``` + + +#### `Str::deduplicate()` {.collection-method} + +The `Str::deduplicate` method replaces consecutive instances of a character with a single instance of that character in the given string. By default, the method deduplicates spaces: + +```php +use Illuminate\Support\Str; + +$result = Str::deduplicate('The Laravel Framework'); + +// The Laravel Framework +``` + +You may specify a different character to deduplicate by passing it in as the second argument to the method: + +```php +use Illuminate\Support\Str; + +$result = Str::deduplicate('The---Laravel---Framework', '-'); + +// The-Laravel-Framework +``` + + +#### `Str::doesntEndWith()` {.collection-method} + +The `Str::doesntEndWith` method determines if the given string doesn't end with the given value: + +```php +use Illuminate\Support\Str; + +$result = Str::doesntEndWith('This is my name', 'dog'); + +// true +``` + +You may also pass an array of values to determine if the given string doesn't end with any of the values in the array: + +```php +use Illuminate\Support\Str; + +$result = Str::doesntEndWith('This is my name', ['this', 'foo']); + +// true + +$result = Str::doesntEndWith('This is my name', ['name', 'foo']); + +// false +``` + + +#### `Str::doesntStartWith()` {.collection-method} + +The `Str::doesntStartWith` method determines if the given string doesn't begin with the given value: + +```php +use Illuminate\Support\Str; + +$result = Str::doesntStartWith('This is my name', 'That'); + +// true +``` + +If an array of possible values is passed, the `doesntStartWith` method will return `true` if the string doesn't begin with any of the given values: + +```php +$result = Str::doesntStartWith('This is my name', ['What', 'That', 'There']); + +// true +``` + + +#### `Str::endsWith()` {.collection-method} + +The `Str::endsWith` method determines if the given string ends with the given value: + +```php +use Illuminate\Support\Str; + +$result = Str::endsWith('This is my name', 'name'); + +// true +``` + +You may also pass an array of values to determine if the given string ends with any of the values in the array: + +```php +use Illuminate\Support\Str; + +$result = Str::endsWith('This is my name', ['name', 'foo']); + +// true + +$result = Str::endsWith('This is my name', ['this', 'foo']); + +// false +``` + + +#### `Str::excerpt()` {.collection-method} + +The `Str::excerpt` method extracts an excerpt from a given string that matches the first instance of a phrase within that string: + +```php +use Illuminate\Support\Str; + +$excerpt = Str::excerpt('This is my name', 'my', [ + 'radius' => 3 +]); + +// '...is my na...' +``` + +The `radius` option, which defaults to `100`, allows you to define the number of characters that should appear on each side of the truncated string. + +In addition, you may use the `omission` option to define the string that will be prepended and appended to the truncated string: + +```php +use Illuminate\Support\Str; + +$excerpt = Str::excerpt('This is my name', 'name', [ + 'radius' => 3, + 'omission' => '(...) ' +]); + +// '(...) my name' +``` + + +#### `Str::finish()` {.collection-method} + +The `Str::finish` method adds a single instance of the given value to a string if it does not already end with that value: + +```php +use Illuminate\Support\Str; + +$adjusted = Str::finish('this/string', '/'); + +// this/string/ + +$adjusted = Str::finish('this/string/', '/'); + +// this/string/ +``` + + +#### `Str::fromBase64()` {.collection-method} + +The `Str::fromBase64` method decodes the given Base64 string: + +```php +use Illuminate\Support\Str; + +$decoded = Str::fromBase64('TGFyYXZlbA=='); + +// Laravel +``` + + +#### `Str::headline()` {.collection-method} + +The `Str::headline` method will convert strings delimited by casing, hyphens, or underscores into a space delimited string with each word's first letter capitalized: + +```php +use Illuminate\Support\Str; + +$headline = Str::headline('steve_jobs'); + +// Steve Jobs + +$headline = Str::headline('EmailNotificationSent'); + +// Email Notification Sent +``` + + +#### `Str::inlineMarkdown()` {.collection-method} + +The `Str::inlineMarkdown` method converts GitHub flavored Markdown into inline HTML using [CommonMark](https://commonmark.thephpleague.com/). However, unlike the `markdown` method, it does not wrap all generated HTML in a block-level element: + +```php +use Illuminate\Support\Str; + +$html = Str::inlineMarkdown('**Laravel**'); + +// Laravel +``` + +#### Markdown Security + +By default, Markdown supports raw HTML, which will expose Cross-Site Scripting (XSS) vulnerabilities when used with raw user input. As per the [CommonMark Security documentation](https://commonmark.thephpleague.com/security/), you may use the `html_input` option to either escape or strip raw HTML, and the `allow_unsafe_links` option to specify whether to allow unsafe links. If you need to allow some raw HTML, you should pass your compiled Markdown through an HTML Purifier: + +```php +use Illuminate\Support\Str; + +Str::inlineMarkdown('Inject: ', [ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, +]); + +// Inject: alert("Hello XSS!"); +``` + + +#### `Str::is()` {.collection-method} + +The `Str::is` method determines if a given string matches a given pattern. Asterisks may be used as wildcard values: + +```php +use Illuminate\Support\Str; + +$matches = Str::is('foo*', 'foobar'); + +// true + +$matches = Str::is('baz*', 'foobar'); + +// false +``` + +You may disable case sensitivity by setting the `ignoreCase` argument to `true`: + +```php +use Illuminate\Support\Str; + +$matches = Str::is('*.jpg', 'photo.JPG', ignoreCase: true); + +// true +``` + + +#### `Str::isAscii()` {.collection-method} + +The `Str::isAscii` method determines if a given string is 7 bit ASCII: + +```php +use Illuminate\Support\Str; + +$isAscii = Str::isAscii('Taylor'); + +// true + +$isAscii = Str::isAscii('ü'); + +// false +``` + + +#### `Str::isJson()` {.collection-method} + +The `Str::isJson` method determines if the given string is valid JSON: + +```php +use Illuminate\Support\Str; + +$result = Str::isJson('[1,2,3]'); + +// true + +$result = Str::isJson('{"first": "John", "last": "Doe"}'); + +// true + +$result = Str::isJson('{first: "John", last: "Doe"}'); + +// false +``` + + +#### `Str::isUrl()` {.collection-method} + +The `Str::isUrl` method determines if the given string is a valid URL: + +```php +use Illuminate\Support\Str; + +$isUrl = Str::isUrl('http://example.com/'); + +// true + +$isUrl = Str::isUrl('laravel'); + +// false +``` + +The `isUrl` method considers a wide range of protocols as valid. However, you may specify the protocols that should be considered valid by providing them to the `isUrl` method: + +```php +$isUrl = Str::isUrl('http://example.com/', ['http', 'https']); +``` + + +#### `Str::isUlid()` {.collection-method} + +The `Str::isUlid` method determines if the given string is a valid ULID: + +```php +use Illuminate\Support\Str; + +$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40'); + +// true + +$isUlid = Str::isUlid('laravel'); + +// false +``` + + +#### `Str::isUuid()` {.collection-method} + +The `Str::isUuid` method determines if the given string is a valid UUID: + +```php +use Illuminate\Support\Str; + +$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de'); + +// true + +$isUuid = Str::isUuid('laravel'); + +// false +``` + +You may also validate that the given UUID matches a UUID specification by version (1, 3, 4, 5, 6, 7, or 8): + +```php +use Illuminate\Support\Str; + +$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 4); + +// true + +$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 1); + +// false +``` + + +#### `Str::kebab()` {.collection-method} + +The `Str::kebab` method converts the given string to `kebab-case`: + +```php +use Illuminate\Support\Str; + +$converted = Str::kebab('fooBar'); + +// foo-bar +``` + + +#### `Str::lcfirst()` {.collection-method} + +The `Str::lcfirst` method returns the given string with the first character lowercased: + +```php +use Illuminate\Support\Str; + +$string = Str::lcfirst('Foo Bar'); + +// foo Bar +``` + + +#### `Str::length()` {.collection-method} + +The `Str::length` method returns the length of the given string: + +```php +use Illuminate\Support\Str; + +$length = Str::length('Laravel'); + +// 7 +``` + + +#### `Str::limit()` {.collection-method} + +The `Str::limit` method truncates the given string to the specified length: + +```php +use Illuminate\Support\Str; + +$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20); + +// The quick brown fox... +``` + +You may pass a third argument to the method to change the string that will be appended to the end of the truncated string: + +```php +$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)'); + +// The quick brown fox (...) +``` + +If you would like to preserve complete words when truncating the string, you may utilize the `preserveWords` argument. When this argument is `true`, the string will be truncated to the nearest complete word boundary: + +```php +$truncated = Str::limit('The quick brown fox', 12, preserveWords: true); + +// The quick... +``` + + +#### `Str::lower()` {.collection-method} + +The `Str::lower` method converts the given string to lowercase: + +```php +use Illuminate\Support\Str; + +$converted = Str::lower('LARAVEL'); + +// laravel +``` + + +#### `Str::markdown()` {.collection-method} + +The `Str::markdown` method converts GitHub flavored Markdown into HTML using [CommonMark](https://commonmark.thephpleague.com/): + +```php +use Illuminate\Support\Str; + +$html = Str::markdown('# Laravel'); + +//

Laravel

+ +$html = Str::markdown('# Taylor Otwell', [ + 'html_input' => 'strip', +]); + +//

Taylor Otwell

+``` + +#### Markdown Security + +By default, Markdown supports raw HTML, which will expose Cross-Site Scripting (XSS) vulnerabilities when used with raw user input. As per the [CommonMark Security documentation](https://commonmark.thephpleague.com/security/), you may use the `html_input` option to either escape or strip raw HTML, and the `allow_unsafe_links` option to specify whether to allow unsafe links. If you need to allow some raw HTML, you should pass your compiled Markdown through an HTML Purifier: + +```php +use Illuminate\Support\Str; + +Str::markdown('Inject: ', [ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, +]); + +//

Inject: alert("Hello XSS!");

+``` + + +#### `Str::mask()` {.collection-method} + +The `Str::mask` method masks a portion of a string with a repeated character, and may be used to obfuscate segments of strings such as email addresses and phone numbers: + +```php +use Illuminate\Support\Str; + +$string = Str::mask('taylor@example.com', '*', 3); + +// tay*************** +``` + +If needed, you provide a negative number as the third argument to the `mask` method, which will instruct the method to begin masking at the given distance from the end of the string: + +```php +$string = Str::mask('taylor@example.com', '*', -15, 3); + +// tay***@example.com +``` + + +#### `Str::match()` {.collection-method} + +The `Str::match` method will return the portion of a string that matches a given regular expression pattern: + +```php +use Illuminate\Support\Str; + +$result = Str::match('/bar/', 'foo bar'); + +// 'bar' + +$result = Str::match('/foo (.*)/', 'foo bar'); + +// 'bar' +``` + + +#### `Str::matchAll()` {.collection-method} + +The `Str::matchAll` method will return a collection containing the portions of a string that match a given regular expression pattern: + +```php +use Illuminate\Support\Str; + +$result = Str::matchAll('/bar/', 'bar foo bar'); + +// collect(['bar', 'bar']) +``` + +If you specify a matching group within the expression, Laravel will return a collection of the first matching group's matches: + +```php +use Illuminate\Support\Str; + +$result = Str::matchAll('/f(\w*)/', 'bar fun bar fly'); + +// collect(['un', 'ly']); +``` + +If no matches are found, an empty collection will be returned. + + +#### `Str::orderedUuid()` {.collection-method} + +The `Str::orderedUuid` method generates a "timestamp first" UUID that may be efficiently stored in an indexed database column. Each UUID that is generated using this method will be sorted after UUIDs previously generated using the method: + +```php +use Illuminate\Support\Str; + +return (string) Str::orderedUuid(); +``` + + +#### `Str::padBoth()` {.collection-method} + +The `Str::padBoth` method wraps PHP's `str_pad` function, padding both sides of a string with another string until the final string reaches a desired length: + +```php +use Illuminate\Support\Str; + +$padded = Str::padBoth('James', 10, '_'); + +// '__James___' + +$padded = Str::padBoth('James', 10); + +// ' James ' +``` + + +#### `Str::padLeft()` {.collection-method} + +The `Str::padLeft` method wraps PHP's `str_pad` function, padding the left side of a string with another string until the final string reaches a desired length: + +```php +use Illuminate\Support\Str; + +$padded = Str::padLeft('James', 10, '-='); + +// '-=-=-James' + +$padded = Str::padLeft('James', 10); + +// ' James' +``` + + +#### `Str::padRight()` {.collection-method} + +The `Str::padRight` method wraps PHP's `str_pad` function, padding the right side of a string with another string until the final string reaches a desired length: + +```php +use Illuminate\Support\Str; + +$padded = Str::padRight('James', 10, '-'); + +// 'James-----' + +$padded = Str::padRight('James', 10); + +// 'James ' +``` + + +#### `Str::password()` {.collection-method} + +The `Str::password` method may be used to generate a secure, random password of a given length. The password will consist of a combination of letters, numbers, symbols, and spaces. By default, passwords are 32 characters long: + +```php +use Illuminate\Support\Str; + +$password = Str::password(); + +// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4' + +$password = Str::password(12); + +// 'qwuar>#V|i]N' +``` + + +#### `Str::plural()` {.collection-method} + +The `Str::plural` method converts a singular word string to its plural form. This function supports [any of the languages supported by Laravel's pluralizer](/docs/{{version}}/localization#pluralization-language): + +```php +use Illuminate\Support\Str; + +$plural = Str::plural('car'); + +// cars + +$plural = Str::plural('child'); + +// children +``` + +You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string: + +```php +use Illuminate\Support\Str; + +$plural = Str::plural('child', 2); + +// children + +$singular = Str::plural('child', 1); + +// child +``` + +The `prependCount` argument may be provided to prefix the pluralized string with the formatted `$count`: + +```php +use Illuminate\Support\Str; + +$label = Str::plural('car', 1000, prependCount: true); + +// 1,000 cars +``` + + +#### `Str::pluralStudly()` {.collection-method} + +The `Str::pluralStudly` method converts a singular word string formatted in studly caps case to its plural form. This function supports [any of the languages supported by Laravel's pluralizer](/docs/{{version}}/localization#pluralization-language): + +```php +use Illuminate\Support\Str; + +$plural = Str::pluralStudly('VerifiedHuman'); + +// VerifiedHumans + +$plural = Str::pluralStudly('UserFeedback'); + +// UserFeedback +``` + +You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string: + +```php +use Illuminate\Support\Str; + +$plural = Str::pluralStudly('VerifiedHuman', 2); + +// VerifiedHumans + +$singular = Str::pluralStudly('VerifiedHuman', 1); + +// VerifiedHuman +``` + + +#### `Str::position()` {.collection-method} + +The `Str::position` method returns the position of the first occurrence of a substring in a string. If the substring does not exist in the given string, `false` is returned: + +```php +use Illuminate\Support\Str; + +$position = Str::position('Hello, World!', 'Hello'); + +// 0 + +$position = Str::position('Hello, World!', 'W'); + +// 7 +``` + + +#### `Str::random()` {.collection-method} + +The `Str::random` method generates a random string of the specified length. This function uses PHP's `random_bytes` function: + +```php +use Illuminate\Support\Str; + +$random = Str::random(40); +``` + +During testing, it may be useful to "fake" the value that is returned by the `Str::random` method. To accomplish this, you may use the `createRandomStringsUsing` method: + +```php +Str::createRandomStringsUsing(function () { + return 'fake-random-string'; +}); +``` + +To instruct the `random` method to return to generating random strings normally, you may invoke the `createRandomStringsNormally` method: + +```php +Str::createRandomStringsNormally(); +``` + + +#### `Str::remove()` {.collection-method} + +The `Str::remove` method removes the given value or array of values from the string: + +```php +use Illuminate\Support\Str; + +$string = 'Peter Piper picked a peck of pickled peppers.'; + +$removed = Str::remove('e', $string); + +// Ptr Pipr pickd a pck of pickld ppprs. +``` + +You may also pass `false` as a third argument to the `remove` method to ignore case when removing strings. + + +#### `Str::repeat()` {.collection-method} + +The `Str::repeat` method repeats the given string: + +```php +use Illuminate\Support\Str; + +$string = 'a'; + +$repeat = Str::repeat($string, 5); + +// aaaaa +``` + + +#### `Str::replace()` {.collection-method} + +The `Str::replace` method replaces a given string within the string: + +```php +use Illuminate\Support\Str; + +$string = 'Laravel 11.x'; + +$replaced = Str::replace('11.x', '12.x', $string); + +// Laravel 12.x +``` + +The `replace` method also accepts a `caseSensitive` argument. By default, the `replace` method is case sensitive: + +```php +$replaced = Str::replace( + 'php', + 'Laravel', + 'PHP Framework for Web Artisans', + caseSensitive: false +); + +// Laravel Framework for Web Artisans +``` + + +#### `Str::replaceArray()` {.collection-method} + +The `Str::replaceArray` method replaces a given value in the string sequentially using an array: + +```php +use Illuminate\Support\Str; + +$string = 'The event will take place between ? and ?'; + +$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string); + +// The event will take place between 8:30 and 9:00 +``` + + +#### `Str::replaceFirst()` {.collection-method} + +The `Str::replaceFirst` method replaces the first occurrence of a given value in a string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog'); + +// a quick brown fox jumps over the lazy dog +``` + + +#### `Str::replaceLast()` {.collection-method} + +The `Str::replaceLast` method replaces the last occurrence of a given value in a string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog'); + +// the quick brown fox jumps over a lazy dog +``` + + +#### `Str::replaceMatches()` {.collection-method} + +The `Str::replaceMatches` method replaces all portions of a string matching a pattern with the given replacement string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::replaceMatches( + pattern: '/[^A-Za-z0-9]++/', + replace: '', + subject: '(+1) 501-555-1000' +) + +// '15015551000' +``` + +The `replaceMatches` method also accepts a closure that will be invoked with each portion of the string matching the given pattern, allowing you to perform the replacement logic within the closure and return the replaced value: + +```php +use Illuminate\Support\Str; + +$replaced = Str::replaceMatches('/\d/', function (array $matches) { + return '['.$matches[0].']'; +}, '123'); + +// '[1][2][3]' +``` + + +#### `Str::replaceStart()` {.collection-method} + +The `Str::replaceStart` method replaces the first occurrence of the given value only if the value appears at the start of the string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::replaceStart('Hello', 'Laravel', 'Hello World'); + +// Laravel World + +$replaced = Str::replaceStart('World', 'Laravel', 'Hello World'); + +// Hello World +``` + + +#### `Str::replaceEnd()` {.collection-method} + +The `Str::replaceEnd` method replaces the last occurrence of the given value only if the value appears at the end of the string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::replaceEnd('World', 'Laravel', 'Hello World'); + +// Hello Laravel + +$replaced = Str::replaceEnd('Hello', 'Laravel', 'Hello World'); + +// Hello World +``` + + +#### `Str::reverse()` {.collection-method} + +The `Str::reverse` method reverses the given string: + +```php +use Illuminate\Support\Str; + +$reversed = Str::reverse('Hello World'); + +// dlroW olleH +``` + + +#### `Str::singular()` {.collection-method} + +The `Str::singular` method converts a string to its singular form. This function supports [any of the languages supported by Laravel's pluralizer](/docs/{{version}}/localization#pluralization-language): + +```php +use Illuminate\Support\Str; + +$singular = Str::singular('cars'); + +// car + +$singular = Str::singular('children'); + +// child +``` + + +#### `Str::slug()` {.collection-method} + +The `Str::slug` method generates a URL friendly "slug" from the given string: + +```php +use Illuminate\Support\Str; + +$slug = Str::slug('Laravel 5 Framework', '-'); + +// laravel-5-framework +``` + + +#### `Str::snake()` {.collection-method} + +The `Str::snake` method converts the given string to `snake_case`: + +```php +use Illuminate\Support\Str; + +$converted = Str::snake('fooBar'); + +// foo_bar + +$converted = Str::snake('fooBar', '-'); + +// foo-bar +``` + + +#### `Str::squish()` {.collection-method} + +The `Str::squish` method removes all extraneous white space from a string, including extraneous white space between words: + +```php +use Illuminate\Support\Str; + +$string = Str::squish(' laravel framework '); + +// laravel framework +``` + + +#### `Str::start()` {.collection-method} + +The `Str::start` method adds a single instance of the given value to a string if it does not already start with that value: + +```php +use Illuminate\Support\Str; + +$adjusted = Str::start('this/string', '/'); + +// /this/string + +$adjusted = Str::start('/this/string', '/'); + +// /this/string +``` + + +#### `Str::startsWith()` {.collection-method} + +The `Str::startsWith` method determines if the given string begins with the given value: + +```php +use Illuminate\Support\Str; + +$result = Str::startsWith('This is my name', 'This'); + +// true +``` + +If an array of possible values is passed, the `startsWith` method will return `true` if the string begins with any of the given values: + +```php +$result = Str::startsWith('This is my name', ['This', 'That', 'There']); + +// true +``` + + +#### `Str::studly()` {.collection-method} + +The `Str::studly` method converts the given string to `StudlyCase`: + +```php +use Illuminate\Support\Str; + +$converted = Str::studly('foo_bar'); + +// FooBar +``` + + +#### `Str::substr()` {.collection-method} + +The `Str::substr` method returns the portion of string specified by the start and length parameters: + +```php +use Illuminate\Support\Str; + +$converted = Str::substr('The Laravel Framework', 4, 7); + +// Laravel +``` + + +#### `Str::substrCount()` {.collection-method} + +The `Str::substrCount` method returns the number of occurrences of a given value in the given string: + +```php +use Illuminate\Support\Str; + +$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like'); + +// 2 +``` + + +#### `Str::substrReplace()` {.collection-method} + +The `Str::substrReplace` method replaces text within a portion of a string, starting at the position specified by the third argument and replacing the number of characters specified by the fourth argument. Passing `0` to the method's fourth argument will insert the string at the specified position without replacing any of the existing characters in the string: + +```php +use Illuminate\Support\Str; + +$result = Str::substrReplace('1300', ':', 2); +// 13: + +$result = Str::substrReplace('1300', ':', 2, 0); +// 13:00 +``` + + +#### `Str::swap()` {.collection-method} + +The `Str::swap` method replaces multiple values in the given string using PHP's `strtr` function: + +```php +use Illuminate\Support\Str; + +$string = Str::swap([ + 'Tacos' => 'Burritos', + 'great' => 'fantastic', +], 'Tacos are great!'); + +// Burritos are fantastic! +``` + + +#### `Str::take()` {.collection-method} + +The `Str::take` method returns a specified number of characters from the beginning of a string: + +```php +use Illuminate\Support\Str; + +$taken = Str::take('Build something amazing!', 5); + +// Build +``` + + +#### `Str::title()` {.collection-method} + +The `Str::title` method converts the given string to `Title Case`: + +```php +use Illuminate\Support\Str; + +$converted = Str::title('a nice title uses the correct case'); + +// A Nice Title Uses The Correct Case +``` + + +#### `Str::toBase64()` {.collection-method} + +The `Str::toBase64` method converts the given string to Base64: + +```php +use Illuminate\Support\Str; + +$base64 = Str::toBase64('Laravel'); + +// TGFyYXZlbA== +``` + + +#### `Str::transliterate()` {.collection-method} + +The `Str::transliterate` method will attempt to convert a given string into its closest ASCII representation: + +```php +use Illuminate\Support\Str; + +$email = Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ'); + +// 'test@laravel.com' +``` + + +#### `Str::trim()` {.collection-method} + +The `Str::trim` method strips whitespace (or other characters) from the beginning and end of the given string. Unlike PHP's native `trim` function, the `Str::trim` method also removes unicode whitespace characters: + +```php +use Illuminate\Support\Str; + +$string = Str::trim(' foo bar '); + +// 'foo bar' +``` + + +#### `Str::ltrim()` {.collection-method} + +The `Str::ltrim` method strips whitespace (or other characters) from the beginning of the given string. Unlike PHP's native `ltrim` function, the `Str::ltrim` method also removes unicode whitespace characters: + +```php +use Illuminate\Support\Str; + +$string = Str::ltrim(' foo bar '); + +// 'foo bar ' +``` + + +#### `Str::rtrim()` {.collection-method} + +The `Str::rtrim` method strips whitespace (or other characters) from the end of the given string. Unlike PHP's native `rtrim` function, the `Str::rtrim` method also removes unicode whitespace characters: + +```php +use Illuminate\Support\Str; + +$string = Str::rtrim(' foo bar '); + +// ' foo bar' +``` + + +#### `Str::ucfirst()` {.collection-method} + +The `Str::ucfirst` method returns the given string with the first character capitalized: + +```php +use Illuminate\Support\Str; + +$string = Str::ucfirst('foo bar'); + +// Foo bar +``` + + +#### `Str::ucsplit()` {.collection-method} + +The `Str::ucsplit` method splits the given string into an array by uppercase characters: + +```php +use Illuminate\Support\Str; + +$segments = Str::ucsplit('FooBar'); + +// [0 => 'Foo', 1 => 'Bar'] +``` + + +#### `Str::upper()` {.collection-method} + +The `Str::upper` method converts the given string to uppercase: + +```php +use Illuminate\Support\Str; + +$string = Str::upper('laravel'); + +// LARAVEL +``` + + +#### `Str::ulid()` {.collection-method} + +The `Str::ulid` method generates a ULID, which is a compact, time-ordered unique identifier: + +```php +use Illuminate\Support\Str; + +return (string) Str::ulid(); + +// 01gd6r360bp37zj17nxb55yv40 +``` + +If you would like to retrieve a `Illuminate\Support\Carbon` date instance representing the date and time that a given ULID was created, you may use the `createFromId` method provided by Laravel's Carbon integration: + +```php +use Illuminate\Support\Carbon; +use Illuminate\Support\Str; + +$date = Carbon::createFromId((string) Str::ulid()); +``` + +During testing, it may be useful to "fake" the value that is returned by the `Str::ulid` method. To accomplish this, you may use the `createUlidsUsing` method: + +```php +use Symfony\Component\Uid\Ulid; + +Str::createUlidsUsing(function () { + return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9'); +}); +``` + +To instruct the `ulid` method to return to generating ULIDs normally, you may invoke the `createUlidsNormally` method: + +```php +Str::createUlidsNormally(); +``` + + +#### `Str::unwrap()` {.collection-method} + +The `Str::unwrap` method removes the specified strings from the beginning and end of a given string: + +```php +use Illuminate\Support\Str; + +Str::unwrap('-Laravel-', '-'); + +// Laravel + +Str::unwrap('{framework: "Laravel"}', '{', '}'); + +// framework: "Laravel" +``` + + +#### `Str::uuid()` {.collection-method} + +The `Str::uuid` method generates a UUID (version 4): + +```php +use Illuminate\Support\Str; + +return (string) Str::uuid(); +``` + +During testing, it may be useful to "fake" the value that is returned by the `Str::uuid` method. To accomplish this, you may use the `createUuidsUsing` method: + +```php +use Ramsey\Uuid\Uuid; + +Str::createUuidsUsing(function () { + return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9'); +}); +``` + +To instruct the `uuid` method to return to generating UUIDs normally, you may invoke the `createUuidsNormally` method: + +```php +Str::createUuidsNormally(); +``` + + +#### `Str::uuid7()` {.collection-method} + +The `Str::uuid7` method generates a UUID (version 7): + +```php +use Illuminate\Support\Str; + +return (string) Str::uuid7(); +``` + +A `DateTimeInterface` may be passed as an optional parameter which will be used to generate the ordered UUID: + +```php +return (string) Str::uuid7(time: now()); +``` + + +#### `Str::wordCount()` {.collection-method} + +The `Str::wordCount` method returns the number of words that a string contains: + +```php +use Illuminate\Support\Str; + +Str::wordCount('Hello, world!'); // 2 +``` + + +#### `Str::wordWrap()` {.collection-method} + +The `Str::wordWrap` method wraps a string to a given number of characters: + +```php +use Illuminate\Support\Str; + +$text = "The quick brown fox jumped over the lazy dog." + +Str::wordWrap($text, characters: 20, break: "
\n"); + +/* +The quick brown fox
+jumped over the lazy
+dog. +*/ +``` + + +#### `Str::words()` {.collection-method} + +The `Str::words` method limits the number of words in a string. An additional string may be passed to this method via its third argument to specify which string should be appended to the end of the truncated string: + +```php +use Illuminate\Support\Str; + +return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>'); + +// Perfectly balanced, as >>> +``` + + +#### `Str::wrap()` {.collection-method} + +The `Str::wrap` method wraps the given string with an additional string or pair of strings: + +```php +use Illuminate\Support\Str; + +Str::wrap('Laravel', '"'); + +// "Laravel" + +Str::wrap('is', before: 'This ', after: ' Laravel!'); + +// This is Laravel! +``` + + +#### `str()` {.collection-method} + +The `str` function returns a new `Illuminate\Support\Stringable` instance of the given string. This function is equivalent to the `Str::of` method: + +```php +$string = str('Taylor')->append(' Otwell'); + +// 'Taylor Otwell' +``` + +If no argument is provided to the `str` function, the function returns an instance of `Illuminate\Support\Str`: + +```php +$snake = str()->snake('FooBar'); + +// 'foo_bar' +``` + + +#### `trans()` {.collection-method} + +The `trans` function translates the given translation key using your [language files](/docs/{{version}}/localization): + +```php +echo trans('messages.welcome'); +``` + +If the specified translation key does not exist, the `trans` function will return the given key. So, using the example above, the `trans` function would return `messages.welcome` if the translation key does not exist. + + +#### `trans_choice()` {.collection-method} + +The `trans_choice` function translates the given translation key with inflection: + +```php +echo trans_choice('messages.notifications', $unreadCount); +``` + +If the specified translation key does not exist, the `trans_choice` function will return the given key. So, using the example above, the `trans_choice` function would return `messages.notifications` if the translation key does not exist. + + +## Fluent Strings + +Fluent strings provide a more fluent, object-oriented interface for working with string values, allowing you to chain multiple string operations together using a more readable syntax compared to traditional string operations. + + +#### `after` {.collection-method} + +The `after` method returns everything after the given value in a string. The entire string will be returned if the value does not exist within the string: + +```php +use Illuminate\Support\Str; + +$slice = Str::of('This is my name')->after('This is'); + +// ' my name' +``` + + +#### `afterLast` {.collection-method} + +The `afterLast` method returns everything after the last occurrence of the given value in a string. The entire string will be returned if the value does not exist within the string: + +```php +use Illuminate\Support\Str; + +$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\'); + +// 'Controller' +``` + + +#### `apa` {.collection-method} + +The `apa` method converts the given string to title case following the [APA guidelines](https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case): + +```php +use Illuminate\Support\Str; + +$converted = Str::of('a nice title uses the correct case')->apa(); + +// A Nice Title Uses the Correct Case +``` + + +#### `append` {.collection-method} + +The `append` method appends the given values to the string: + +```php +use Illuminate\Support\Str; + +$string = Str::of('Taylor')->append(' Otwell'); + +// 'Taylor Otwell' +``` + + +#### `ascii` {.collection-method} + +The `ascii` method will attempt to transliterate the string into an ASCII value: + +```php +use Illuminate\Support\Str; + +$string = Str::of('ü')->ascii(); + +// 'u' +``` + + +#### `basename` {.collection-method} + +The `basename` method will return the trailing name component of the given string: + +```php +use Illuminate\Support\Str; + +$string = Str::of('/foo/bar/baz')->basename(); + +// 'baz' +``` + +If needed, you may provide an "extension" that will be removed from the trailing component: + +```php +use Illuminate\Support\Str; + +$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg'); + +// 'baz' +``` + + +#### `before` {.collection-method} + +The `before` method returns everything before the given value in a string: + +```php +use Illuminate\Support\Str; + +$slice = Str::of('This is my name')->before('my name'); + +// 'This is ' +``` + + +#### `beforeLast` {.collection-method} + +The `beforeLast` method returns everything before the last occurrence of the given value in a string: + +```php +use Illuminate\Support\Str; + +$slice = Str::of('This is my name')->beforeLast('is'); + +// 'This ' +``` + + +#### `between` {.collection-method} + +The `between` method returns the portion of a string between two values: + +```php +use Illuminate\Support\Str; + +$converted = Str::of('This is my name')->between('This', 'name'); + +// ' is my ' +``` + + +#### `betweenFirst` {.collection-method} + +The `betweenFirst` method returns the smallest possible portion of a string between two values: + +```php +use Illuminate\Support\Str; + +$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']'); + +// 'a' +``` + + +#### `camel` {.collection-method} + +The `camel` method converts the given string to `camelCase`: + +```php +use Illuminate\Support\Str; + +$converted = Str::of('foo_bar')->camel(); + +// 'fooBar' +``` + + +#### `charAt` {.collection-method} + +The `charAt` method returns the character at the specified index. If the index is out of bounds, `false` is returned: + +```php +use Illuminate\Support\Str; + +$character = Str::of('This is my name.')->charAt(6); + +// 's' +``` + + +#### `classBasename` {.collection-method} + +The `classBasename` method returns the class name of the given class with the class's namespace removed: + +```php +use Illuminate\Support\Str; + +$class = Str::of('Foo\Bar\Baz')->classBasename(); + +// 'Baz' +``` + + +#### `chopStart` {.collection-method} + +The `chopStart` method removes the first occurrence of the given value only if the value appears at the start of the string: + +```php +use Illuminate\Support\Str; + +$url = Str::of('https://laravel.com/')->chopStart('https://'); + +// 'laravel.com' +``` + +You may also pass an array. If the string starts with any of the values in the array then that value will be removed from string: + +```php +use Illuminate\Support\Str; + +$url = Str::of('http://laravel.com/')->chopStart(['https://', 'http://']); + +// 'laravel.com' +``` + + +#### `chopEnd` {.collection-method} + +The `chopEnd` method removes the last occurrence of the given value only if the value appears at the end of the string: + +```php +use Illuminate\Support\Str; + +$url = Str::of('https://laravel.com/')->chopEnd('.com'); + +// 'https://laravel/' +``` + +You may also pass an array. If the string ends with any of the values in the array then that value will be removed from string: + +```php +use Illuminate\Support\Str; + +$url = Str::of('http://laravel.com/')->chopEnd(['.com', '.io']); + +// 'http://laravel/' +``` + + +#### `contains` {.collection-method} + +The `contains` method determines if the given string contains the given value. By default, this method is case sensitive: + +```php +use Illuminate\Support\Str; + +$contains = Str::of('This is my name')->contains('my'); + +// true +``` + +You may also pass an array of values to determine if the given string contains any of the values in the array: + +```php +use Illuminate\Support\Str; + +$contains = Str::of('This is my name')->contains(['my', 'foo']); + +// true +``` + +You can disable case sensitivity by setting the `ignoreCase` argument to `true`: + +```php +use Illuminate\Support\Str; + +$contains = Str::of('This is my name')->contains('MY', ignoreCase: true); + +// true +``` + + +#### `containsAll` {.collection-method} + +The `containsAll` method determines if the given string contains all of the values in the given array: + +```php +use Illuminate\Support\Str; + +$containsAll = Str::of('This is my name')->containsAll(['my', 'name']); + +// true +``` + +You can disable case sensitivity by setting the `ignoreCase` argument to `true`: + +```php +use Illuminate\Support\Str; + +$containsAll = Str::of('This is my name')->containsAll(['MY', 'NAME'], ignoreCase: true); + +// true +``` + + +#### `decrypt` {.collection-method} + +The `decrypt` method [decrypts](/docs/{{version}}/encryption) the encrypted string: + +```php +use Illuminate\Support\Str; + +$decrypted = $encrypted->decrypt(); + +// 'secret' +``` + +For the inverse of `decrypt`, see the [encrypt](#method-fluent-str-encrypt) method. + + +#### `deduplicate` {.collection-method} + +The `deduplicate` method replaces consecutive instances of a character with a single instance of that character in the given string. By default, the method deduplicates spaces: + +```php +use Illuminate\Support\Str; + +$result = Str::of('The Laravel Framework')->deduplicate(); + +// The Laravel Framework +``` + +You may specify a different character to deduplicate by passing it in as the second argument to the method: + +```php +use Illuminate\Support\Str; + +$result = Str::of('The---Laravel---Framework')->deduplicate('-'); + +// The-Laravel-Framework +``` + + +#### `dirname` {.collection-method} + +The `dirname` method returns the parent directory portion of the given string: + +```php +use Illuminate\Support\Str; + +$string = Str::of('/foo/bar/baz')->dirname(); + +// '/foo/bar' +``` + +If necessary, you may specify how many directory levels you wish to trim from the string: + +```php +use Illuminate\Support\Str; + +$string = Str::of('/foo/bar/baz')->dirname(2); + +// '/foo' +``` + + +#### `doesntEndWith` {.collection-method} + +The `doesntEndWith` method determines if the given string doesn't end with the given value: + +```php +use Illuminate\Support\Str; + +$result = Str::of('This is my name')->doesntEndWith('dog'); + +// true +``` + +You may also pass an array of values to determine if the given string doesn't end with any of the values in the array: + +```php +use Illuminate\Support\Str; + +$result = Str::of('This is my name')->doesntEndWith(['this', 'foo']); + +// true + +$result = Str::of('This is my name')->doesntEndWith(['name', 'foo']); + +// false +``` + + +#### `doesntStartWith` {.collection-method} + +The `doesntStartWith` method determines if the given string doesn't begin with the given value: + +```php +use Illuminate\Support\Str; + +$result = Str::of('This is my name')->doesntStartWith('That'); + +// true +``` + +You may also pass an array of values to determine if the given string doesn't start with any of the values in the array: + +```php +use Illuminate\Support\Str; + +$result = Str::of('This is my name')->doesntStartWith(['What', 'That', 'There']); + +// true +``` + + +#### `encrypt` {.collection-method} + +The `encrypt` method [encrypts](/docs/{{version}}/encryption) the string: + +```php +use Illuminate\Support\Str; + +$encrypted = Str::of('secret')->encrypt(); +``` + +For the inverse of `encrypt`, see the [decrypt](#method-fluent-str-decrypt) method. + + +#### `endsWith` {.collection-method} + +The `endsWith` method determines if the given string ends with the given value: + +```php +use Illuminate\Support\Str; + +$result = Str::of('This is my name')->endsWith('name'); + +// true +``` + +You may also pass an array of values to determine if the given string ends with any of the values in the array: + +```php +use Illuminate\Support\Str; + +$result = Str::of('This is my name')->endsWith(['name', 'foo']); + +// true + +$result = Str::of('This is my name')->endsWith(['this', 'foo']); + +// false +``` + + +#### `exactly` {.collection-method} + +The `exactly` method determines if the given string is an exact match with another string: + +```php +use Illuminate\Support\Str; + +$result = Str::of('Laravel')->exactly('Laravel'); + +// true +``` + + +#### `excerpt` {.collection-method} + +The `excerpt` method extracts an excerpt from the string that matches the first instance of a phrase within that string: + +```php +use Illuminate\Support\Str; + +$excerpt = Str::of('This is my name')->excerpt('my', [ + 'radius' => 3 +]); + +// '...is my na...' +``` + +The `radius` option, which defaults to `100`, allows you to define the number of characters that should appear on each side of the truncated string. + +In addition, you may use the `omission` option to change the string that will be prepended and appended to the truncated string: + +```php +use Illuminate\Support\Str; + +$excerpt = Str::of('This is my name')->excerpt('name', [ + 'radius' => 3, + 'omission' => '(...) ' +]); + +// '(...) my name' +``` + + +#### `explode` {.collection-method} + +The `explode` method splits the string by the given delimiter and returns a collection containing each section of the split string: + +```php +use Illuminate\Support\Str; + +$collection = Str::of('foo bar baz')->explode(' '); + +// collect(['foo', 'bar', 'baz']) +``` + + +#### `finish` {.collection-method} + +The `finish` method adds a single instance of the given value to a string if it does not already end with that value: + +```php +use Illuminate\Support\Str; + +$adjusted = Str::of('this/string')->finish('/'); + +// this/string/ + +$adjusted = Str::of('this/string/')->finish('/'); + +// this/string/ +``` + + +#### `fromBase64` {.collection-method} + +The `fromBase64` method decodes the given Base64 string: + +```php +use Illuminate\Support\Str; + +$decoded = Str::of('TGFyYXZlbA==')->fromBase64(); + +// Laravel +``` + + +#### `hash` {.collection-method} + +The `hash` method hashes the string using the given [algorithm](https://www.php.net/manual/en/function.hash-algos.php): + +```php +use Illuminate\Support\Str; + +$hashed = Str::of('secret')->hash(algorithm: 'sha256'); + +// '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b' +``` + + +#### `headline` {.collection-method} + +The `headline` method will convert strings delimited by casing, hyphens, or underscores into a space delimited string with each word's first letter capitalized: + +```php +use Illuminate\Support\Str; + +$headline = Str::of('taylor_otwell')->headline(); + +// Taylor Otwell + +$headline = Str::of('EmailNotificationSent')->headline(); + +// Email Notification Sent +``` + + +#### `inlineMarkdown` {.collection-method} + +The `inlineMarkdown` method converts GitHub flavored Markdown into inline HTML using [CommonMark](https://commonmark.thephpleague.com/). However, unlike the `markdown` method, it does not wrap all generated HTML in a block-level element: + +```php +use Illuminate\Support\Str; + +$html = Str::of('**Laravel**')->inlineMarkdown(); + +// Laravel +``` + +#### Markdown Security + +By default, Markdown supports raw HTML, which will expose Cross-Site Scripting (XSS) vulnerabilities when used with raw user input. As per the [CommonMark Security documentation](https://commonmark.thephpleague.com/security/), you may use the `html_input` option to either escape or strip raw HTML, and the `allow_unsafe_links` option to specify whether to allow unsafe links. If you need to allow some raw HTML, you should pass your compiled Markdown through an HTML Purifier: + +```php +use Illuminate\Support\Str; + +Str::of('Inject: ')->inlineMarkdown([ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, +]); + +// Inject: alert("Hello XSS!"); +``` + + +#### `is` {.collection-method} + +The `is` method determines if a given string matches a given pattern. Asterisks may be used as wildcard values + +```php +use Illuminate\Support\Str; + +$matches = Str::of('foobar')->is('foo*'); + +// true + +$matches = Str::of('foobar')->is('baz*'); + +// false +``` + + +#### `isAscii` {.collection-method} + +The `isAscii` method determines if a given string is an ASCII string: + +```php +use Illuminate\Support\Str; + +$result = Str::of('Taylor')->isAscii(); + +// true + +$result = Str::of('ü')->isAscii(); + +// false +``` + + +#### `isEmpty` {.collection-method} + +The `isEmpty` method determines if the given string is empty: + +```php +use Illuminate\Support\Str; + +$result = Str::of(' ')->trim()->isEmpty(); + +// true + +$result = Str::of('Laravel')->trim()->isEmpty(); + +// false +``` + + +#### `isNotEmpty` {.collection-method} + +The `isNotEmpty` method determines if the given string is not empty: + +```php +use Illuminate\Support\Str; + +$result = Str::of(' ')->trim()->isNotEmpty(); + +// false + +$result = Str::of('Laravel')->trim()->isNotEmpty(); + +// true +``` + + +#### `isJson` {.collection-method} + +The `isJson` method determines if a given string is valid JSON: + +```php +use Illuminate\Support\Str; + +$result = Str::of('[1,2,3]')->isJson(); + +// true + +$result = Str::of('{"first": "John", "last": "Doe"}')->isJson(); + +// true + +$result = Str::of('{first: "John", last: "Doe"}')->isJson(); + +// false +``` + + +#### `isUlid` {.collection-method} + +The `isUlid` method determines if a given string is a ULID: + +```php +use Illuminate\Support\Str; + +$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid(); + +// true + +$result = Str::of('Taylor')->isUlid(); + +// false +``` + + +#### `isUrl` {.collection-method} + +The `isUrl` method determines if a given string is a URL: + +```php +use Illuminate\Support\Str; + +$result = Str::of('http://example.com/')->isUrl(); + +// true + +$result = Str::of('Taylor')->isUrl(); + +// false +``` + +The `isUrl` method considers a wide range of protocols as valid. However, you may specify the protocols that should be considered valid by providing them to the `isUrl` method: + +```php +$result = Str::of('http://example.com/')->isUrl(['http', 'https']); +``` + + +#### `isUuid` {.collection-method} + +The `isUuid` method determines if a given string is a UUID: + +```php +use Illuminate\Support\Str; + +$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid(); + +// true + +$result = Str::of('Taylor')->isUuid(); + +// false +``` + +You may also validate that the given UUID matches a UUID specification by version (1, 3, 4, 5, 6, 7, or 8): + +```php +use Illuminate\Support\Str; + +$isUuid = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 4); + +// true + +$isUuid = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 1); + +// false +``` + + +#### `kebab` {.collection-method} + +The `kebab` method converts the given string to `kebab-case`: + +```php +use Illuminate\Support\Str; + +$converted = Str::of('fooBar')->kebab(); + +// foo-bar +``` + + +#### `lcfirst` {.collection-method} + +The `lcfirst` method returns the given string with the first character lowercased: + +```php +use Illuminate\Support\Str; + +$string = Str::of('Foo Bar')->lcfirst(); + +// foo Bar +``` + + +#### `length` {.collection-method} + +The `length` method returns the length of the given string: + +```php +use Illuminate\Support\Str; + +$length = Str::of('Laravel')->length(); + +// 7 +``` + + +#### `limit` {.collection-method} + +The `limit` method truncates the given string to the specified length: + +```php +use Illuminate\Support\Str; + +$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20); + +// The quick brown fox... +``` + +You may also pass a second argument to change the string that will be appended to the end of the truncated string: + +```php +$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)'); + +// The quick brown fox (...) +``` + +If you would like to preserve complete words when truncating the string, you may utilize the `preserveWords` argument. When this argument is `true`, the string will be truncated to the nearest complete word boundary: + +```php +$truncated = Str::of('The quick brown fox')->limit(12, preserveWords: true); + +// The quick... +``` + + +#### `lower` {.collection-method} + +The `lower` method converts the given string to lowercase: + +```php +use Illuminate\Support\Str; + +$result = Str::of('LARAVEL')->lower(); + +// 'laravel' +``` + + +#### `markdown` {.collection-method} + +The `markdown` method converts GitHub flavored Markdown into HTML: + +```php +use Illuminate\Support\Str; + +$html = Str::of('# Laravel')->markdown(); + +//

Laravel

+ +$html = Str::of('# Taylor Otwell')->markdown([ + 'html_input' => 'strip', +]); + +//

Taylor Otwell

+``` + +#### Markdown Security + +By default, Markdown supports raw HTML, which will expose Cross-Site Scripting (XSS) vulnerabilities when used with raw user input. As per the [CommonMark Security documentation](https://commonmark.thephpleague.com/security/), you may use the `html_input` option to either escape or strip raw HTML, and the `allow_unsafe_links` option to specify whether to allow unsafe links. If you need to allow some raw HTML, you should pass your compiled Markdown through an HTML Purifier: + +```php +use Illuminate\Support\Str; + +Str::of('Inject: ')->markdown([ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, +]); + +//

Inject: alert("Hello XSS!");

+``` + + +#### `mask` {.collection-method} + +The `mask` method masks a portion of a string with a repeated character, and may be used to obfuscate segments of strings such as email addresses and phone numbers: + +```php +use Illuminate\Support\Str; + +$string = Str::of('taylor@example.com')->mask('*', 3); + +// tay*************** +``` + +If needed, you may provide negative numbers as the third or fourth argument to the `mask` method, which will instruct the method to begin masking at the given distance from the end of the string: + +```php +$string = Str::of('taylor@example.com')->mask('*', -15, 3); + +// tay***@example.com + +$string = Str::of('taylor@example.com')->mask('*', 4, -4); + +// tayl**********.com +``` + + +#### `match` {.collection-method} + +The `match` method will return the portion of a string that matches a given regular expression pattern: + +```php +use Illuminate\Support\Str; + +$result = Str::of('foo bar')->match('/bar/'); + +// 'bar' + +$result = Str::of('foo bar')->match('/foo (.*)/'); + +// 'bar' +``` + + +#### `matchAll` {.collection-method} + +The `matchAll` method will return a collection containing the portions of a string that match a given regular expression pattern: + +```php +use Illuminate\Support\Str; + +$result = Str::of('bar foo bar')->matchAll('/bar/'); + +// collect(['bar', 'bar']) +``` + +If you specify a matching group within the expression, Laravel will return a collection of the first matching group's matches: + +```php +use Illuminate\Support\Str; + +$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/'); + +// collect(['un', 'ly']); +``` + +If no matches are found, an empty collection will be returned. + + +#### `isMatch` {.collection-method} + +The `isMatch` method will return `true` if the string matches a given regular expression: + +```php +use Illuminate\Support\Str; + +$result = Str::of('foo bar')->isMatch('/foo (.*)/'); + +// true + +$result = Str::of('laravel')->isMatch('/foo (.*)/'); + +// false +``` + + +#### `newLine` {.collection-method} + +The `newLine` method appends an "end of line" character to a string: + +```php +use Illuminate\Support\Str; + +$padded = Str::of('Laravel')->newLine()->append('Framework'); + +// 'Laravel +// Framework' +``` + + +#### `padBoth` {.collection-method} + +The `padBoth` method wraps PHP's `str_pad` function, padding both sides of a string with another string until the final string reaches the desired length: + +```php +use Illuminate\Support\Str; + +$padded = Str::of('James')->padBoth(10, '_'); + +// '__James___' + +$padded = Str::of('James')->padBoth(10); + +// ' James ' +``` + + +#### `padLeft` {.collection-method} + +The `padLeft` method wraps PHP's `str_pad` function, padding the left side of a string with another string until the final string reaches the desired length: + +```php +use Illuminate\Support\Str; + +$padded = Str::of('James')->padLeft(10, '-='); + +// '-=-=-James' + +$padded = Str::of('James')->padLeft(10); + +// ' James' +``` + + +#### `padRight` {.collection-method} + +The `padRight` method wraps PHP's `str_pad` function, padding the right side of a string with another string until the final string reaches the desired length: + +```php +use Illuminate\Support\Str; + +$padded = Str::of('James')->padRight(10, '-'); + +// 'James-----' + +$padded = Str::of('James')->padRight(10); + +// 'James ' +``` + + +#### `pipe` {.collection-method} + +The `pipe` method allows you to transform the string by passing its current value to the given callable: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: '); + +// 'Checksum: a5c95b86291ea299fcbe64458ed12702' + +$closure = Str::of('foo')->pipe(function (Stringable $str) { + return 'bar'; +}); + +// 'bar' +``` + + +#### `plural` {.collection-method} + +The `plural` method converts a singular word string to its plural form. This function supports [any of the languages supported by Laravel's pluralizer](/docs/{{version}}/localization#pluralization-language): + +```php +use Illuminate\Support\Str; + +$plural = Str::of('car')->plural(); + +// cars + +$plural = Str::of('child')->plural(); + +// children +``` + +You may provide an integer argument to the function to retrieve the singular or plural form of the string: + +```php +use Illuminate\Support\Str; + +$plural = Str::of('child')->plural(2); + +// children + +$plural = Str::of('child')->plural(1); + +// child +``` + +You may provide the `prependCount` argument to prefix the pluralized string with the formatted `$count`: + +```php +use Illuminate\Support\Str; + +$label = Str::of('car')->plural(1000, prependCount: true); + +// 1,000 cars +``` + + +#### `position` {.collection-method} + +The `position` method returns the position of the first occurrence of a substring in a string. If the substring does not exist within the string, `false` is returned: + +```php +use Illuminate\Support\Str; + +$position = Str::of('Hello, World!')->position('Hello'); + +// 0 + +$position = Str::of('Hello, World!')->position('W'); + +// 7 +``` + + +#### `prepend` {.collection-method} + +The `prepend` method prepends the given values onto the string: + +```php +use Illuminate\Support\Str; + +$string = Str::of('Framework')->prepend('Laravel '); + +// Laravel Framework +``` + + +#### `remove` {.collection-method} + +The `remove` method removes the given value or array of values from the string: + +```php +use Illuminate\Support\Str; + +$string = Str::of('Arkansas is quite beautiful!')->remove('quite '); + +// Arkansas is beautiful! +``` + +You may also pass `false` as a second parameter to ignore case when removing strings. + + +#### `repeat` {.collection-method} + +The `repeat` method repeats the given string: + +```php +use Illuminate\Support\Str; + +$repeated = Str::of('a')->repeat(5); + +// aaaaa +``` + + +#### `replace` {.collection-method} + +The `replace` method replaces a given string within the string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x'); + +// Laravel 7.x +``` + +The `replace` method also accepts a `caseSensitive` argument. By default, the `replace` method is case sensitive: + +```php +$replaced = Str::of('macOS 13.x')->replace( + 'macOS', 'iOS', caseSensitive: false +); +``` + + +#### `replaceArray` {.collection-method} + +The `replaceArray` method replaces a given value in the string sequentially using an array: + +```php +use Illuminate\Support\Str; + +$string = 'The event will take place between ? and ?'; + +$replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']); + +// The event will take place between 8:30 and 9:00 +``` + + +#### `replaceFirst` {.collection-method} + +The `replaceFirst` method replaces the first occurrence of a given value in a string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a'); + +// a quick brown fox jumps over the lazy dog +``` + + +#### `replaceLast` {.collection-method} + +The `replaceLast` method replaces the last occurrence of a given value in a string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a'); + +// the quick brown fox jumps over a lazy dog +``` + + +#### `replaceMatches` {.collection-method} + +The `replaceMatches` method replaces all portions of a string matching a pattern with the given replacement string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '') + +// '15015551000' +``` + +The `replaceMatches` method also accepts a closure that will be invoked with each portion of the string matching the given pattern, allowing you to perform the replacement logic within the closure and return the replaced value: + +```php +use Illuminate\Support\Str; + +$replaced = Str::of('123')->replaceMatches('/\d/', function (array $matches) { + return '['.$matches[0].']'; +}); + +// '[1][2][3]' +``` + + +#### `replaceStart` {.collection-method} + +The `replaceStart` method replaces the first occurrence of the given value only if the value appears at the start of the string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::of('Hello World')->replaceStart('Hello', 'Laravel'); + +// Laravel World + +$replaced = Str::of('Hello World')->replaceStart('World', 'Laravel'); + +// Hello World +``` + + +#### `replaceEnd` {.collection-method} + +The `replaceEnd` method replaces the last occurrence of the given value only if the value appears at the end of the string: + +```php +use Illuminate\Support\Str; + +$replaced = Str::of('Hello World')->replaceEnd('World', 'Laravel'); + +// Hello Laravel + +$replaced = Str::of('Hello World')->replaceEnd('Hello', 'Laravel'); + +// Hello World +``` + + +#### `scan` {.collection-method} + +The `scan` method parses input from a string into a collection according to a format supported by the [`sscanf` PHP function](https://www.php.net/manual/en/function.sscanf.php): + +```php +use Illuminate\Support\Str; + +$collection = Str::of('filename.jpg')->scan('%[^.].%s'); + +// collect(['filename', 'jpg']) +``` + + +#### `singular` {.collection-method} + +The `singular` method converts a string to its singular form. This function supports [any of the languages supported by Laravel's pluralizer](/docs/{{version}}/localization#pluralization-language): + +```php +use Illuminate\Support\Str; + +$singular = Str::of('cars')->singular(); + +// car + +$singular = Str::of('children')->singular(); + +// child +``` + + +#### `slug` {.collection-method} + +The `slug` method generates a URL friendly "slug" from the given string: + +```php +use Illuminate\Support\Str; + +$slug = Str::of('Laravel Framework')->slug('-'); + +// laravel-framework +``` + + +#### `snake` {.collection-method} + +The `snake` method converts the given string to `snake_case`: + +```php +use Illuminate\Support\Str; + +$converted = Str::of('fooBar')->snake(); + +// foo_bar +``` + + +#### `split` {.collection-method} + +The `split` method splits a string into a collection using a regular expression: + +```php +use Illuminate\Support\Str; + +$segments = Str::of('one, two, three')->split('/[\s,]+/'); + +// collect(["one", "two", "three"]) +``` + + +#### `squish` {.collection-method} + +The `squish` method removes all extraneous white space from a string, including extraneous white space between words: + +```php +use Illuminate\Support\Str; + +$string = Str::of(' laravel framework ')->squish(); + +// laravel framework +``` + + +#### `start` {.collection-method} + +The `start` method adds a single instance of the given value to a string if it does not already start with that value: + +```php +use Illuminate\Support\Str; + +$adjusted = Str::of('this/string')->start('/'); + +// /this/string + +$adjusted = Str::of('/this/string')->start('/'); + +// /this/string +``` + + +#### `startsWith` {.collection-method} + +The `startsWith` method determines if the given string begins with the given value: + +```php +use Illuminate\Support\Str; + +$result = Str::of('This is my name')->startsWith('This'); + +// true +``` + + +#### `stripTags` {.collection-method} + +The `stripTags` method removes all HTML and PHP tags from a string: + +```php +use Illuminate\Support\Str; + +$result = Str::of('Taylor Otwell')->stripTags(); + +// Taylor Otwell + +$result = Str::of('Taylor Otwell')->stripTags(''); + +// Taylor Otwell +``` + + +#### `studly` {.collection-method} + +The `studly` method converts the given string to `StudlyCase`: + +```php +use Illuminate\Support\Str; + +$converted = Str::of('foo_bar')->studly(); + +// FooBar +``` + + +#### `substr` {.collection-method} + +The `substr` method returns the portion of the string specified by the given start and length parameters: + +```php +use Illuminate\Support\Str; + +$string = Str::of('Laravel Framework')->substr(8); + +// Framework + +$string = Str::of('Laravel Framework')->substr(8, 5); + +// Frame +``` + + +#### `substrReplace` {.collection-method} + +The `substrReplace` method replaces text within a portion of a string, starting at the position specified by the second argument and replacing the number of characters specified by the third argument. Passing `0` to the method's third argument will insert the string at the specified position without replacing any of the existing characters in the string: + +```php +use Illuminate\Support\Str; + +$string = Str::of('1300')->substrReplace(':', 2); + +// 13: + +$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0); + +// The Laravel Framework +``` + + +#### `swap` {.collection-method} + +The `swap` method replaces multiple values in the string using PHP's `strtr` function: + +```php +use Illuminate\Support\Str; + +$string = Str::of('Tacos are great!') + ->swap([ + 'Tacos' => 'Burritos', + 'great' => 'fantastic', + ]); + +// Burritos are fantastic! +``` + + +#### `take` {.collection-method} + +The `take` method returns a specified number of characters from the beginning of the string: + +```php +use Illuminate\Support\Str; + +$taken = Str::of('Build something amazing!')->take(5); + +// Build +``` + + +#### `tap` {.collection-method} + +The `tap` method passes the string to the given closure, allowing you to examine and interact with the string while not affecting the string itself. The original string is returned by the `tap` method regardless of what is returned by the closure: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('Laravel') + ->append(' Framework') + ->tap(function (Stringable $string) { + dump('String after append: '.$string); + }) + ->upper(); + +// LARAVEL FRAMEWORK +``` + + +#### `test` {.collection-method} + +The `test` method determines if a string matches the given regular expression pattern: + +```php +use Illuminate\Support\Str; + +$result = Str::of('Laravel Framework')->test('/Laravel/'); + +// true +``` + + +#### `title` {.collection-method} + +The `title` method converts the given string to `Title Case`: + +```php +use Illuminate\Support\Str; + +$converted = Str::of('a nice title uses the correct case')->title(); + +// A Nice Title Uses The Correct Case +``` + + +#### `toBase64` {.collection-method} + +The `toBase64` method converts the given string to Base64: + +```php +use Illuminate\Support\Str; + +$base64 = Str::of('Laravel')->toBase64(); + +// TGFyYXZlbA== +``` + + +#### `toHtmlString` {.collection-method} + +The `toHtmlString` method converts the given string to an instance of `Illuminate\Support\HtmlString`, which will not be escaped when rendered in Blade templates: + +```php +use Illuminate\Support\Str; + +$htmlString = Str::of('Nuno Maduro')->toHtmlString(); +``` + + +#### `toUri` {.collection-method} + +The `toUri` method converts the given string to an instance of [Illuminate\Support\Uri](/docs/{{version}}/helpers#uri): + +```php +use Illuminate\Support\Str; + +$uri = Str::of('https://example.com/')->toUri(); +``` + + +#### `transliterate` {.collection-method} + +The `transliterate` method will attempt to convert a given string into its closest ASCII representation: + +```php +use Illuminate\Support\Str; + +$email = Str::of('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ')->transliterate() + +// 'test@laravel.com' +``` + + +#### `trim` {.collection-method} + +The `trim` method trims the given string. Unlike PHP's native `trim` function, Laravel's `trim` method also removes unicode whitespace characters: + +```php +use Illuminate\Support\Str; + +$string = Str::of(' Laravel ')->trim(); + +// 'Laravel' + +$string = Str::of('/Laravel/')->trim('/'); + +// 'Laravel' +``` + + +#### `ltrim` {.collection-method} + +The `ltrim` method trims the left side of the string. Unlike PHP's native `ltrim` function, Laravel's `ltrim` method also removes unicode whitespace characters: + +```php +use Illuminate\Support\Str; + +$string = Str::of(' Laravel ')->ltrim(); + +// 'Laravel ' + +$string = Str::of('/Laravel/')->ltrim('/'); + +// 'Laravel/' +``` + + +#### `rtrim` {.collection-method} + +The `rtrim` method trims the right side of the given string. Unlike PHP's native `rtrim` function, Laravel's `rtrim` method also removes unicode whitespace characters: + +```php +use Illuminate\Support\Str; + +$string = Str::of(' Laravel ')->rtrim(); + +// ' Laravel' + +$string = Str::of('/Laravel/')->rtrim('/'); + +// '/Laravel' +``` + + +#### `ucfirst` {.collection-method} + +The `ucfirst` method returns the given string with the first character capitalized: + +```php +use Illuminate\Support\Str; + +$string = Str::of('foo bar')->ucfirst(); + +// Foo bar +``` + + +#### `ucsplit` {.collection-method} + +The `ucsplit` method splits the given string into a collection by uppercase characters: + +```php +use Illuminate\Support\Str; + +$string = Str::of('Foo Bar')->ucsplit(); + +// collect(['Foo ', 'Bar']) +``` + + +#### `unwrap` {.collection-method} + +The `unwrap` method removes the specified strings from the beginning and end of a given string: + +```php +use Illuminate\Support\Str; + +Str::of('-Laravel-')->unwrap('-'); + +// Laravel + +Str::of('{framework: "Laravel"}')->unwrap('{', '}'); + +// framework: "Laravel" +``` + + +#### `upper` {.collection-method} + +The `upper` method converts the given string to uppercase: + +```php +use Illuminate\Support\Str; + +$adjusted = Str::of('laravel')->upper(); + +// LARAVEL +``` + + +#### `when` {.collection-method} + +The `when` method invokes the given closure if a given condition is `true`. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('Taylor') + ->when(true, function (Stringable $string) { + return $string->append(' Otwell'); + }); + +// 'Taylor Otwell' +``` + +If necessary, you may pass another closure as the third parameter to the `when` method. This closure will execute if the condition parameter evaluates to `false`. + + +#### `whenContains` {.collection-method} + +The `whenContains` method invokes the given closure if the string contains the given value. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('tony stark') + ->whenContains('tony', function (Stringable $string) { + return $string->title(); + }); + +// 'Tony Stark' +``` + +If necessary, you may pass another closure as the third parameter to the `when` method. This closure will execute if the string does not contain the given value. + +You may also pass an array of values to determine if the given string contains any of the values in the array: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('tony stark') + ->whenContains(['tony', 'hulk'], function (Stringable $string) { + return $string->title(); + }); + +// Tony Stark +``` + + +#### `whenContainsAll` {.collection-method} + +The `whenContainsAll` method invokes the given closure if the string contains all of the given sub-strings. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('tony stark') + ->whenContainsAll(['tony', 'stark'], function (Stringable $string) { + return $string->title(); + }); + +// 'Tony Stark' +``` + +If necessary, you may pass another closure as the third parameter to the `when` method. This closure will execute if the condition parameter evaluates to `false`. + + +#### `whenDoesntEndWith` {.collection-method} + +The `whenDoesntEndWith` method invokes the given closure if the string doesn't end with the given sub-string. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('disney world')->whenDoesntEndWith('land', function (Stringable $string) { + return $string->title(); +}); + +// 'Disney World' +``` + + +#### `whenDoesntStartWith` {.collection-method} + +The `whenDoesntStartWith` method invokes the given closure if the string doesn't start with the given sub-string. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('disney world')->whenDoesntStartWith('sea', function (Stringable $string) { + return $string->title(); +}); + +// 'Disney World' +``` + + +#### `whenEmpty` {.collection-method} + +The `whenEmpty` method invokes the given closure if the string is empty. If the closure returns a value, that value will also be returned by the `whenEmpty` method. If the closure does not return a value, the fluent string instance will be returned: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of(' ')->trim()->whenEmpty(function (Stringable $string) { + return $string->prepend('Laravel'); +}); + +// 'Laravel' +``` + + +#### `whenNotEmpty` {.collection-method} + +The `whenNotEmpty` method invokes the given closure if the string is not empty. If the closure returns a value, that value will also be returned by the `whenNotEmpty` method. If the closure does not return a value, the fluent string instance will be returned: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('Framework')->whenNotEmpty(function (Stringable $string) { + return $string->prepend('Laravel '); +}); + +// 'Laravel Framework' +``` + + +#### `whenStartsWith` {.collection-method} + +The `whenStartsWith` method invokes the given closure if the string starts with the given sub-string. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) { + return $string->title(); +}); + +// 'Disney World' +``` + + +#### `whenEndsWith` {.collection-method} + +The `whenEndsWith` method invokes the given closure if the string ends with the given sub-string. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('disney world')->whenEndsWith('world', function (Stringable $string) { + return $string->title(); +}); + +// 'Disney World' +``` + + +#### `whenExactly` {.collection-method} + +The `whenExactly` method invokes the given closure if the string exactly matches the given string. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('laravel')->whenExactly('laravel', function (Stringable $string) { + return $string->title(); +}); + +// 'Laravel' +``` + + +#### `whenNotExactly` {.collection-method} + +The `whenNotExactly` method invokes the given closure if the string does not exactly match the given string. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) { + return $string->title(); +}); + +// 'Framework' +``` + + +#### `whenIs` {.collection-method} + +The `whenIs` method invokes the given closure if the string matches a given pattern. Asterisks may be used as wildcard values. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('foo/bar')->whenIs('foo/*', function (Stringable $string) { + return $string->append('/baz'); +}); + +// 'foo/bar/baz' +``` + + +#### `whenIsAscii` {.collection-method} + +The `whenIsAscii` method invokes the given closure if the string is 7 bit ASCII. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) { + return $string->title(); +}); + +// 'Laravel' +``` + + +#### `whenIsUlid` {.collection-method} + +The `whenIsUlid` method invokes the given closure if the string is a valid ULID. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; + +$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) { + return $string->substr(0, 8); +}); + +// '01gd6r36' +``` + + +#### `whenIsUuid` {.collection-method} + +The `whenIsUuid` method invokes the given closure if the string is a valid UUID. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function (Stringable $string) { + return $string->substr(0, 8); +}); + +// 'a0a2a2d2' +``` + + +#### `whenTest` {.collection-method} + +The `whenTest` method invokes the given closure if the string matches the given regular expression. The closure will receive the fluent string instance: + +```php +use Illuminate\Support\Str; +use Illuminate\Support\Stringable; + +$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) { + return $string->title(); +}); + +// 'Laravel Framework' +``` + + +#### `wordCount` {.collection-method} + +The `wordCount` method returns the number of words that a string contains: + +```php +use Illuminate\Support\Str; + +Str::of('Hello, world!')->wordCount(); // 2 +``` + + +#### `words` {.collection-method} + +The `words` method limits the number of words in a string. If necessary, you may specify an additional string that will be appended to the truncated string: + +```php +use Illuminate\Support\Str; + +$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>'); + +// Perfectly balanced, as >>> +``` + + +#### `wrap` {.collection-method} + +The `wrap` method wraps the given string with an additional string or pair of strings: + +```php +use Illuminate\Support\Str; + +Str::of('Laravel')->wrap('"'); + +// "Laravel" + +Str::is('is')->wrap(before: 'This ', after: ' Laravel!'); + +// This is Laravel! +``` diff --git a/structure.md b/structure.md index bfb9525cf5c..2218e1a24d9 100644 --- a/structure.md +++ b/structure.md @@ -6,7 +6,6 @@ - [The `bootstrap` Directory](#the-bootstrap-directory) - [The `config` Directory](#the-config-directory) - [The `database` Directory](#the-database-directory) - - [The `lang` Directory](#the-lang-directory) - [The `public` Directory](#the-public-directory) - [The `resources` Directory](#the-resources-directory) - [The `routes` Directory](#the-routes-directory) @@ -37,67 +36,64 @@ The default Laravel application structure is intended to provide a great startin ## The Root Directory -#### The App Directory +### The App Directory The `app` directory contains the core code of your application. We'll explore this directory in more detail soon; however, almost all of the classes in your application will be in this directory. -#### The Bootstrap Directory +### The Bootstrap Directory -The `bootstrap` directory contains the `app.php` file which bootstraps the framework. This directory also houses a `cache` directory which contains framework generated files for performance optimization such as the route and services cache files. You should not typically need to modify any files within this directory. +The `bootstrap` directory contains the `app.php` file which bootstraps the framework. This directory also houses a `cache` directory which contains framework generated files for performance optimization such as the route and services cache files. -#### The Config Directory +### The Config Directory The `config` directory, as the name implies, contains all of your application's configuration files. It's a great idea to read through all of these files and familiarize yourself with all of the options available to you. -#### The Database Directory +### The Database Directory The `database` directory contains your database migrations, model factories, and seeds. If you wish, you may also use this directory to hold an SQLite database. - -#### The Lang Directory - -The `lang` directory houses all of your application's language files. - -#### The Public Directory +### The Public Directory The `public` directory contains the `index.php` file, which is the entry point for all requests entering your application and configures autoloading. This directory also houses your assets such as images, JavaScript, and CSS. -#### The Resources Directory +### The Resources Directory The `resources` directory contains your [views](/docs/{{version}}/views) as well as your raw, un-compiled assets such as CSS or JavaScript. -#### The Routes Directory +### The Routes Directory + +The `routes` directory contains all of the route definitions for your application. By default, two route files are included with Laravel: `web.php` and `console.php`. -The `routes` directory contains all of the route definitions for your application. By default, several route files are included with Laravel: `web.php`, `api.php`, `console.php`, and `channels.php`. +The `web.php` file contains routes that Laravel places in the `web` middleware group, which provides session state, CSRF protection, and cookie encryption. If your application does not offer a stateless, RESTful API then all your routes will most likely be defined in the `web.php` file. -The `web.php` file contains routes that the `RouteServiceProvider` places in the `web` middleware group, which provides session state, CSRF protection, and cookie encryption. If your application does not offer a stateless, RESTful API then it is likely that all of your routes will most likely be defined in the `web.php` file. +The `console.php` file is where you may define all of your closure-based console commands. Each closure is bound to a command instance allowing a simple approach to interacting with each command's IO methods. Even though this file does not define HTTP routes, it defines console based entry points (routes) into your application. You may also [schedule](/docs/{{version}}/scheduling) tasks in the `console.php` file. -The `api.php` file contains routes that the `RouteServiceProvider` places in the `api` middleware group. These routes are intended to be stateless, so requests entering the application through these routes are intended to be authenticated [via tokens](/docs/{{version}}/sanctum) and will not have access to session state. +Optionally, you may install additional route files for API routes (`api.php`) and broadcasting channels (`channels.php`), via the `install:api` and `install:broadcasting` Artisan commands. -The `console.php` file is where you may define all of your closure based console commands. Each closure is bound to a command instance allowing a simple approach to interacting with each command's IO methods. Even though this file does not define HTTP routes, it defines console based entry points (routes) into your application. +The `api.php` file contains routes that are intended to be stateless, so requests entering the application through these routes are intended to be authenticated [via tokens](/docs/{{version}}/sanctum) and will not have access to session state. The `channels.php` file is where you may register all of the [event broadcasting](/docs/{{version}}/broadcasting) channels that your application supports. -#### The Storage Directory +### The Storage Directory The `storage` directory contains your logs, compiled Blade templates, file based sessions, file caches, and other files generated by the framework. This directory is segregated into `app`, `framework`, and `logs` directories. The `app` directory may be used to store any files generated by your application. The `framework` directory is used to store framework generated files and caches. Finally, the `logs` directory contains your application's log files. The `storage/app/public` directory may be used to store user-generated files, such as profile avatars, that should be publicly accessible. You should create a symbolic link at `public/storage` which points to this directory. You may create the link using the `php artisan storage:link` Artisan command. -#### The Tests Directory +### The Tests Directory -The `tests` directory contains your automated tests. Example [PHPUnit](https://phpunit.de/) unit tests and feature tests are provided out of the box. Each test class should be suffixed with the word `Test`. You may run your tests using the `phpunit` or `php vendor/bin/phpunit` commands. Or, if you would like a more detailed and beautiful representation of your test results, you may run your tests using the `php artisan test` Artisan command. +The `tests` directory contains your automated tests. Example [Pest](https://pestphp.com) or [PHPUnit](https://phpunit.de/) unit tests and feature tests are provided out of the box. Each test class should be suffixed with the word `Test`. You may run your tests using the `/vendor/bin/pest` or `/vendor/bin/phpunit` commands. Or, if you would like a more detailed and beautiful representation of your test results, you may run your tests using the `php artisan test` Artisan command. -#### The Vendor Directory +### The Vendor Directory The `vendor` directory contains your [Composer](https://getcomposer.org) dependencies. @@ -106,75 +102,76 @@ The `vendor` directory contains your [Composer](https://getcomposer.org) depende The majority of your application is housed in the `app` directory. By default, this directory is namespaced under `App` and is autoloaded by Composer using the [PSR-4 autoloading standard](https://www.php-fig.org/psr/psr-4/). -The `app` directory contains a variety of additional directories such as `Console`, `Http`, and `Providers`. Think of the `Console` and `Http` directories as providing an API into the core of your application. The HTTP protocol and CLI are both mechanisms to interact with your application, but do not actually contain application logic. In other words, they are two ways of issuing commands to your application. The `Console` directory contains all of your Artisan commands, while the `Http` directory contains your controllers, middleware, and requests. +By default, the `app` directory contains the `Http`, `Models`, and `Providers` directories. However, over time, a variety of other directories will be generated inside the app directory as you use the make Artisan commands to generate classes. For example, the `app/Console` directory will not exist until you execute the `make:command` Artisan command to generate a command class. -A variety of other directories will be generated inside the `app` directory as you use the `make` Artisan commands to generate classes. So, for example, the `app/Jobs` directory will not exist until you execute the `make:job` Artisan command to generate a job class. +Both the `Console` and `Http` directories are further explained in their respective sections below, but think of the `Console` and `Http` directories as providing an API into the core of your application. The HTTP protocol and CLI are both mechanisms to interact with your application, but do not actually contain application logic. In other words, they are two ways of issuing commands to your application. The `Console` directory contains all of your Artisan commands, while the `Http` directory contains your controllers, middleware, and requests. -> {tip} Many of the classes in the `app` directory can be generated by Artisan via commands. To review the available commands, run the `php artisan list make` command in your terminal. +> [!NOTE] +> Many of the classes in the `app` directory can be generated by Artisan via commands. To review the available commands, run the `php artisan list make` command in your terminal. -#### The Broadcasting Directory +### The Broadcasting Directory The `Broadcasting` directory contains all of the broadcast channel classes for your application. These classes are generated using the `make:channel` command. This directory does not exist by default, but will be created for you when you create your first channel. To learn more about channels, check out the documentation on [event broadcasting](/docs/{{version}}/broadcasting). -#### The Console Directory +### The Console Directory -The `Console` directory contains all of the custom Artisan commands for your application. These commands may be generated using the `make:command` command. This directory also houses your console kernel, which is where your custom Artisan commands are registered and your [scheduled tasks](/docs/{{version}}/scheduling) are defined. +The `Console` directory contains all of the custom Artisan commands for your application. These commands may be generated using the `make:command` command. -#### The Events Directory +### The Events Directory This directory does not exist by default, but will be created for you by the `event:generate` and `make:event` Artisan commands. The `Events` directory houses [event classes](/docs/{{version}}/events). Events may be used to alert other parts of your application that a given action has occurred, providing a great deal of flexibility and decoupling. -#### The Exceptions Directory +### The Exceptions Directory -The `Exceptions` directory contains your application's exception handler and is also a good place to place any exceptions thrown by your application. If you would like to customize how your exceptions are logged or rendered, you should modify the `Handler` class in this directory. +The `Exceptions` directory contains all of the custom exceptions for your application. These exceptions may be generated using the `make:exception` command. -#### The Http Directory +### The Http Directory The `Http` directory contains your controllers, middleware, and form requests. Almost all of the logic to handle requests entering your application will be placed in this directory. -#### The Jobs Directory +### The Jobs Directory This directory does not exist by default, but will be created for you if you execute the `make:job` Artisan command. The `Jobs` directory houses the [queueable jobs](/docs/{{version}}/queues) for your application. Jobs may be queued by your application or run synchronously within the current request lifecycle. Jobs that run synchronously during the current request are sometimes referred to as "commands" since they are an implementation of the [command pattern](https://en.wikipedia.org/wiki/Command_pattern). -#### The Listeners Directory +### The Listeners Directory This directory does not exist by default, but will be created for you if you execute the `event:generate` or `make:listener` Artisan commands. The `Listeners` directory contains the classes that handle your [events](/docs/{{version}}/events). Event listeners receive an event instance and perform logic in response to the event being fired. For example, a `UserRegistered` event might be handled by a `SendWelcomeEmail` listener. -#### The Mail Directory +### The Mail Directory This directory does not exist by default, but will be created for you if you execute the `make:mail` Artisan command. The `Mail` directory contains all of your [classes that represent emails](/docs/{{version}}/mail) sent by your application. Mail objects allow you to encapsulate all of the logic of building an email in a single, simple class that may be sent using the `Mail::send` method. -#### The Models Directory +### The Models Directory The `Models` directory contains all of your [Eloquent model classes](/docs/{{version}}/eloquent). The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. -#### The Notifications Directory +### The Notifications Directory This directory does not exist by default, but will be created for you if you execute the `make:notification` Artisan command. The `Notifications` directory contains all of the "transactional" [notifications](/docs/{{version}}/notifications) that are sent by your application, such as simple notifications about events that happen within your application. Laravel's notification feature abstracts sending notifications over a variety of drivers such as email, Slack, SMS, or stored in a database. -#### The Policies Directory +### The Policies Directory This directory does not exist by default, but will be created for you if you execute the `make:policy` Artisan command. The `Policies` directory contains the [authorization policy classes](/docs/{{version}}/authorization) for your application. Policies are used to determine if a user can perform a given action against a resource. -#### The Providers Directory +### The Providers Directory The `Providers` directory contains all of the [service providers](/docs/{{version}}/providers) for your application. Service providers bootstrap your application by binding services in the service container, registering events, or performing any other tasks to prepare your application for incoming requests. -In a fresh Laravel application, this directory will already contain several providers. You are free to add your own providers to this directory as needed. +In a fresh Laravel application, this directory will already contain the `AppServiceProvider`. You are free to add your own providers to this directory as needed. -#### The Rules Directory +### The Rules Directory This directory does not exist by default, but will be created for you if you execute the `make:rule` Artisan command. The `Rules` directory contains the custom validation rule objects for your application. Rules are used to encapsulate complicated validation logic in a simple object. For more information, check out the [validation documentation](/docs/{{version}}/validation). diff --git a/telescope.md b/telescope.md index 3ccf67e1fb1..50a11dfef37 100644 --- a/telescope.md +++ b/telescope.md @@ -48,7 +48,7 @@ You may use the Composer package manager to install Telescope into your Laravel composer require laravel/telescope ``` -After installing Telescope, publish its assets using the `telescope:install` Artisan command. After installing Telescope, you should also run the `migrate` command in order to create the tables needed to store Telescope's data: +After installing Telescope, publish its assets and migrations using the `telescope:install` Artisan command. After installing Telescope, you should also run the `migrate` command in order to create the tables needed to store Telescope's data: ```shell php artisan telescope:install @@ -56,10 +56,7 @@ php artisan telescope:install php artisan migrate ``` - -#### Migration Customization - -If you are not going to use Telescope's default migrations, you should call the `Telescope::ignoreMigrations` method in the `register` method of your application's `App\Providers\AppServiceProvider` class. You may export the default migrations using the following command: `php artisan vendor:publish --tag=telescope-migrations` +Finally, you may access the Telescope dashboard via the `/telescope` route. ### Local Only Installation @@ -74,20 +71,20 @@ php artisan telescope:install php artisan migrate ``` -After running `telescope:install`, you should remove the `TelescopeServiceProvider` service provider registration from your application's `config/app.php` configuration file. Instead, manually register Telescope's service providers in the `register` method of your `App\Providers\AppServiceProvider` class. We will ensure the current environment is `local` before registering the providers: +After running `telescope:install`, you should remove the `TelescopeServiceProvider` service provider registration from your application's `bootstrap/providers.php` configuration file. Instead, manually register Telescope's service providers in the `register` method of your `App\Providers\AppServiceProvider` class. We will ensure the current environment is `local` before registering the providers: - /** - * Register any application services. - * - * @return void - */ - public function register() - { - if ($this->app->environment('local')) { - $this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class); - $this->app->register(TelescopeServiceProvider::class); - } +```php +/** + * Register any application services. + */ +public function register(): void +{ + if ($this->app->environment('local') && class_exists(\Laravel\Telescope\TelescopeServiceProvider::class)) { + $this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class); + $this->app->register(TelescopeServiceProvider::class); } +} +``` Finally, you should also prevent the Telescope package from being [auto-discovered](/docs/{{version}}/packages#package-discovery) by adding the following to your `composer.json` file: @@ -108,41 +105,54 @@ After publishing Telescope's assets, its primary configuration file will be loca If desired, you may disable Telescope's data collection entirely using the `enabled` configuration option: - 'enabled' => env('TELESCOPE_ENABLED', true), +```php +'enabled' => env('TELESCOPE_ENABLED', true), +``` ### Data Pruning Without pruning, the `telescope_entries` table can accumulate records very quickly. To mitigate this, you should [schedule](/docs/{{version}}/scheduling) the `telescope:prune` Artisan command to run daily: - $schedule->command('telescope:prune')->daily(); +```php +use Illuminate\Support\Facades\Schedule; + +Schedule::command('telescope:prune')->daily(); +``` By default, all entries older than 24 hours will be pruned. You may use the `hours` option when calling the command to determine how long to retain Telescope data. For example, the following command will delete all records created over 48 hours ago: - $schedule->command('telescope:prune --hours=48')->daily(); +```php +use Illuminate\Support\Facades\Schedule; + +Schedule::command('telescope:prune --hours=48')->daily(); +``` ### Dashboard Authorization -The Telescope dashboard may be accessed at the `/telescope` route. By default, you will only be able to access this dashboard in the `local` environment. Within your `app/Providers/TelescopeServiceProvider.php` file, there is an [authorization gate](/docs/{{version}}/authorization#gates) definition. This authorization gate controls access to Telescope in **non-local** environments. You are free to modify this gate as needed to restrict access to your Telescope installation: - - /** - * Register the Telescope gate. - * - * This gate determines who can access Telescope in non-local environments. - * - * @return void - */ - protected function gate() - { - Gate::define('viewTelescope', function ($user) { - return in_array($user->email, [ - 'taylor@laravel.com', - ]); - }); - } +The Telescope dashboard may be accessed via the `/telescope` route. By default, you will only be able to access this dashboard in the `local` environment. Within your `app/Providers/TelescopeServiceProvider.php` file, there is an [authorization gate](/docs/{{version}}/authorization#gates) definition. This authorization gate controls access to Telescope in **non-local** environments. You are free to modify this gate as needed to restrict access to your Telescope installation: + +```php +use App\Models\User; + +/** + * Register the Telescope gate. + * + * This gate determines who can access Telescope in non-local environments. + */ +protected function gate(): void +{ + Gate::define('viewTelescope', function (User $user) { + return in_array($user->email, [ + 'taylor@laravel.com', + ]); + }); +} +``` -> {note} You should ensure you change your `APP_ENV` environment variable to `production` in your production environment. Otherwise, your Telescope installation will be publicly available. +> [!WARNING] +> You should ensure you change your `APP_ENV` environment variable to `production` in your production environment. Otherwise, your Telescope installation will be publicly available. ## Upgrading Telescope @@ -155,13 +165,13 @@ In addition, when upgrading to any new Telescope version, you should re-publish php artisan telescope:publish ``` -To keep the assets up-to-date and avoid issues in future updates, you may add the `telescope:publish` command to the `post-update-cmd` scripts in your application's `composer.json` file: +To keep the assets up-to-date and avoid issues in future updates, you may add the `vendor:publish --tag=laravel-assets` command to the `post-update-cmd` scripts in your application's `composer.json` file: ```json { "scripts": { "post-update-cmd": [ - "@php artisan telescope:publish --ansi" + "@php artisan vendor:publish --tag=laravel-assets --ansi --force" ] } } @@ -175,107 +185,113 @@ To keep the assets up-to-date and avoid issues in future updates, you may add th You may filter the data that is recorded by Telescope via the `filter` closure that is defined in your `App\Providers\TelescopeServiceProvider` class. By default, this closure records all data in the `local` environment and exceptions, failed jobs, scheduled tasks, and data with monitored tags in all other environments: - use Laravel\Telescope\IncomingEntry; - use Laravel\Telescope\Telescope; +```php +use Laravel\Telescope\IncomingEntry; +use Laravel\Telescope\Telescope; - /** - * Register any application services. - * - * @return void - */ - public function register() - { - $this->hideSensitiveRequestDetails(); +/** + * Register any application services. + */ +public function register(): void +{ + $this->hideSensitiveRequestDetails(); - Telescope::filter(function (IncomingEntry $entry) { - if ($this->app->environment('local')) { - return true; - } + Telescope::filter(function (IncomingEntry $entry) { + if ($this->app->environment('local')) { + return true; + } - return $entry->isReportableException() || - $entry->isFailedJob() || - $entry->isScheduledTask() || - $entry->isSlowQuery() || - $entry->hasMonitoredTag(); - }); - } + return $entry->isReportableException() || + $entry->isFailedJob() || + $entry->isScheduledTask() || + $entry->isSlowQuery() || + $entry->hasMonitoredTag(); + }); +} +``` ### Batches While the `filter` closure filters data for individual entries, you may use the `filterBatch` method to register a closure that filters all data for a given request or console command. If the closure returns `true`, all of the entries are recorded by Telescope: - use Illuminate\Support\Collection; - use Laravel\Telescope\Telescope; - - /** - * Register any application services. - * - * @return void - */ - public function register() - { - $this->hideSensitiveRequestDetails(); - - Telescope::filterBatch(function (Collection $entries) { - if ($this->app->environment('local')) { - return true; - } - - return $entries->contains(function ($entry) { - return $entry->isReportableException() || - $entry->isFailedJob() || - $entry->isScheduledTask() || - $entry->isSlowQuery() || - $entry->hasMonitoredTag(); - }); - }); - } +```php +use Illuminate\Support\Collection; +use Laravel\Telescope\IncomingEntry; +use Laravel\Telescope\Telescope; + +/** + * Register any application services. + */ +public function register(): void +{ + $this->hideSensitiveRequestDetails(); + + Telescope::filterBatch(function (Collection $entries) { + if ($this->app->environment('local')) { + return true; + } + + return $entries->contains(function (IncomingEntry $entry) { + return $entry->isReportableException() || + $entry->isFailedJob() || + $entry->isScheduledTask() || + $entry->isSlowQuery() || + $entry->hasMonitoredTag(); + }); + }); +} +``` ## Tagging Telescope allows you to search entries by "tag". Often, tags are Eloquent model class names or authenticated user IDs which Telescope automatically adds to entries. Occasionally, you may want to attach your own custom tags to entries. To accomplish this, you may use the `Telescope::tag` method. The `tag` method accepts a closure which should return an array of tags. The tags returned by the closure will be merged with any tags Telescope would automatically attach to the entry. Typically, you should call the `tag` method within the `register` method of your `App\Providers\TelescopeServiceProvider` class: - use Laravel\Telescope\IncomingEntry; - use Laravel\Telescope\Telescope; - - /** - * Register any application services. - * - * @return void - */ - public function register() - { - $this->hideSensitiveRequestDetails(); - - Telescope::tag(function (IncomingEntry $entry) { - return $entry->type === 'request' - ? ['status:'.$entry->content['response_status']] - : []; - }); - } +```php +use Laravel\Telescope\EntryType; +use Laravel\Telescope\IncomingEntry; +use Laravel\Telescope\Telescope; + +/** + * Register any application services. + */ +public function register(): void +{ + $this->hideSensitiveRequestDetails(); + + Telescope::tag(function (IncomingEntry $entry) { + return $entry->type === EntryType::REQUEST + ? ['status:'.$entry->content['response_status']] + : []; + }); +} +``` ## Available Watchers Telescope "watchers" gather application data when a request or console command is executed. You may customize the list of watchers that you would like to enable within your `config/telescope.php` configuration file: - 'watchers' => [ - Watchers\CacheWatcher::class => true, - Watchers\CommandWatcher::class => true, - ... - ], +```php +'watchers' => [ + Watchers\CacheWatcher::class => true, + Watchers\CommandWatcher::class => true, + // ... +], +``` Some watchers also allow you to provide additional customization options: - 'watchers' => [ - Watchers\QueryWatcher::class => [ - 'enabled' => env('TELESCOPE_QUERY_WATCHER', true), - 'slow' => 100, - ], - ... +```php +'watchers' => [ + Watchers\QueryWatcher::class => [ + 'enabled' => env('TELESCOPE_QUERY_WATCHER', true), + 'slow' => 100, ], + // ... +], +``` ### Batch Watcher @@ -292,13 +308,15 @@ The cache watcher records data when a cache key is hit, missed, updated and forg The command watcher records the arguments, options, exit code, and output whenever an Artisan command is executed. If you would like to exclude certain commands from being recorded by the watcher, you may specify the command in the `ignore` option within your `config/telescope.php` file: - 'watchers' => [ - Watchers\CommandWatcher::class => [ - 'enabled' => env('TELESCOPE_COMMAND_WATCHER', true), - 'ignore' => ['key:generate'], - ], - ... +```php +'watchers' => [ + Watchers\CommandWatcher::class => [ + 'enabled' => env('TELESCOPE_COMMAND_WATCHER', true), + 'ignore' => ['key:generate'], ], + // ... +], +``` ### Dump Watcher @@ -320,13 +338,15 @@ The exception watcher records the data and stack trace for any reportable except The gate watcher records the data and result of [gate and policy](/docs/{{version}}/authorization) checks by your application. If you would like to exclude certain abilities from being recorded by the watcher, you may specify those in the `ignore_abilities` option in your `config/telescope.php` file: - 'watchers' => [ - Watchers\GateWatcher::class => [ - 'enabled' => env('TELESCOPE_GATE_WATCHER', true), - 'ignore_abilities' => ['viewNova'], - ], - ... +```php +'watchers' => [ + Watchers\GateWatcher::class => [ + 'enabled' => env('TELESCOPE_GATE_WATCHER', true), + 'ignore_abilities' => ['viewNova'], ], + // ... +], +``` ### HTTP Client Watcher @@ -343,6 +363,19 @@ The job watcher records the data and status of any [jobs](/docs/{{version}}/queu The log watcher records the [log data](/docs/{{version}}/logging) for any logs written by your application. +By default, Telescope will only record logs at the `error` level and above. However, you can modify the `level` option in your application's `config/telescope.php` configuration file to modify this behavior: + +```php +'watchers' => [ + Watchers\LogWatcher::class => [ + 'enabled' => env('TELESCOPE_LOG_WATCHER', true), + 'level' => 'debug', + ], + + // ... +], +``` + ### Mail Watcher @@ -353,24 +386,28 @@ The mail watcher allows you to view an in-browser preview of [emails](/docs/{{ve The model watcher records model changes whenever an Eloquent [model event](/docs/{{version}}/eloquent#events) is dispatched. You may specify which model events should be recorded via the watcher's `events` option: - 'watchers' => [ - Watchers\ModelWatcher::class => [ - 'enabled' => env('TELESCOPE_MODEL_WATCHER', true), - 'events' => ['eloquent.created*', 'eloquent.updated*'], - ], - ... +```php +'watchers' => [ + Watchers\ModelWatcher::class => [ + 'enabled' => env('TELESCOPE_MODEL_WATCHER', true), + 'events' => ['eloquent.created*', 'eloquent.updated*'], ], + // ... +], +``` If you would like to record the number of models hydrated during a given request, enable the `hydrations` option: - 'watchers' => [ - Watchers\ModelWatcher::class => [ - 'enabled' => env('TELESCOPE_MODEL_WATCHER', true), - 'events' => ['eloquent.created*', 'eloquent.updated*'], - 'hydrations' => true, - ], - ... +```php +'watchers' => [ + Watchers\ModelWatcher::class => [ + 'enabled' => env('TELESCOPE_MODEL_WATCHER', true), + 'events' => ['eloquent.created*', 'eloquent.updated*'], + 'hydrations' => true, ], + // ... +], +``` ### Notification Watcher @@ -382,13 +419,15 @@ The notification watcher records all [notifications](/docs/{{version}}/notificat The query watcher records the raw SQL, bindings, and execution time for all queries that are executed by your application. The watcher also tags any queries slower than 100 milliseconds as `slow`. You may customize the slow query threshold using the watcher's `slow` option: - 'watchers' => [ - Watchers\QueryWatcher::class => [ - 'enabled' => env('TELESCOPE_QUERY_WATCHER', true), - 'slow' => 50, - ], - ... +```php +'watchers' => [ + Watchers\QueryWatcher::class => [ + 'enabled' => env('TELESCOPE_QUERY_WATCHER', true), + 'slow' => 50, ], + // ... +], +``` ### Redis Watcher @@ -400,13 +439,15 @@ The Redis watcher records all [Redis](/docs/{{version}}/redis) commands executed The request watcher records the request, headers, session, and response data associated with any requests handled by the application. You may limit your recorded response data via the `size_limit` (in kilobytes) option: - 'watchers' => [ - Watchers\RequestWatcher::class => [ - 'enabled' => env('TELESCOPE_REQUEST_WATCHER', true), - 'size_limit' => env('TELESCOPE_RESPONSE_SIZE_LIMIT', 64), - ], - ... +```php +'watchers' => [ + Watchers\RequestWatcher::class => [ + 'enabled' => env('TELESCOPE_REQUEST_WATCHER', true), + 'size_limit' => env('TELESCOPE_RESPONSE_SIZE_LIMIT', 64), ], + // ... +], +``` ### Schedule Watcher @@ -423,19 +464,21 @@ The view watcher records the [view](/docs/{{version}}/views) name, path, data, a The Telescope dashboard displays the user avatar for the user that was authenticated when a given entry was saved. By default, Telescope will retrieve avatars using the Gravatar web service. However, you may customize the avatar URL by registering a callback in your `App\Providers\TelescopeServiceProvider` class. The callback will receive the user's ID and email address and should return the user's avatar image URL: - use App\Models\User; - use Laravel\Telescope\Telescope; - - /** - * Register any application services. - * - * @return void - */ - public function register() - { - // ... - - Telescope::avatar(function ($id, $email) { - return '/avatars/'.User::find($id)->avatar_path; - }); - } +```php +use App\Models\User; +use Laravel\Telescope\Telescope; + +/** + * Register any application services. + */ +public function register(): void +{ + // ... + + Telescope::avatar(function (?string $id, ?string $email) { + return ! is_null($id) + ? '/avatars/'.User::find($id)->avatar_path + : '/generic-avatar.jpg'; + }); +} +``` diff --git a/testing.md b/testing.md index 1293f246a27..8532d5235ba 100644 --- a/testing.md +++ b/testing.md @@ -4,36 +4,32 @@ - [Environment](#environment) - [Creating Tests](#creating-tests) - [Running Tests](#running-tests) - - [Running Tests In Parallel](#running-tests-in-parallel) + - [Running Tests in Parallel](#running-tests-in-parallel) - [Reporting Test Coverage](#reporting-test-coverage) + - [Profiling Tests](#profiling-tests) ## Introduction -Laravel is built with testing in mind. In fact, support for testing with PHPUnit is included out of the box and a `phpunit.xml` file is already set up for your application. The framework also ships with convenient helper methods that allow you to expressively test your applications. +Laravel is built with testing in mind. In fact, support for testing with [Pest](https://pestphp.com) and [PHPUnit](https://phpunit.de) is included out of the box and a `phpunit.xml` file is already set up for your application. The framework also ships with convenient helper methods that allow you to expressively test your applications. By default, your application's `tests` directory contains two directories: `Feature` and `Unit`. Unit tests are tests that focus on a very small, isolated portion of your code. In fact, most unit tests probably focus on a single method. Tests within your "Unit" test directory do not boot your Laravel application and therefore are unable to access your application's database or other framework services. Feature tests may test a larger portion of your code, including how several objects interact with each other or even a full HTTP request to a JSON endpoint. **Generally, most of your tests should be feature tests. These types of tests provide the most confidence that your system as a whole is functioning as intended.** -An `ExampleTest.php` file is provided in both the `Feature` and `Unit` test directories. After installing a new Laravel application, execute the `vendor/bin/phpunit` or `php artisan test` commands to run your tests. +An `ExampleTest.php` file is provided in both the `Feature` and `Unit` test directories. After installing a new Laravel application, execute the `vendor/bin/pest`, `vendor/bin/phpunit`, or `php artisan test` commands to run your tests. ## Environment -When running tests, Laravel will automatically set the [configuration environment](/docs/{{version}}/configuration#environment-configuration) to `testing` because of the environment variables defined in the `phpunit.xml` file. Laravel also automatically configures the session and cache to the `array` driver while testing, meaning no session or cache data will be persisted while testing. +When running tests, Laravel will automatically set the [configuration environment](/docs/{{version}}/configuration#environment-configuration) to `testing` because of the environment variables defined in the `phpunit.xml` file. Laravel also automatically configures the session and cache to the `array` driver so that no session or cache data will be persisted while testing. You are free to define other testing environment configuration values as necessary. The `testing` environment variables may be configured in your application's `phpunit.xml` file, but make sure to clear your configuration cache using the `config:clear` Artisan command before running your tests! #### The `.env.testing` Environment File -In addition, you may create a `.env.testing` file in the root of your project. This file will be used instead of the `.env` file when running PHPUnit tests or executing Artisan commands with the `--env=testing` option. - - -#### The `CreatesApplication` Trait - -Laravel includes a `CreatesApplication` trait that is applied to your application's base `TestCase` class. This trait contains a `createApplication` method that bootstraps the Laravel application before running your tests. It's important that you leave this trait at its original location as some features, such as Laravel's parallel testing feature, depend on it. +In addition, you may create a `.env.testing` file in the root of your project. This file will be used instead of the `.env` file when running Pest and PHPUnit tests or executing Artisan commands with the `--env=testing` option. ## Creating Tests @@ -50,65 +46,74 @@ If you would like to create a test within the `tests/Unit` directory, you may us php artisan make:test UserTest --unit ``` -If you would like to create a [Pest PHP](https://pestphp.com) test, you may provide the `--pest` option to the `make:test` command: +> [!NOTE] +> Test stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization). -```shell -php artisan make:test UserTest --pest -php artisan make:test UserTest --unit --pest -``` +Once the test has been generated, you may define test as you normally would using Pest or PHPUnit. To run your tests, execute the `vendor/bin/pest`, `vendor/bin/phpunit`, or `php artisan test` command from your terminal: -> {tip} Test stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization). +```php tab=Pest +toBeTrue(); +}); +``` - assertTrue(true); - } + $this->assertTrue(true); } +} +``` -> {note} If you define your own `setUp` / `tearDown` methods within a test class, be sure to call the respective `parent::setUp()` / `parent::tearDown()` methods on the parent class. +> [!WARNING] +> If you define your own `setUp` / `tearDown` methods within a test class, be sure to call the respective `parent::setUp()` / `parent::tearDown()` methods on the parent class. Typically, you should invoke `parent::setUp()` at the start of your own `setUp` method, and `parent::tearDown()` at the end of your `tearDown` method. ## Running Tests -As mentioned previously, once you've written tests, you may run them using `phpunit`: +As mentioned previously, once you've written tests, you may run them using `pest` or `phpunit`: -```shell +```shell tab=Pest +./vendor/bin/pest +``` + +```shell tab=PHPUnit ./vendor/bin/phpunit ``` -In addition to the `phpunit` command, you may use the `test` Artisan command to run your tests. The Artisan test runner provides verbose test reports in order to ease development and debugging: +In addition to the `pest` or `phpunit` commands, you may use the `test` Artisan command to run your tests. The Artisan test runner provides verbose test reports in order to ease development and debugging: ```shell php artisan test ``` -Any arguments that can be passed to the `phpunit` command may also be passed to the Artisan `test` command: +Any arguments that can be passed to the `pest` or `phpunit` commands may also be passed to the Artisan `test` command: ```shell php artisan test --testsuite=Feature --stop-on-failure ``` -### Running Tests In Parallel +### Running Tests in Parallel -By default, Laravel and PHPUnit execute your tests sequentially within a single process. However, you may greatly reduce the amount of time it takes to run your tests by running tests simultaneously across multiple processes. To get started, ensure your application depends on version `^5.3` or greater of the `nunomaduro/collision` package. Then, include the `--parallel` option when executing the `test` Artisan command: +By default, Laravel and Pest / PHPUnit execute your tests sequentially within a single process. However, you may greatly reduce the amount of time it takes to run your tests by running tests simultaneously across multiple processes. To get started, you should install the `brianium/paratest` Composer package as a "dev" dependency. Then, include the `--parallel` option when executing the `test` Artisan command: ```shell +composer require brianium/paratest --dev + php artisan test --parallel ``` @@ -118,12 +123,13 @@ By default, Laravel will create as many processes as there are available CPU cor php artisan test --parallel --processes=4 ``` -> {note} When running tests in parallel, some PHPUnit options (such as `--do-not-cache-result`) may not be available. +> [!WARNING] +> When running tests in parallel, some Pest / PHPUnit options (such as `--do-not-cache-result`) may not be available. -#### Parallel Testing & Databases +#### Parallel Testing and Databases -Laravel automatically handles creating and migrating a test database for each parallel process that is running your tests. The test databases will be suffixed with a process token which is unique per process. For example, if you have two parallel test processes, Laravel will create and use `your_db_test_1` and `your_db_test_2` test databases. +As long as you have configured a primary database connection, Laravel automatically handles creating and migrating a test database for each parallel process that is running your tests. The test databases will be suffixed with a process token which is unique per process. For example, if you have two parallel test processes, Laravel will create and use `your_db_test_1` and `your_db_test_2` test databases. By default, test databases persist between calls to the `test` Artisan command so that they can be used again by subsequent `test` invocations. However, you may re-create them using the `--recreate-databases` option: @@ -138,57 +144,59 @@ Occasionally, you may need to prepare certain resources used by your application Using the `ParallelTesting` facade, you may specify code to be executed on the `setUp` and `tearDown` of a process or test case. The given closures receive the `$token` and `$testCase` variables that contain the process token and the current test case, respectively: - -#### Accessing The Parallel Testing Token +#### Accessing the Parallel Testing Token -If you would like to access to current parallel process "token" from any other location in your application's test code, you may use the `token` method. This token is a unique, string identifier for an individual test process and may be used to segment resources across parallel test processes. For example, Laravel automatically appends this token to the end of the test databases created by each parallel testing process: +If you would like to access the current parallel process "token" from any other location in your application's test code, you may use the `token` method. This token is a unique, string identifier for an individual test process and may be used to segment resources across parallel test processes. For example, Laravel automatically appends this token to the end of the test databases created by each parallel testing process: $token = ParallelTesting::token(); ### Reporting Test Coverage -> {note} This feature requires [Xdebug](https://xdebug.org) or [PCOV](https://pecl.php.net/package/pcov). +> [!WARNING] +> This feature requires [Xdebug](https://xdebug.org) or [PCOV](https://pecl.php.net/package/pcov). When running your application tests, you may want to determine whether your test cases are actually covering the application code and how much application code is used when running your tests. To accomplish this, you may provide the `--coverage` option when invoking the `test` command: @@ -197,10 +205,19 @@ php artisan test --coverage ``` -#### Enforcing A Minimum Coverage Threshold +#### Enforcing a Minimum Coverage Threshold You may use the `--min` option to define a minimum test coverage threshold for your application. The test suite will fail if this threshold is not met: ```shell php artisan test --coverage --min=80.3 ``` + + +### Profiling Tests + +The Artisan test runner also includes a convenient mechanism for listing your application's slowest tests. Invoke the `test` command with the `--profile` option to be presented with a list of your ten slowest tests, allowing you to easily investigate which tests can be improved to speed up your test suite: + +```shell +php artisan test --profile +``` diff --git a/upgrade.md b/upgrade.md index 9ded856ed74..ae70332c303 100644 --- a/upgrade.md +++ b/upgrade.md @@ -1,6 +1,6 @@ # Upgrade Guide -- [Upgrading To 9.0 From 8.x](#upgrade-9.0) +- [Upgrading To 12.0 From 11.x](#upgrade-12.0) ## High Impact Changes @@ -8,8 +8,7 @@
- [Updating Dependencies](#updating-dependencies) -- [Flysystem 3.x](#flysystem-3) -- [Symfony Mailer](#symfony-mailer) +- [Updating the Laravel Installer](#updating-the-laravel-installer)
@@ -18,680 +17,241 @@
-- [Belongs To Many `firstOrNew`, `firstOrCreate`, and `updateOrCreate` methods](#belongs-to-many-first-or-new) -- [Custom Casts & `null`](#custom-casts-and-null) -- [Default HTTP Client Timeout](#http-client-default-timeout) -- [PHP Return Types](#php-return-types) -- [Postgres "Schema" Configuration](#postgres-schema-configuration) -- [The `assertDeleted` Method](#the-assert-deleted-method) -- [The `lang` Directory](#the-lang-directory) -- [The `password` Rule](#the-password-rule) -- [The `when` / `unless` Methods](#when-and-unless-methods) -- [Unvalidated Array Keys](#unvalidated-array-keys) +- [Models and UUIDv7](#models-and-uuidv7)
- -## Upgrading To 9.0 From 8.x - - -#### Estimated Upgrade Time: 30 Minutes - -> {tip} We attempt to document every possible breaking change. Since some of these breaking changes are in obscure parts of the framework only a portion of these changes may actually affect your application. Want to save time? You can use [Laravel Shift](https://laravelshift.com/) to help automate your application upgrades. - - -### Updating Dependencies - -**Likelihood Of Impact: High** - -#### PHP 8.0.2 Required - -Laravel now requires PHP 8.0.2 or greater. - -#### Composer Dependencies - -You should update the following dependencies in your application's `composer.json` file: + +## Low Impact Changes
-- `laravel/framework` to `^9.0` -- `nunomaduro/collision` to `^6.1` +- [Carbon 3](#carbon-3) +- [Concurrency Result Index Mapping](#concurrency-result-index-mapping) +- [Container Class Dependency Resolution](#container-class-dependency-resolution) +- [Image Validation Now Excludes SVGs](#image-validation) +- [Local Filesystem Disk Default Root Path](#local-filesystem-disk-default-root-path) +- [Multi-Schema Database Inspecting](#multi-schema-database-inspecting) +- [Nested Array Request Merging](#nested-array-request-merging)
-In addition, please replace `facade/ignition` with `"spatie/laravel-ignition": "^1.0"` in your application's `composer.json` file. + +## Upgrading To 12.0 From 11.x -Furthermore, the following first-party packages have received new major releases to support Laravel 9.x. If applicable, you should read their individual upgrade guides before upgrading: +#### Estimated Upgrade Time: 5 Minutes -
- -- [Vonage Notification Channel (v3.0)](https://github.com/laravel/vonage-notification-channel/blob/3.x/UPGRADE.md) (Replaces Nexmo) +> [!NOTE] +> We attempt to document every possible breaking change. Since some of these breaking changes are in obscure parts of the framework only a portion of these changes may actually affect your application. Want to save time? You can use [Laravel Shift](https://laravelshift.com/) to help automate your application upgrades. -
- -Finally, examine any other third-party packages consumed by your application and verify you are using the proper version for Laravel 9 support. - - -#### PHP Return Types - -PHP is beginning to transition to requiring return type definitions on PHP methods such as `offsetGet`, `offsetSet`, etc. In light of this, Laravel 9 has implemented these return types in its code base. Typically, this should not affect user written code; however, if you are overriding one of these methods by extending Laravel's core classes, you will need to add these return types to your own application or package code: - -
- -- `count(): int` -- `getIterator(): Traversable` -- `getSize(): int` -- `jsonSerialize(): array` -- `offsetExists($key): bool` -- `offsetGet($key): mixed` -- `offsetSet($key, $value): void` -- `offsetUnset($key): void` + +### Updating Dependencies -
+**Likelihood Of Impact: High** -In addition, return types were added to methods implementing PHP's `SessionHandlerInterface`. Again, it is unlikely that this change affects your own application or package code: +You should update the following dependencies in your application's `composer.json` file:
-- `open($savePath, $sessionName): bool` -- `close(): bool` -- `read($sessionId): string|false` -- `write($sessionId, $data): bool` -- `destroy($sessionId): bool` -- `gc($lifetime): int` +- `laravel/framework` to `^12.0` +- `phpunit/phpunit` to `^11.0` +- `pestphp/pest` to `^3.0`
- -### Application - - -#### The `Application` Contract + +#### Carbon 3 **Likelihood Of Impact: Low** -The `storagePath` method of the `Illuminate\Contracts\Foundation\Application` interface has been updated to accept a `$path` argument. If you are implementing this interface you should update your implementation accordingly: - - public function storagePath($path = ''); - -Similarly, the `langPath` method of the `Illuminate\Foundation\Application` class has been updated to accept a `$path` argument: - - public function langPath($path = ''); +Support for [Carbon 2.x](https://carbon.nesbot.com/docs/) has been removed. All Laravel 12 applications now require [Carbon 3.x](https://carbon.nesbot.com/docs/#api-carbon-3). -#### Exception Handler `ignore` Method + +### Updating the Laravel Installer -**Likelihood Of Impact: Low** - -The exception handler's `ignore` method is now `public` instead of `protected`. This method is not included in the default application skeleton; however, if you have manually defined this method you should update its visibility to `public`: +If you are using the Laravel installer CLI tool to create new Laravel applications, you should update your installer installation to be compatible with Laravel 12.x and the [new Laravel starter kits](https://laravel.com/starter-kits). If you installed the Laravel installer via `composer global require`, you may update the installer using `composer global update`: -```php -public function ignore(string $class); +```shell +composer global update laravel/installer ``` -### Blade - -#### Lazy Collections & The `$loop` Variable - -**Likelihood Of Impact: Low** - -When iterating over a `LazyCollection` instance within a Blade template, the `$loop` variable is no longer available, as accessing this variable causes the entire `LazyCollection` to be loaded into memory, thus rendering the usage of lazy collections pointless in this scenario. +If you originally installed PHP and Laravel via `php.new`, you may simply re-run the `php.new` installation commands for your operating system to install the latest version of PHP and the Laravel installer: -### Collections - -#### The `Enumerable` Contract - -**Likelihood Of Impact: Low** - -The `Illuminate\Support\Enumerable` contract now defines a `sole` method. If you are manually implementing this interface, you should update your implementation to reflect this new method: - -```php -public function sole($key = null, $operator = null, $value = null); +```shell tab=macOS +/bin/bash -c "$(curl -fsSL https://php.new/install/mac/8.4)" ``` -#### The `reduceWithKeys` Method - -The `reduceWithKeys` method has been removed as the `reduce` method provides the same functionality. You may simply update your code to call `reduce` instead of `reduceWithKeys`. - -#### The `reduceMany` Method - -The `reduceMany` method has been renamed to `reduceSpread` for naming consistency with other similar methods. - -### Container - -#### The `Container` Contract - -**Likelihood Of Impact: Very Low** - -The `Illuminate\Contracts\Container\Container` contract has received two method definitions: `scoped` and `scopedIf`. If you are manually implementing this contract, you should update your implementation to reflect these new methods. - -#### The `ContextualBindingBuilder` Contract - -**Likelihood Of Impact: Very Low** - -The `Illuminate\Contracts\Container\ContextualBindingBuilder` contract now defines a `giveConfig` method. If you are manually implementing this interface, you should update your implementation to reflect this new method: - -```php -public function giveConfig($key, $default = null); +```shell tab=Windows PowerShell +# Run as administrator... +Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://php.new/install/windows/8.4')) ``` -### Database - - -#### Postgres "Schema" Configuration - -**Likelihood Of Impact: Medium** - -The `schema` configuration option used to configure Postgres connection search paths in your application's `config/database.php` configuration file should be renamed to `search_path`. - - -#### Schema Builder `registerCustomDoctrineType` Method - -**Likelihood Of Impact: Low** - -The `registerCustomDoctrineType` method has been removed from the `Illuminate\Database\Schema\Builder` class. You may use the `registerDoctrineType` method on the `DB` facade instead, or register custom Doctrine types in the `config/database.php` configuration file. - -### Eloquent - - -#### Custom Casts & `null` - -**Likelihood Of Impact: Medium** - -In previous releases of Laravel, the `set` method of custom cast classes was not invoked if the cast attribute was being set to `null`. However, this behavior was inconsistent with the Laravel documentation. In Laravel 9.x, the `set` method of the cast class will be invoked with `null` as the provided `$value` argument. Therefore, you should ensure your custom casts are able to sufficiently handle this scenario: - -```php -/** - * Prepare the given value for storage. - * - * @param \Illuminate\Database\Eloquent\Model $model - * @param string $key - * @param AddressModel $value - * @param array $attributes - * @return array - */ -public function set($model, $key, $value, $attributes) -{ - if (! $value instanceof AddressModel) { - throw new InvalidArgumentException('The given value is not an Address instance.'); - } - - return [ - 'address_line_one' => $value->lineOne, - 'address_line_two' => $value->lineTwo, - ]; -} +```shell tab=Linux +/bin/bash -c "$(curl -fsSL https://php.new/install/linux/8.4)" ``` - -#### Belongs To Many `firstOrNew`, `firstOrCreate`, and `updateOrCreate` Methods +Or, if you are using [Laravel Herd's](https://herd.laravel.com) bundled copy of the Laravel installer, you should update your Herd installation to the latest release. -**Likelihood Of Impact: Medium** - -The `belongsToMany` relationship's `firstOrNew`, `firstOrCreate`, and `updateOrCreate` methods all accept an array of attributes as their first argument. In previous releases of Laravel, this array of attributes was compared against the "pivot" / intermediate table for existing records. + +### Authentication -However, this behavior was unexpected and typically unwanted. Instead, these methods now compare the array of attributes against the table of the related model: + +#### Updated `DatabaseTokenRepository` Constructor Signature -```php -$user->roles()->updateOrCreate([ - 'name' => 'Administrator', -]); -``` +**Likelihood Of Impact: Very Low** -In addition, the `firstOrCreate` method now accepts a `$values` array as its second argument. This array will be merged with the first argument to the method (`$attributes`) when creating the related model if one does not already exist. This change makes this method consistent with the `firstOrCreate` methods offered by other relationship types: +The constructor of the `Illuminate\Auth\Passwords\DatabaseTokenRepository` class now expects the `$expires` parameter to be given in seconds, rather than minutes. -```php -$user->roles()->firstOrCreate([ - 'name' => 'Administrator', -], [ - 'created_by' => $user->id, -]); -``` + +### Concurrency -#### The `touch` Method + +#### Concurrency Result Index Mapping **Likelihood Of Impact: Low** -The `touch` method now accepts an attribute to touch. If you were previously overwriting this method, you should update your method signature to reflect this new argument: +When invoking the `Concurrency::run` method with an associative array, the results of the concurrent operations are now returned with their associated keys: ```php -public function touch($attribute = null); -``` - -### Encryption - -#### The Encrypter Contract - -**Likelihood Of Impact: Low** - -The `Illuminate\Contracts\Encryption\Encrypter` contract now defines a `getKey` method. If you are manually implementing this interface, you should update your implementation accordingly: +$result = Concurrency::run([ + 'task-1' => fn () => 1 + 1, + 'task-2' => fn () => 2 + 2, +]); -```php -public function getKey(); +// ['task-1' => 2, 'task-2' => 4] ``` -### Facades + +### Container -#### The `getFacadeAccessor` Method + +#### Container Class Dependency Resolution **Likelihood Of Impact: Low** -The `getFacadeAccessor` method must always return a container binding key. In previous releases of Laravel, this method could return an object instance; however, this behavior is no longer supported. If you have written your own facades, you should ensure that this method returns a container binding string: +The dependency injection container now respects the default value of class properties when resolving a class instance. If you were previously relying on the container to resolve a class instance without the default value, you may need to adjust your application to account for this new behavior: ```php -/** - * Get the registered name of the component. - * - * @return string - */ -protected static function getFacadeAccessor() +class Example { - return Example::class; + public function __construct(public ?Carbon $date = null) {} } -``` -### Filesystem +$example = resolve(Example::class); -#### The `FILESYSTEM_DRIVER` Environment Variable +// <= 11.x +$example->date instanceof Carbon; -**Likelihood Of Impact: Low** +// >= 12.x +$example->date === null; +``` -The `FILESYSTEM_DRIVER` environment variable has been renamed to `FILESYSTEM_DISK` to more accurately reflect its usage. This change only affects the application skeleton; however, you are welcome to update your own application's environment variables to reflect this change if you wish. + +### Database -#### The "Cloud" Disk + +#### Multi-Schema Database Inspecting **Likelihood Of Impact: Low** -The `cloud` disk configuration option was removed from the default application skeleton in November of 2020. This change only affects the application skeleton. If you are using the `cloud` disk within your application, you should leave this configuration value in your own application's skeleton. - - -### Flysystem 3.x - -**Likelihood Of Impact: High** - -Laravel 9.x has migrated from [Flysystem](https://flysystem.thephpleague.com/v2/docs/) 1.x to 3.x. Under the hood, Flysystem powers all of the file manipulation methods provided by the `Storage` facade. In light of this, some changes may be required within your application; however, we have tried to make this transition as seamless as possible. - -#### Driver Prerequisites - -Before using the S3, FTP, or SFTP drivers, you will need to install the appropriate package via the Composer package manager: - -- Amazon S3: `composer require -W league/flysystem-aws-s3-v3 "^3.0"` -- FTP: `composer require league/flysystem-ftp "^3.0"` -- SFTP: `composer require league/flysystem-sftp-v3 "^3.0"` - -#### Overwriting Existing Files - -Write operations such as `put`, `write`, `writeStream` now overwrite existing files by default. If you do not want to overwrite existing files, you should manually check for the file's existence before performing the write operation. +The `Schema::getTables()`, `Schema::getViews()`, and `Schema::getTypes()` methods now include the results from all schemas by default. You may pass the `schema` argument to retrieve the result for the given schema only: -#### Reading Missing Files - -Attempting to read from a file that does not exist now returns `null`. In previous releases of Laravel, an `Illuminate\Contracts\Filesystem\FileNotFoundException` would have been thrown. - -#### Deleting Missing Files - -Attempting to `delete` a file that does not exist now returns `true`. - -#### Cached Adapters - -Flysystem no longer supports "cached adapters". Thus, they have been removed from Laravel and any relevant configuration (such as the `cache` key within disk configurations) can be removed. +```php +// All tables on all schemas... +$tables = Schema::getTables(); -#### Custom Filesystems +// All tables on the 'main' schema... +$tables = Schema::getTables(schema: 'main'); -Slight changes have been made to the steps required to register custom filesystem drivers. Therefore, if you were defining your own custom filesystem drivers, or using packages that define custom drivers, you should update your code and dependencies. +// All tables on the 'main' and 'blog' schemas... +$tables = Schema::getTables(schema: ['main', 'blog']); +``` -For example, in Laravel 8.x, a custom filesystem driver might be registered like so: +The `Schema::getTableListing()` method now returns schema-qualified table names by default. You may pass the `schemaQualified` argument to change the behavior as desired: ```php -use Illuminate\Support\Facades\Storage; -use League\Flysystem\Filesystem; -use Spatie\Dropbox\Client as DropboxClient; -use Spatie\FlysystemDropbox\DropboxAdapter; - -Storage::extend('dropbox', function ($app, $config) { - $client = new DropboxClient( - $config['authorization_token'] - ); - - return new Filesystem(new DropboxAdapter($client)); -}); -``` +$tables = Schema::getTableListing(); +// ['main.migrations', 'main.users', 'blog.posts'] -However, in Laravel 9.x, the callback given to the `Storage::extend` method should return an instance of `Illuminate\Filesystem\FilesystemAdapter` directly: +$tables = Schema::getTableListing(schema: 'main'); +// ['main.migrations', 'main.users'] -```php -use Illuminate\Filesystem\FilesystemAdapter; -use Illuminate\Support\Facades\Storage; -use League\Flysystem\Filesystem; -use Spatie\Dropbox\Client as DropboxClient; -use Spatie\FlysystemDropbox\DropboxAdapter; - -Storage::extend('dropbox', function ($app, $config) { - $adapter = new DropboxAdapter(new DropboxClient( - $config['authorization_token'] - );); - - return new FilesystemAdapter( - new Filesystem($adapter, $config), - $adapter, - $config - ); -}); +$tables = Schema::getTableListing(schema: 'main', schemaQualified: false); +// ['migrations', 'users'] ``` -### Helpers +The `db:table` and `db:show` commands now output the results of all schemas on MySQL, MariaDB, and SQLite, just like PostgreSQL and SQL Server. - -#### The `data_get` Helper & Iterable Objects + +#### Updated `Blueprint` Constructor Signature **Likelihood Of Impact: Very Low** -Previously, the `data_get` helper could be used to retrieve nested data on arrays and `Collection` instances; however, this helper can now retrieve nested data on all iterable objects. - - -#### The `str` Helper - -**Likelihood Of Impact: Very Low** +The constructor of the `Illuminate\Database\Schema\Blueprint` class now expects an instance of `Illuminate\Database\Connection` as its first argument. -Laravel 9.x now includes a global `str` [helper function](/docs/{{version}}/helpers#method-str). If you are defining a global `str` helper in your application, you should rename or remove it so that it does not conflict with Laravel's own `str` helper. + +### Eloquent - -#### The `when` / `unless` Methods + +#### Models and UUIDv7 **Likelihood Of Impact: Medium** -As you may know, `when` and `unless` methods are offered by various classes throughout the framework. These methods can be used to conditionally perform an action if the boolean value of the first argument to the method evaluates to `true` or `false`: +The `HasUuids` trait now returns UUIDs that are compatible with version 7 of the UUID spec (ordered UUIDs). If you would like to continue using ordered UUIDv4 strings for your model's IDs, you should now use the `HasVersion4Uuids` trait: ```php -$collection->when(true, function ($collection) { - $collection->merge([1, 2, 3]); -}); +use Illuminate\Database\Eloquent\Concerns\HasUuids; // [tl! remove] +use Illuminate\Database\Eloquent\Concerns\HasVersion4Uuids as HasUuids; // [tl! add] ``` -Therefore, in previous releases of Laravel, passing a closure to the `when` or `unless` methods meant that the conditional operation would always execute, since a loose comparison against a closure object (or any other object) always evaluates to `true`. This often led to unexpected outcomes because developers expect the **result** of the closure to be used as the boolean value that determines if the conditional action executes. - -So, in Laravel 9.x, any closures passed to the `when` or `unless` methods will be executed and the value returned by the closure will be considered the boolean value used by the `when` and `unless` methods: - -```php -$collection->when(function ($collection) { - // This closure is executed... - return false; -}, function ($collection) { - // Not executed since first closure returned "false"... - $collection->merge([1, 2, 3]); -}); -``` - -### HTTP Client - - -#### Default Timeout - -**Likelihood Of Impact: Medium** - -The [HTTP client](/docs/{{version}}/http-client) now has a default timeout of 30 seconds. In other words, if the server does not respond within 30 seconds, an exception will be thrown. Previously, no default timeout length was configured on the HTTP client, causing requests to sometimes "hang" indefinitely. - -If you wish to specify a longer timeout for a given request, you may do so using the `timeout` method: - - $response = Http::timeout(120)->get(...); - -#### HTTP Fake & Middleware - -**Likelihood Of Impact: Low** - -Previously, Laravel would not execute any provided Guzzle HTTP middleware when the [HTTP client](/docs/{{version}}/http-client) was "faked". However, in Laravel 9.x, Guzzle HTTP middleware will be executed even when the HTTP client is faked. - -#### HTTP Fake & Dependency Injection - -**Likelihood Of Impact: Low** - -In previous releases of Laravel, invoking the `Http::fake()` method would not affect instances of the `Illuminate\Http\Client\Factory` that were injected into class constructors. However, in Laravel 9.x, `Http::fake()` will ensure fake responses are returned by HTTP clients injected into other services via dependency injection. This behavior is more consistent with the behavior of other facades and fakes. - - -### Symfony Mailer - -**Likelihood Of Impact: High** - -One of the largest changes in Laravel 9.x is the transition from SwiftMailer, which is no longer maintained as of December 2021, to Symfony Mailer. However, we have tried to make this transition as seamless as possible for your applications. That being said, please thoroughly review the list of changes below to ensure your application is fully compatible. - -#### Driver Prerequisites - -To continue using the Mailgun transport, your application should require the `symfony/mailgun-mailer` and `symfony/http-client` Composer packages: - -```shell -composer require symfony/mailgun-mailer symfony/http-client -``` - -The `wildbit/swiftmailer-postmark` Composer package should be removed from your application. Instead, your application should require the `symfony/postmark-mailer` and `symfony/http-client` Composer packages: - -```shell -composer require symfony/postmark-mailer symfony/http-client -``` - -#### Updated Return Types - -The `send`, `html`, `text`, and `plain` methods no longer return the number of recipients that received the message. Instead, an instance of `Illuminate\Mail\SentMessage` is returned. This object contains an instance of `Symfony\Component\Mailer\SentMessage` that is accessible via the `getSymfonySentMessage` method or by dynamically invoking methods on the object. - -#### Renamed "Swift" Methods - -Various SwiftMailer related methods, some of which were undocumented, have been renamed to their Symfony Mailer counterparts. For example, the `withSwiftMessage` method has been renamed to `withSymfonyMessage`: - - // Laravel 8.x... - $this->withSwiftMessage(function ($message) { - $message->getHeaders()->addTextHeader( - 'Custom-Header', 'Header Value' - ); - }); - - // Laravel 9.x... - use Symfony\Component\Mime\Email; - - $this->withSymfonyMessage(function (Email $message) { - $message->getHeaders()->addTextHeader( - 'Custom-Header', 'Header Value' - ); - }); - -> {note} Please thoroughly review the [Symfony Mailer documentation](https://symfony.com/doc/6.0/mailer.html#creating-sending-messages) for all possible interactions with the `Symfony\Component\Mime\Email` object. - -The list below contains a more thorough overview of renamed methods. Many of these methods are low-level methods used to interact with SwiftMailer / Symfony Mailer directly, so may not be commonly used within most Laravel applications: - - Message::getSwiftMessage(); - Message::getSymfonyMessage(); - - Mailable::withSwiftMessage($callback); - Mailable::withSymfonyMessage($callback); - - MailMessage::withSwiftMessage($callback); - MailMessage::withSymfonyMessage($callback); - - Mailer::getSwiftMailer(); - Mailer::getSymfonyTransport(); - - Mailer::setSwiftMailer($swift); - Mailer::setSymfonyTransport(TransportInterface $transport); - - MailManager::createTransport($config); - MailManager::createSymfonyTransport($config); - -#### Proxied `Illuminate\Mail\Message` Methods - -The `Illuminate\Mail\Message` typically proxied missing methods to the underlying `Swift_Message` instance. However, missing methods are now proxied to an instance of `Symfony\Component\Mime\Email` instead. So, any code that was previously relying on missing methods to be proxied to SwiftMailer should be updated to their corresponding Symfony Mailer counterparts. - -Again, many applications may not be interacting with these methods, as they are not documented within the Laravel documentation: - - // Laravel 8.x... - $message - ->setFrom('taylor@laravel.com') - ->setTo('example@example.org') - ->setSubject('Order Shipped') - ->setBody('

HTML

', 'text/html') - ->addPart('Plain Text', 'text/plain'); +The `HasVersion7Uuids` trait has been removed. If you were previously using this trait, you should use the `HasUuids` trait instead, which now provides the same behavior. - // Laravel 9.x... - $message - ->from('taylor@laravel.com') - ->to('example@example.org') - ->subject('Order Shipped') - ->html('

HTML

') - ->text('Plain Text'); + +### Requests -#### Generated Messages IDs - -SwiftMailer offered the ability to define a custom domain to include in generated Message IDs via the `mime.idgenerator.idright` configuration option. This is not supported by Symfony Mailer. Instead, Symfony Mailer will automatically generate a Message ID based on the sender. - -#### Forced Reconnections - -It is no longer possible to force a transport reconnection (for example when the mailer is running via a daemon process). Instead, Symfony Mailer will attempt to reconnect to the transport automatically and throw an exception if the reconnection fails. - -#### SMTP Stream Options - -Defining stream options for the SMTP transport is no longer supported. Instead, you must define the relevant options directly within the configuration if they are supported. For example, to disable TLS peer verification: - - 'smtp' => [ - // Laravel 8.x... - 'stream' => [ - 'ssl' => [ - 'verify_peer' => false, - ], - ], - - // Laravel 9.x... - 'verify_peer' => false, - ], - -To learn more about the available configuration options, please review the [Symfony Mailer documentation](https://symfony.com/doc/6.0/mailer.html#transport-setup). - -> {note} In spite of the example above, you are not generally advised to disable SSL verification since it introduces the possibility of "man-in-the-middle" attacks. - -#### SMTP `auth_mode` - -Defining the SMTP `auth_mode` in the `mail` configuration file is no longer required. The authentication mode will be automatically negotiated between Symfony Mailer and the SMTP server. - -#### Failed Recipients - -It is no longer possible to retrieve a list of failed recipients after sending a message. Instead, a `Symfony\Component\Mailer\Exception\TransportExceptionInterface` exception will be thrown if a message fails to send. Instead of relying on retrieving invalid email addresses after sending a message, we recommend that you validate email addresses before sending the message instead. - -### Packages - - -#### The `lang` Directory - -**Likelihood Of Impact: Medium** - -In new Laravel applications, the `resources/lang` directory is now located in the root project directory (`lang`). If your package is publishing language files to this directory, you should ensure that your package is publishing to `app()->langPath()` instead of a hard-coded path. - - -### Queue - - -#### The `opis/closure` Library - -**Likelihood Of Impact: Low** - -Laravel's dependency on `opis/closure` has been replaced by `laravel/serializable-closure`. This should not cause any breaking change in your application unless you are interacting with the `opis/closure` library directly. In addition, the previously deprecated `Illuminate\Queue\SerializableClosureFactory` and `Illuminate\Queue\SerializableClosure` classes have been removed. If you are interacting with `opis/closure` library directly or using any of the removed classes, you may use [Laravel Serializable Closure](https://github.com/laravel/serializable-closure) instead. - -#### The Failed Job Provider `flush` Method + +#### Nested Array Request Merging **Likelihood Of Impact: Low** -The `flush` method defined by the `Illuminate\Queue\Failed\FailedJobProviderInterface` interface now accepts an `$hours` argument which determines how old a failed job must be (in hours) before it is flushed by the `queue:flush` command. If you are manually implementing the `FailedJobProviderInterface` you should ensure that your implementation is updated to reflect this new argument: +The `$request->mergeIfMissing()` method now allows merging nested array data using "dot" notation. If you were previously relying on this method to create a top-level array key containing the "dot" notation version of the key, you may need to adjust your application to account for this new behavior: ```php -public function flush($hours = null); +$request->mergeIfMissing([ + 'user.last_name' => 'Otwell', +]); ``` -### Session + +### Storage -#### The `getSession` Method + +#### Local Filesystem Disk Default Root Path **Likelihood Of Impact: Low** -The `Symfony\Component\HttpFoundaton\Request` class that is extended by Laravel's own `Illuminate\Http\Request` class offers a `getSession` method to get the current session storage handler. This method is not documented by Laravel as most Laravel applications interact with the session through Laravel's own `session` method. - -The `getSession` method previously returned an instance of `Illuminate\Session\Store` or `null`; however, due to the Symfony 6.x release enforcing a return type of `Symfony\Component\HttpFoundation\Session\SessionInterface`, the `getSession` now correctly returns a `SessionInterface` implementation or throws an `\Symfony\Component\HttpFoundation\Exception\SessionNotFoundException` exception when no session is available. - -### Testing - - -#### The `assertDeleted` Method - -**Likelihood Of Impact: Medium** - -All calls to the `assertDeleted` method should be updated to `assertModelMissing`. - -### Trusted Proxies - -**Likelihood Of Impact: Low** - -If you are upgrading your Laravel 8 project to Laravel 9 by importing your existing application code into a totally new Laravel 9 application skeleton, you may need to update your application's "trusted proxy" middleware. - -Within your `app/Http/Middleware/TrustProxies.php` file, update `use Fideloper\Proxy\TrustProxies as Middleware` to `use Illuminate\Http\Middleware\TrustProxies as Middleware`. - -Next, within `app/Http/Middleware/TrustProxies.php`, you should update the `$headers` property definition: - -```php -// Before... -protected $headers = Request::HEADER_X_FORWARDED_ALL; - -// After... -protected $headers = - Request::HEADER_X_FORWARDED_FOR | - Request::HEADER_X_FORWARDED_HOST | - Request::HEADER_X_FORWARDED_PORT | - Request::HEADER_X_FORWARDED_PROTO | - Request::HEADER_X_FORWARDED_AWS_ELB; -``` - -Finally, you can remove the `fideloper/proxy` Composer dependency from your application: - -```shell -composer remove fideloper/proxy -``` +If your application does not explicitly define a `local` disk in your filesystems configuration, Laravel will now default the local disk's root to `storage/app/private`. In previous releases, this defaulted to `storage/app`. As a result, calls to `Storage::disk('local')` will read from and write to `storage/app/private` unless otherwise configured. To restore the previous behavior, you may define the `local` disk manually and set the desired root path. + ### Validation -#### Form Request `validated` Method + +#### Image Validation Now Excludes SVGs **Likelihood Of Impact: Low** -The `validated` method offered by form requests now accepts `$key` and `$default` arguments. If you are manually overwriting the definition of this method, you should update your method's signature to reflect these new arguments: +The `image` validation rule no longer allows SVG images by default. If you would like to allow SVGs when using the `image` rule, you must explicitly allow them: ```php -public function validated($key = null, $default = null) -``` - - -#### The `password` Rule - -**Likelihood Of Impact: Medium** - -The `password` rule, which validates that the given input value matches the authenticated user's current password, has been renamed to `current_password`. - - -#### Unvalidated Array Keys +use Illuminate\Validation\Rules\File; -**Likelihood Of Impact: Medium** - -In previous releases of Laravel, you were required to manually instruct Laravel's validator to exclude unvalidated array keys from the "validated" data it returns, especially in combination with an `array` rule that does not specify a list of allowed keys. - -However, in Laravel 9.x, unvalidated array keys are always excluded from the "validated" data even when no allowed keys have been specified via the `array` rule. Typically, this behavior is the most expected behavior and the previous `excludeUnvalidatedArrayKeys` method was only added to Laravel 8.x as a temporary measure in order to preserve backwards compatibility. - -Although it is not recommended, you may opt-in to the previous Laravel 8.x behavior by invoking a new `includeUnvalidatedArrayKeys` method within the `boot` method of one of your application's service providers: +'photo' => 'required|image:allow_svg' -```php -use Illuminate\Support\Facades\Validator; - -/** - * Register any application services. - * - * @return void - */ -public function boot() -{ - Validator::includeUnvalidatedArrayKeys(); -} +// Or... +'photo' => ['required', File::image(allowSvg: true)], ``` ### Miscellaneous -We also encourage you to view the changes in the `laravel/laravel` [GitHub repository](https://github.com/laravel/laravel). While many of these changes are not required, you may wish to keep these files in sync with your application. Some of these changes will be covered in this upgrade guide, but others, such as changes to configuration files or comments, will not be. You can easily view the changes with the [GitHub comparison tool](https://github.com/laravel/laravel/compare/8.x...9.x) and choose which updates are important to you. +We also encourage you to view the changes in the `laravel/laravel` [GitHub repository](https://github.com/laravel/laravel). While many of these changes are not required, you may wish to keep these files in sync with your application. Some of these changes will be covered in this upgrade guide, but others, such as changes to configuration files or comments, will not be. You can easily view the changes with the [GitHub comparison tool](https://github.com/laravel/laravel/compare/11.x...12.x) and choose which updates are important to you. diff --git a/urls.md b/urls.md index 504081eb9f4..cc2f24c26a6 100644 --- a/urls.md +++ b/urls.md @@ -3,10 +3,11 @@ - [Introduction](#introduction) - [The Basics](#the-basics) - [Generating URLs](#generating-urls) - - [Accessing The Current URL](#accessing-the-current-url) -- [URLs For Named Routes](#urls-for-named-routes) + - [Accessing the Current URL](#accessing-the-current-url) +- [URLs for Named Routes](#urls-for-named-routes) - [Signed URLs](#signed-urls) -- [URLs For Controller Actions](#urls-for-controller-actions) +- [URLs for Controller Actions](#urls-for-controller-actions) +- [Fluent URI Objects](#fluent-uri-objects) - [Default Values](#default-values) @@ -22,69 +23,120 @@ Laravel provides several helpers to assist you in generating URLs for your appli The `url` helper may be used to generate arbitrary URLs for your application. The generated URL will automatically use the scheme (HTTP or HTTPS) and host from the current request being handled by the application: - $post = App\Models\Post::find(1); +```php +$post = App\Models\Post::find(1); - echo url("https://github.com/posts/%7B$post-%3Eid%7D"); +echo url("https://github.com/posts/%7B$post-%3Eid%7D"); - // http://example.com/posts/1 +// http://example.com/posts/1 +``` + +To generate a URL with query string parameters, you may use the `query` method: + +```php +echo url()->query('/posts', ['search' => 'Laravel']); + +// https://example.com/posts?search=Laravel + +echo url()->query('/posts?sort=latest', ['search' => 'Laravel']); + +// http://example.com/posts?sort=latest&search=Laravel +``` + +Providing query string parameters that already exist in the path will overwrite their existing value: + +```php +echo url()->query('/posts?sort=latest', ['sort' => 'oldest']); + +// http://example.com/posts?sort=oldest +``` + +Arrays of values may also be passed as query parameters. These values will be properly keyed and encoded in the generated URL: + +```php +echo $url = url()->query('/posts', ['columns' => ['title', 'body']]); + +// http://example.com/posts?columns%5B0%5D=title&columns%5B1%5D=body + +echo urldecode($url); + +// http://example.com/posts?columns[0]=title&columns[1]=body +``` -### Accessing The Current URL +### Accessing the Current URL If no path is provided to the `url` helper, an `Illuminate\Routing\UrlGenerator` instance is returned, allowing you to access information about the current URL: - // Get the current URL without the query string... - echo url()->current(); +```php +// Get the current URL without the query string... +echo url()->current(); - // Get the current URL including the query string... - echo url()->full(); +// Get the current URL including the query string... +echo url()->full(); - // Get the full URL for the previous request... - echo url()->previous(); +// Get the full URL for the previous request... +echo url()->previous(); + +// Get the path for the previous request... +echo url()->previousPath(); +``` Each of these methods may also be accessed via the `URL` [facade](/docs/{{version}}/facades): - use Illuminate\Support\Facades\URL; +```php +use Illuminate\Support\Facades\URL; - echo URL::current(); +echo URL::current(); +``` -## URLs For Named Routes +## URLs for Named Routes The `route` helper may be used to generate URLs to [named routes](/docs/{{version}}/routing#named-routes). Named routes allow you to generate URLs without being coupled to the actual URL defined on the route. Therefore, if the route's URL changes, no changes need to be made to your calls to the `route` function. For example, imagine your application contains a route defined like the following: - Route::get('/post/{post}', function (Post $post) { - // - })->name('post.show'); +```php +Route::get('/post/{post}', function (Post $post) { + // ... +})->name('post.show'); +``` To generate a URL to this route, you may use the `route` helper like so: - echo route('post.show', ['post' => 1]); +```php +echo route('post.show', ['post' => 1]); - // http://example.com/post/1 +// http://example.com/post/1 +``` Of course, the `route` helper may also be used to generate URLs for routes with multiple parameters: - Route::get('/post/{post}/comment/{comment}', function (Post $post, Comment $comment) { - // - })->name('comment.show'); +```php +Route::get('/post/{post}/comment/{comment}', function (Post $post, Comment $comment) { + // ... +})->name('comment.show'); - echo route('comment.show', ['post' => 1, 'comment' => 3]); +echo route('comment.show', ['post' => 1, 'comment' => 3]); - // http://example.com/post/1/comment/3 +// http://example.com/post/1/comment/3 +``` Any additional array elements that do not correspond to the route's definition parameters will be added to the URL's query string: - echo route('post.show', ['post' => 1, 'search' => 'rocket']); +```php +echo route('post.show', ['post' => 1, 'search' => 'rocket']); - // http://example.com/post/1?search=rocket +// http://example.com/post/1?search=rocket +``` #### Eloquent Models You will often be generating URLs using the route key (typically the primary key) of [Eloquent models](/docs/{{version}}/eloquent). For this reason, you may pass Eloquent models as parameter values. The `route` helper will automatically extract the model's route key: - echo route('post.show', ['post' => $post]); +```php +echo route('post.show', ['post' => $post]); +``` ### Signed URLs @@ -93,144 +145,193 @@ Laravel allows you to easily create "signed" URLs to named routes. These URLs ha For example, you might use signed URLs to implement a public "unsubscribe" link that is emailed to your customers. To create a signed URL to a named route, use the `signedRoute` method of the `URL` facade: - use Illuminate\Support\Facades\URL; +```php +use Illuminate\Support\Facades\URL; + +return URL::signedRoute('unsubscribe', ['user' => 1]); +``` + +You may exclude the domain from the signed URL hash by providing the `absolute` argument to the `signedRoute` method: - return URL::signedRoute('unsubscribe', ['user' => 1]); +```php +return URL::signedRoute('unsubscribe', ['user' => 1], absolute: false); +``` If you would like to generate a temporary signed route URL that expires after a specified amount of time, you may use the `temporarySignedRoute` method. When Laravel validates a temporary signed route URL, it will ensure that the expiration timestamp that is encoded into the signed URL has not elapsed: - use Illuminate\Support\Facades\URL; +```php +use Illuminate\Support\Facades\URL; - return URL::temporarySignedRoute( - 'unsubscribe', now()->addMinutes(30), ['user' => 1] - ); +return URL::temporarySignedRoute( + 'unsubscribe', now()->addMinutes(30), ['user' => 1] +); +``` #### Validating Signed Route Requests To verify that an incoming request has a valid signature, you should call the `hasValidSignature` method on the incoming `Illuminate\Http\Request` instance: - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::get('/unsubscribe/{user}', function (Request $request) { - if (! $request->hasValidSignature()) { - abort(401); - } +Route::get('/unsubscribe/{user}', function (Request $request) { + if (! $request->hasValidSignature()) { + abort(401); + } - // ... - })->name('unsubscribe'); + // ... +})->name('unsubscribe'); +``` Sometimes, you may need to allow your application's frontend to append data to a signed URL, such as when performing client-side pagination. Therefore, you can specify request query parameters that should be ignored when validating a signed URL using the `hasValidSignatureWhileIgnoring` method. Remember, ignoring parameters allows anyone to modify those parameters on the request: - if (! $request->hasValidSignatureWhileIgnoring(['page', 'order'])) { - abort(401); - } +```php +if (! $request->hasValidSignatureWhileIgnoring(['page', 'order'])) { + abort(401); +} +``` -Instead of validating signed URLs using the incoming request instance, you may assign the `Illuminate\Routing\Middleware\ValidateSignature` [middleware](/docs/{{version}}/middleware) to the route. If it is not already present, you should assign this middleware a key in your HTTP kernel's `routeMiddleware` array: +Instead of validating signed URLs using the incoming request instance, you may assign the `signed` (`Illuminate\Routing\Middleware\ValidateSignature`) [middleware](/docs/{{version}}/middleware) to the route. If the incoming request does not have a valid signature, the middleware will automatically return a `403` HTTP response: - /** - * The application's route middleware. - * - * These middleware may be assigned to groups or used individually. - * - * @var array - */ - protected $routeMiddleware = [ - 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, - ]; +```php +Route::post('/unsubscribe/{user}', function (Request $request) { + // ... +})->name('unsubscribe')->middleware('signed'); +``` -Once you have registered the middleware in your kernel, you may attach it to a route. If the incoming request does not have a valid signature, the middleware will automatically return a `403` HTTP response: +If your signed URLs do not include the domain in the URL hash, you should provide the `relative` argument to the middleware: - Route::post('/unsubscribe/{user}', function (Request $request) { - // ... - })->name('unsubscribe')->middleware('signed'); +```php +Route::post('/unsubscribe/{user}', function (Request $request) { + // ... +})->name('unsubscribe')->middleware('signed:relative'); +``` -#### Responding To Invalid Signed Routes +#### Responding to Invalid Signed Routes -When someone visits a signed URL that has expired, they will receive a generic error page for the `403` HTTP status code. However, you can customize this behavior by defining a custom "renderable" closure for the `InvalidSignatureException` exception in your exception handler. This closure should return an HTTP response: +When someone visits a signed URL that has expired, they will receive a generic error page for the `403` HTTP status code. However, you can customize this behavior by defining a custom "render" closure for the `InvalidSignatureException` exception in your application's `bootstrap/app.php` file: - use Illuminate\Routing\Exceptions\InvalidSignatureException; +```php +use Illuminate\Routing\Exceptions\InvalidSignatureException; - /** - * Register the exception handling callbacks for the application. - * - * @return void - */ - public function register() - { - $this->renderable(function (InvalidSignatureException $e) { - return response()->view('error.link-expired', [], 403); - }); - } +->withExceptions(function (Exceptions $exceptions): void { + $exceptions->render(function (InvalidSignatureException $e) { + return response()->view('errors.link-expired', status: 403); + }); +}) +``` -## URLs For Controller Actions +## URLs for Controller Actions The `action` function generates a URL for the given controller action: - use App\Http\Controllers\HomeController; +```php +use App\Http\Controllers\HomeController; - $url = action([HomeController::class, 'index']); +$url = action([HomeController::class, 'index']); +``` If the controller method accepts route parameters, you may pass an associative array of route parameters as the second argument to the function: - $url = action([UserController::class, 'profile'], ['id' => 1]); +```php +$url = action([UserController::class, 'profile'], ['id' => 1]); +``` + + +## Fluent URI Objects + +Laravel's `Uri` class provides a convenient and fluent interface for creating and manipulating URIs via objects. This class wraps the functionality provided by the underlying League URI package and integrates seamlessly with Laravel's routing system. + +You can create a `Uri` instance easily using static methods: + +```php +use App\Http\Controllers\UserController; +use App\Http\Controllers\InvokableController; +use Illuminate\Support\Uri; + +// Generate a URI instance from the given string... +$uri = Uri::of('https://example.com/path'); + +// Generate URI instances to paths, named routes, or controller actions... +$uri = Uri::to('/dashboard'); +$uri = Uri::route('users.show', ['user' => 1]); +$uri = Uri::signedRoute('users.show', ['user' => 1]); +$uri = Uri::temporarySignedRoute('user.index', now()->addMinutes(5)); +$uri = Uri::action([UserController::class, 'index']); +$uri = Uri::action(InvokableController::class); + +// Generate a URI instance from the current request URL... +$uri = $request->uri(); +``` + +Once you have a URI instance, you can fluently modify it: + +```php +$uri = Uri::of('https://example.com/') + ->withScheme('http') + ->withHost('test.com') + ->withPort(8000) + ->withPath('/users') + ->withQuery(['page' => 2]) + ->withFragment('section-1'); +``` + +For more information on working with fluent URI objects, consult the [URI documentation](/docs/{{version}}/helpers#uri). ## Default Values For some applications, you may wish to specify request-wide default values for certain URL parameters. For example, imagine many of your routes define a `{locale}` parameter: - Route::get('/{locale}/posts', function () { - // - })->name('post.index'); +```php +Route::get('/{locale}/posts', function () { + // ... +})->name('post.index'); +``` It is cumbersome to always pass the `locale` every time you call the `route` helper. So, you may use the `URL::defaults` method to define a default value for this parameter that will always be applied during the current request. You may wish to call this method from a [route middleware](/docs/{{version}}/middleware#assigning-middleware-to-routes) so that you have access to the current request: - $request->user()->locale]); - - return $next($request); - } + URL::defaults(['locale' => $request->user()->locale]); + + return $next($request); } +} +``` Once the default value for the `locale` parameter has been set, you are no longer required to pass its value when generating URLs via the `route` helper. -#### URL Defaults & Middleware Priority +#### URL Defaults and Middleware Priority -Setting URL default values can interfere with Laravel's handling of implicit model bindings. Therefore, you should [prioritize your middleware](/docs/{{version}}/middleware#sorting-middleware) that set URL defaults to be executed before Laravel's own `SubstituteBindings` middleware. You can accomplish this by making sure your middleware occurs before the `SubstituteBindings` middleware within the `$middlewarePriority` property of your application's HTTP kernel. +Setting URL default values can interfere with Laravel's handling of implicit model bindings. Therefore, you should [prioritize your middleware](/docs/{{version}}/middleware#sorting-middleware) that set URL defaults to be executed before Laravel's own `SubstituteBindings` middleware. You can accomplish this using the `priority` middleware method in your application's `bootstrap/app.php` file: -The `$middlewarePriority` property is defined in the base `Illuminate\Foundation\Http\Kernel` class. You may copy its definition from that class and overwrite it in your application's HTTP kernel in order to modify it: - - /** - * The priority-sorted list of middleware. - * - * This forces non-global middleware to always be in the given order. - * - * @var array - */ - protected $middlewarePriority = [ - // ... - \App\Http\Middleware\SetDefaultLocaleForUrls::class, - \Illuminate\Routing\Middleware\SubstituteBindings::class, - // ... - ]; +```php +->withMiddleware(function (Middleware $middleware): void { + $middleware->prependToPriorityList( + before: \Illuminate\Routing\Middleware\SubstituteBindings::class, + prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class, + ); +}) +``` diff --git a/valet.md b/valet.md index 603fb775526..cae1a895cb6 100644 --- a/valet.md +++ b/valet.md @@ -8,20 +8,23 @@ - [The "Link" Command](#the-link-command) - [Securing Sites With TLS](#securing-sites) - [Serving a Default Site](#serving-a-default-site) + - [Per-Site PHP Versions](#per-site-php-versions) - [Sharing Sites](#sharing-sites) - - [Sharing Sites Via Ngrok](#sharing-sites-via-ngrok) - - [Sharing Sites Via Expose](#sharing-sites-via-expose) - - [Sharing Sites On Your Local Network](#sharing-sites-on-your-local-network) + - [Sharing Sites on Your Local Network](#sharing-sites-on-your-local-network) - [Site Specific Environment Variables](#site-specific-environment-variables) - [Proxying Services](#proxying-services) - [Custom Valet Drivers](#custom-valet-drivers) - [Local Drivers](#local-drivers) - [Other Valet Commands](#other-valet-commands) -- [Valet Directories & Files](#valet-directories-and-files) +- [Valet Directories and Files](#valet-directories-and-files) + - [Disk Access](#disk-access) ## Introduction +> [!NOTE] +> Looking for an even easier way to develop Laravel applications on macOS or Windows? Check out [Laravel Herd](https://herd.laravel.com). Herd includes everything you need to get started with Laravel development, including Valet, PHP, and Composer. + [Laravel Valet](https://github.com/laravel/valet) is a development environment for macOS minimalists. Laravel Valet configures your Mac to always run [Nginx](https://www.nginx.com/) in the background when your machine starts. Then, using [DnsMasq](https://en.wikipedia.org/wiki/Dnsmasq), Valet proxies all requests on the `*.test` domain to point to sites installed on your local machine. In other words, Valet is a blazing fast Laravel development environment that uses roughly 7 MB of RAM. Valet isn't a complete replacement for [Sail](/docs/{{version}}/sail) or [Homestead](/docs/{{version}}/homestead), but provides a great alternative if you want flexible basics, prefer extreme speed, or are working on a machine with a limited amount of RAM. @@ -38,10 +41,9 @@ Out of the box, Valet support includes, but is not limited to:
- [Laravel](https://laravel.com) -- [Lumen](https://lumen.laravel.com) - [Bedrock](https://roots.io/bedrock/) - [CakePHP 3](https://cakephp.org) -- [Concrete5](https://www.concrete5.org/) +- [ConcreteCMS](https://www.concretecms.com/) - [Contao](https://contao.org/en/) - [Craft](https://craftcms.com) - [Drupal](https://www.drupal.org/) @@ -67,7 +69,8 @@ However, you may extend Valet with your own [custom drivers](#custom-valet-drive ## Installation -> {note} Valet requires macOS and [Homebrew](https://brew.sh/). Before installation, you should make sure that no other programs such as Apache or Nginx are binding to your local machine's port 80. +> [!WARNING] +> Valet requires macOS and [Homebrew](https://brew.sh/). Before installation, you should make sure that no other programs such as Apache or Nginx are binding to your local machine's port 80. To get started, you first need to ensure that Homebrew is up to date using the `update` command: @@ -81,7 +84,7 @@ Next, you should use Homebrew to install PHP: brew install php ``` -After installing PHP, you are ready to install the [Composer package manager](https://getcomposer.org). In addition, you should make sure the `~/.composer/vendor/bin` directory is in your system's "PATH". After Composer has been installed, you may install Laravel Valet as a global Composer package: +After installing PHP, you are ready to install the [Composer package manager](https://getcomposer.org). In addition, you should make sure the `$HOME/.composer/vendor/bin` directory is in your system's "PATH". After Composer has been installed, you may install Laravel Valet as a global Composer package: ```shell composer global require laravel/valet @@ -100,38 +103,55 @@ Valet will automatically start its required services each time your machine boot #### PHP Versions +> [!NOTE] +> Instead of modifying your global PHP version, you can instruct Valet to use per-site PHP versions via the `isolate` [command](#per-site-php-versions). + Valet allows you to switch PHP versions using the `valet use php@version` command. Valet will install the specified PHP version via Homebrew if it is not already installed: ```shell -valet use php@7.2 +valet use php@8.2 valet use php ``` -You may also create a `.valetphprc` file in the root of your project. The `.valetphprc` file should contain the PHP version the site should use: +You may also create a `.valetrc` file in the root of your project. The `.valetrc` file should contain the PHP version the site should use: ```shell -php@7.2 +php=php@8.2 ``` Once this file has been created, you may simply execute the `valet use` command and the command will determine the site's preferred PHP version by reading the file. -> {note} Valet only serves one PHP version at a time, even if you have multiple PHP versions installed. +> [!WARNING] +> Valet only serves one PHP version at a time, even if you have multiple PHP versions installed. #### Database -If your application needs a database, check out [DBngin](https://dbngin.com). DBngin provides a free, all-in-one database management tool that includes MySQL, PostgreSQL, and Redis. After DBngin has been installed, you can connect to your database at `127.0.0.1` using the `root` username and an empty string for the password. +If your application needs a database, check out [DBngin](https://dbngin.com), which provides a free, all-in-one database management tool that includes MySQL, PostgreSQL, and Redis. After DBngin has been installed, you can connect to your database at `127.0.0.1` using the `root` username and an empty string for the password. #### Resetting Your Installation -If you are having trouble getting your Valet installation to run properly, executing the `composer global update` command followed by `valet install` will reset your installation and can solve a variety of problems. In rare cases, it may be necessary to "hard reset" Valet by executing `valet uninstall --force` followed by `valet install`. +If you are having trouble getting your Valet installation to run properly, executing the `composer global require laravel/valet` command followed by `valet install` will reset your installation and can solve a variety of problems. In rare cases, it may be necessary to "hard reset" Valet by executing `valet uninstall --force` followed by `valet install`. ### Upgrading Valet -You may update your Valet installation by executing the `composer global update` command in your terminal. After upgrading, it is good practice to run the `valet install` command so Valet can make additional upgrades to your configuration files if necessary. +You may update your Valet installation by executing the `composer global require laravel/valet` command in your terminal. After upgrading, it is good practice to run the `valet install` command so Valet can make additional upgrades to your configuration files if necessary. + + +#### Upgrading to Valet 4 + +If you're upgrading from Valet 3 to Valet 4, take the following steps to properly upgrade your Valet installation: + +
+ +- If you've added `.valetphprc` files to customize your site's PHP version, rename each `.valetphprc` file to `.valetrc`. Then, prepend `php=` to the existing content of the `.valetrc` file. +- Update any custom drivers to match the namespace, extension, type-hints, and return type-hints of the new driver system. You may consult Valet's [SampleValetDriver](https://github.com/laravel/valet/blob/d7787c025e60abc24a5195dc7d4c5c6f2d984339/cli/stubs/SampleValetDriver.php) as an example. +- If you use PHP 7.1 - 7.4 to serve your sites, make sure you still use Homebrew to install a version of PHP that's 8.0 or higher, as Valet will use this version, even if it's not your primary linked version, to run some of its scripts. + +
## Serving Sites @@ -172,6 +192,12 @@ cd ~/Sites/laravel valet link application ``` +Of course, you may also serve applications on subdomains using the `link` command: + +```shell +valet link api.application +``` + You may execute the `links` command to display a list of all of your linked directories: ```shell @@ -202,21 +228,63 @@ valet unsecure laravel ``` -### Serving A Default Site +### Serving a Default Site Sometimes, you may wish to configure Valet to serve a "default" site instead of a `404` when visiting an unknown `test` domain. To accomplish this, you may add a `default` option to your `~/.config/valet/config.json` configuration file containing the path to the site that should serve as your default site: - "default": "/Users/Sally/Sites/foo", + "default": "/Users/Sally/Sites/example-site", + + +### Per-Site PHP Versions + +By default, Valet uses your global PHP installation to serve your sites. However, if you need to support multiple PHP versions across various sites, you may use the `isolate` command to specify which PHP version a particular site should use. The `isolate` command configures Valet to use the specified PHP version for the site located in your current working directory: + +```shell +cd ~/Sites/example-site + +valet isolate php@8.0 +``` + +If your site name does not match the name of the directory that contains it, you may specify the site name using the `--site` option: + +```shell +valet isolate php@8.0 --site="site-name" +``` + +For convenience, you may use the `valet php`, `composer`, and `which-php` commands to proxy calls to the appropriate PHP CLI or tool based on the site's configured PHP version: + +```shell +valet php +valet composer +valet which-php +``` + +You may execute the `isolated` command to display a list of all of your isolated sites and their PHP versions: + +```shell +valet isolated +``` + +To revert a site back to Valet's globally installed PHP version, you may invoke the `unisolate` command from the site's root directory: + +```shell +valet unisolate +``` ## Sharing Sites -Valet even includes a command to share your local sites with the world, providing an easy way to test your site on mobile devices or share it with team members and clients. +Valet includes a command to share your local sites with the world, providing an easy way to test your site on mobile devices or share it with team members and clients. - -### Sharing Sites Via Ngrok +Out of the box, Valet supports sharing your sites via ngrok or Expose. Before sharing a site, you should update your Valet configuration using the `share-tool` command, specifying `ngrok`, `expose`, or `cloudflared`: + +```shell +valet share-tool ngrok +``` -To share a site, navigate to the site's directory in your terminal and run Valet's `share` command. A publicly accessible URL will be inserted into your clipboard and is ready to paste directly into your browser or share with your team: +If you choose a tool and don't have it installed via Homebrew (for ngrok and cloudflared) or Composer (for Expose), Valet will automatically prompt you to install it. Of course, both tools require you to authenticate your ngrok or Expose account before you can start sharing sites. + +To share a site, navigate to the site's directory in your terminal and run Valet's `share` command. A publicly accessible URL will be placed into your clipboard and is ready to paste directly into your browser or to be shared with your team: ```shell cd ~/Sites/laravel @@ -224,25 +292,32 @@ cd ~/Sites/laravel valet share ``` -To stop sharing your site, you may press `Control + C`. Sharing your site using Ngrok requires you to [create an Ngrok account](https://dashboard.ngrok.com/signup) and [setup an authentication token](https://dashboard.ngrok.com/get-started/your-authtoken). +To stop sharing your site, you may press `Control + C`. -> {tip} You may pass additional Ngrok parameters to the share command, such as `valet share --region=eu`. For more information, consult the [ngrok documentation](https://ngrok.com/docs). +> [!WARNING] +> If you're using a custom DNS server (like `1.1.1.1`), ngrok sharing may not work correctly. If this is the case on your machine, open your Mac's system settings, go to the Network settings, open the Advanced settings, then go the DNS tab and add `127.0.0.1` as your first DNS server. - -### Sharing Sites Via Expose + +#### Sharing Sites via Ngrok -If you have [Expose](https://expose.dev) installed, you can share your site by navigating to the site's directory in your terminal and running the `expose` command. Consult the [Expose documentation](https://expose.dev/docs) for information regarding the additional command-line parameters it supports. After sharing the site, Expose will display the sharable URL that you may use on your other devices or amongst team members: +Sharing your site using ngrok requires you to [create an ngrok account](https://dashboard.ngrok.com/signup) and [set up an authentication token](https://dashboard.ngrok.com/get-started/your-authtoken). Once you have an authentication token, you can update your Valet configuration with that token: ```shell -cd ~/Sites/laravel - -expose +valet set-ngrok-token YOUR_TOKEN_HERE ``` -To stop sharing your site, you may press `Control + C`. +> [!NOTE] +> You may pass additional ngrok parameters to the share command, such as `valet share --region=eu`. For more information, consult the [ngrok documentation](https://ngrok.com/docs). + + +#### Sharing Sites via Expose + +Sharing your site using Expose requires you to [create an Expose account](https://expose.dev/register) and [authenticate with Expose via your authentication token](https://expose.dev/docs/getting-started/getting-your-token). + +You may consult the [Expose documentation](https://expose.dev/docs) for information regarding the additional command-line parameters it supports. -### Sharing Sites On Your Local Network +### Sharing Sites on Your Local Network Valet restricts incoming traffic to the internal `127.0.0.1` interface by default so that your development machine isn't exposed to security risks from the Internet. @@ -257,19 +332,21 @@ Once you have updated your Nginx configuration, run the `valet restart` command Some applications using other frameworks may depend on server environment variables but do not provide a way for those variables to be configured within your project. Valet allows you to configure site specific environment variables by adding a `.valet-env.php` file within the root of your project. This file should return an array of site / environment variable pairs which will be added to the global `$_SERVER` array for each site specified in the array: - [ - 'key' => 'value', - ], +return [ + // Set $_SERVER['key'] to "value" for the laravel.test site... + 'laravel' => [ + 'key' => 'value', + ], - // Set $_SERVER['key'] to "value" for all sites... - '*' => [ - 'key' => 'value', - ], - ]; + // Set $_SERVER['key'] to "value" for all sites... + '*' => [ + 'key' => 'value', + ], +]; +``` ## Proxying Services @@ -316,111 +393,106 @@ The `serves` method should return `true` if your driver should handle the incomi For example, let's imagine we are writing a `WordPressValetDriver`. Our `serves` method might look something like this: - /** - * Determine if the driver serves the request. - * - * @param string $sitePath - * @param string $siteName - * @param string $uri - * @return bool - */ - public function serves($sitePath, $siteName, $uri) - { - return is_dir($sitePath.'/wp-admin'); - } +```php +/** + * Determine if the driver serves the request. + */ +public function serves(string $sitePath, string $siteName, string $uri): bool +{ + return is_dir($sitePath.'/wp-admin'); +} +``` #### The `isStaticFile` Method The `isStaticFile` should determine if the incoming request is for a file that is "static", such as an image or a stylesheet. If the file is static, the method should return the fully qualified path to the static file on disk. If the incoming request is not for a static file, the method should return `false`: - /** - * Determine if the incoming request is for a static file. - * - * @param string $sitePath - * @param string $siteName - * @param string $uri - * @return string|false - */ - public function isStaticFile($sitePath, $siteName, $uri) - { - if (file_exists($staticFilePath = $sitePath.'/public/'.$uri)) { - return $staticFilePath; - } - - return false; +```php +/** + * Determine if the incoming request is for a static file. + * + * @return string|false + */ +public function isStaticFile(string $sitePath, string $siteName, string $uri) +{ + if (file_exists($staticFilePath = $sitePath.'/public/'.$uri)) { + return $staticFilePath; } -> {note} The `isStaticFile` method will only be called if the `serves` method returns `true` for the incoming request and the request URI is not `/`. + return false; +} +``` + +> [!WARNING] +> The `isStaticFile` method will only be called if the `serves` method returns `true` for the incoming request and the request URI is not `/`. #### The `frontControllerPath` Method The `frontControllerPath` method should return the fully qualified path to your application's "front controller", which is typically an "index.php" file or equivalent: - /** - * Get the fully resolved path to the application's front controller. - * - * @param string $sitePath - * @param string $siteName - * @param string $uri - * @return string - */ - public function frontControllerPath($sitePath, $siteName, $uri) - { - return $sitePath.'/public/index.php'; - } +```php +/** + * Get the fully resolved path to the application's front controller. + */ +public function frontControllerPath(string $sitePath, string $siteName, string $uri): string +{ + return $sitePath.'/public/index.php'; +} +``` ### Local Drivers If you would like to define a custom Valet driver for a single application, create a `LocalValetDriver.php` file in the application's root directory. Your custom driver may extend the base `ValetDriver` class or extend an existing application specific driver such as the `LaravelValetDriver`: - class LocalValetDriver extends LaravelValetDriver +```php +use Valet\Drivers\LaravelValetDriver; + +class LocalValetDriver extends LaravelValetDriver +{ + /** + * Determine if the driver serves the request. + */ + public function serves(string $sitePath, string $siteName, string $uri): bool { - /** - * Determine if the driver serves the request. - * - * @param string $sitePath - * @param string $siteName - * @param string $uri - * @return bool - */ - public function serves($sitePath, $siteName, $uri) - { - return true; - } - - /** - * Get the fully resolved path to the application's front controller. - * - * @param string $sitePath - * @param string $siteName - * @param string $uri - * @return string - */ - public function frontControllerPath($sitePath, $siteName, $uri) - { - return $sitePath.'/public_html/index.php'; - } + return true; } + /** + * Get the fully resolved path to the application's front controller. + */ + public function frontControllerPath(string $sitePath, string $siteName, string $uri): string + { + return $sitePath.'/public_html/index.php'; + } +} +``` + ## Other Valet Commands -Command | Description -------------- | ------------- -`valet forget` | Run this command from a "parked" directory to remove it from the parked directory list. -`valet log` | View a list of logs which are written by Valet's services. -`valet paths` | View all of your "parked" paths. -`valet restart` | Restart the Valet daemons. -`valet start` | Start the Valet daemons. -`valet stop` | Stop the Valet daemons. -`valet trust` | Add sudoers files for Brew and Valet to allow Valet commands to be run without prompting for your password. -`valet uninstall` | Uninstall Valet: shows instructions for manual uninstall. Pass the `--force` option to aggressively delete all of Valet's resources. +
+ +| Command | Description | +| --- | --- | +| `valet list` | Display a list of all Valet commands. | +| `valet diagnose` | Output diagnostics to aid in debugging Valet. | +| `valet directory-listing` | Determine directory-listing behavior. Default is "off", which renders a 404 page for directories. | +| `valet forget` | Run this command from a "parked" directory to remove it from the parked directory list. | +| `valet log` | View a list of logs which are written by Valet's services. | +| `valet paths` | View all of your "parked" paths. | +| `valet restart` | Restart the Valet daemons. | +| `valet start` | Start the Valet daemons. | +| `valet stop` | Stop the Valet daemons. | +| `valet trust` | Add sudoers files for Brew and Valet to allow Valet commands to be run without prompting for your password. | +| `valet uninstall` | Uninstall Valet: shows instructions for manual uninstall. Pass the `--force` option to aggressively delete all of Valet's resources. | + +
-## Valet Directories & Files +## Valet Directories and Files You may find the following directory and file information helpful while troubleshooting issues with your Valet environment: @@ -436,13 +508,9 @@ This directory contains DNSMasq's configuration. This directory contains Valet's drivers. Drivers determine how a particular framework / CMS is served. -#### `~/.config/valet/Extensions/` - -This directory contains custom Valet extensions / commands. - #### `~/.config/valet/Nginx/` -This directory contains all of Valet's Nginx site configurations. These files are rebuilt when running the `install`, `secure`, and `tld` commands. +This directory contains all of Valet's Nginx site configurations. These files are rebuilt when running the `install` and `secure` commands. #### `~/.config/valet/Sites/` @@ -483,3 +551,10 @@ This file is the PHP-FPM pool configuration file. #### `~/.composer/vendor/laravel/valet/cli/stubs/secure.valet.conf` This file is the default Nginx configuration used for building SSL certificates for your sites. + + +### Disk Access + +Since macOS 10.14, [access to some files and directories is restricted by default](https://manuals.info.apple.com/MANUALS/1000/MA1902/en_US/apple-platform-security-guide.pdf). These restrictions include the Desktop, Documents, and Downloads directories. In addition, network volume and removable volume access is restricted. Therefore, Valet recommends your site folders are located outside of these protected locations. + +However, if you wish to serve sites from within one of those locations, you will need to give Nginx "Full Disk Access". Otherwise, you may encounter server errors or other unpredictable behavior from Nginx, especially when serving static assets. Typically, macOS will automatically prompt you to grant Nginx full access to these locations. Or, you may do so manually via `System Preferences` > `Security & Privacy` > `Privacy` and selecting `Full Disk Access`. Next, enable any `nginx` entries in the main window pane. diff --git a/validation.md b/validation.md index a6270d91c9e..fef312d222c 100644 --- a/validation.md +++ b/validation.md @@ -2,31 +2,34 @@ - [Introduction](#introduction) - [Validation Quickstart](#validation-quickstart) - - [Defining The Routes](#quick-defining-the-routes) - - [Creating The Controller](#quick-creating-the-controller) - - [Writing The Validation Logic](#quick-writing-the-validation-logic) - - [Displaying The Validation Errors](#quick-displaying-the-validation-errors) + - [Defining the Routes](#quick-defining-the-routes) + - [Creating the Controller](#quick-creating-the-controller) + - [Writing the Validation Logic](#quick-writing-the-validation-logic) + - [Displaying the Validation Errors](#quick-displaying-the-validation-errors) - [Repopulating Forms](#repopulating-forms) - - [A Note On Optional Fields](#a-note-on-optional-fields) + - [A Note on Optional Fields](#a-note-on-optional-fields) + - [Validation Error Response Format](#validation-error-response-format) - [Form Request Validation](#form-request-validation) - [Creating Form Requests](#creating-form-requests) - [Authorizing Form Requests](#authorizing-form-requests) - - [Customizing The Error Messages](#customizing-the-error-messages) - - [Preparing Input For Validation](#preparing-input-for-validation) + - [Customizing the Error Messages](#customizing-the-error-messages) + - [Preparing Input for Validation](#preparing-input-for-validation) - [Manually Creating Validators](#manually-creating-validators) - [Automatic Redirection](#automatic-redirection) - [Named Error Bags](#named-error-bags) - - [Customizing The Error Messages](#manual-customizing-the-error-messages) - - [After Validation Hook](#after-validation-hook) + - [Customizing the Error Messages](#manual-customizing-the-error-messages) + - [Performing Additional Validation](#performing-additional-validation) - [Working With Validated Input](#working-with-validated-input) - [Working With Error Messages](#working-with-error-messages) - - [Specifying Custom Messages In Language Files](#specifying-custom-messages-in-language-files) - - [Specifying Attributes In Language Files](#specifying-attribute-in-language-files) - - [Specifying Values In Language Files](#specifying-values-in-language-files) + - [Specifying Custom Messages in Language Files](#specifying-custom-messages-in-language-files) + - [Specifying Attributes in Language Files](#specifying-attribute-in-language-files) + - [Specifying Values in Language Files](#specifying-values-in-language-files) - [Available Validation Rules](#available-validation-rules) - [Conditionally Adding Rules](#conditionally-adding-rules) - [Validating Arrays](#validating-arrays) - [Validating Nested Array Input](#validating-nested-array-input) + - [Error Message Indexes and Positions](#error-message-indexes-and-positions) +- [Validating Files](#validating-files) - [Validating Passwords](#validating-passwords) - [Custom Validation Rules](#custom-validation-rules) - [Using Rule Objects](#using-rule-objects) @@ -46,126 +49,141 @@ Laravel includes a wide variety of convenient validation rules that you may appl To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user. By reading this high-level overview, you'll be able to gain a good general understanding of how to validate incoming request data using Laravel: -### Defining The Routes +### Defining the Routes First, let's assume we have the following routes defined in our `routes/web.php` file: - use App\Http\Controllers\PostController; +```php +use App\Http\Controllers\PostController; - Route::get('/post/create', [PostController::class, 'create']); - Route::post('/post', [PostController::class, 'store']); +Route::get('/post/create', [PostController::class, 'create']); +Route::post('/post', [PostController::class, 'store']); +``` The `GET` route will display a form for the user to create a new blog post, while the `POST` route will store the new blog post in the database. -### Creating The Controller +### Creating the Controller Next, let's take a look at a simple controller that handles incoming requests to these routes. We'll leave the `store` method empty for now: - $post->id]); } +} +``` -### Writing The Validation Logic +### Writing the Validation Logic Now we are ready to fill in our `store` method with the logic to validate the new blog post. To do this, we will use the `validate` method provided by the `Illuminate\Http\Request` object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an `Illuminate\Validation\ValidationException` exception will be thrown and the proper error response will automatically be sent back to the user. -If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned. +If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a [JSON response containing the validation error messages](#validation-error-response-format) will be returned. To get a better understanding of the `validate` method, let's jump back into the `store` method: - /** - * Store a new blog post. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\Response - */ - public function store(Request $request) - { - $validated = $request->validate([ - 'title' => 'required|unique:posts|max:255', - 'body' => 'required', - ]); +```php +/** + * Store a new blog post. + */ +public function store(Request $request): RedirectResponse +{ + $validated = $request->validate([ + 'title' => 'required|unique:posts|max:255', + 'body' => 'required', + ]); - // The blog post is valid... - } + // The blog post is valid... + + return redirect('/posts'); +} +``` As you can see, the validation rules are passed into the `validate` method. Don't worry - all available validation rules are [documented](#available-validation-rules). Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally. Alternatively, validation rules may be specified as arrays of rules instead of a single `|` delimited string: - $validatedData = $request->validate([ - 'title' => ['required', 'unique:posts', 'max:255'], - 'body' => ['required'], - ]); +```php +$validatedData = $request->validate([ + 'title' => ['required', 'unique:posts', 'max:255'], + 'body' => ['required'], +]); +``` In addition, you may use the `validateWithBag` method to validate a request and store any error messages within a [named error bag](#named-error-bags): - $validatedData = $request->validateWithBag('post', [ - 'title' => ['required', 'unique:posts', 'max:255'], - 'body' => ['required'], - ]); +```php +$validatedData = $request->validateWithBag('post', [ + 'title' => ['required', 'unique:posts', 'max:255'], + 'body' => ['required'], +]); +``` -#### Stopping On First Validation Failure +#### Stopping on First Validation Failure Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the `bail` rule to the attribute: - $request->validate([ - 'title' => 'bail|required|unique:posts|max:255', - 'body' => 'required', - ]); +```php +$request->validate([ + 'title' => 'bail|required|unique:posts|max:255', + 'body' => 'required', +]); +``` In this example, if the `unique` rule on the `title` attribute fails, the `max` rule will not be checked. Rules will be validated in the order they are assigned. -#### A Note On Nested Attributes +#### A Note on Nested Attributes If the incoming HTTP request contains "nested" field data, you may specify these fields in your validation rules using "dot" syntax: - $request->validate([ - 'title' => 'required|unique:posts|max:255', - 'author.name' => 'required', - 'author.description' => 'required', - ]); +```php +$request->validate([ + 'title' => 'required|unique:posts|max:255', + 'author.name' => 'required', + 'author.description' => 'required', +]); +``` On the other hand, if your field name contains a literal period, you can explicitly prevent this from being interpreted as "dot" syntax by escaping the period with a backslash: - $request->validate([ - 'title' => 'required|unique:posts|max:255', - 'v1\.0' => 'required', - ]); +```php +$request->validate([ + 'title' => 'required|unique:posts|max:255', + 'v1\.0' => 'required', +]); +``` -### Displaying The Validation Errors +### Displaying the Validation Errors So, what if the incoming request fields do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and [request input](/docs/{{version}}/requests#retrieving-old-input) will automatically be [flashed to the session](/docs/{{version}}/session#flash-data). @@ -192,16 +210,21 @@ So, in our example, the user will be redirected to our controller's `create` met ``` -#### Customizing The Error Messages +#### Customizing the Error Messages + +Laravel's built-in validation rules each have an error message that is located in your application's `lang/en/validation.php` file. If your application does not have a `lang` directory, you may instruct Laravel to create it using the `lang:publish` Artisan command. -Laravel's built-in validation rules each has an error message that is located in your application's `lang/en/validation.php` file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application. +Within the `lang/en/validation.php` file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application. -In addition, you may copy this file to another translation language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete [localization documentation](/docs/{{version}}/localization). +In addition, you may copy this file to another language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete [localization documentation](/docs/{{version}}/localization). + +> [!WARNING] +> By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. -#### XHR Requests & Validation +#### XHR Requests and Validation -In this example, we used a traditional form to send data to the application. However, many applications receive XHR requests from a JavaScript powered frontend. When using the `validate` method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code. +In this example, we used a traditional form to send data to the application. However, many applications receive XHR requests from a JavaScript powered frontend. When using the `validate` method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a [JSON response containing all of the validation errors](#validation-error-response-format). This JSON response will be sent with a 422 HTTP status code. #### The `@error` Directive @@ -213,10 +236,12 @@ You may use the `@error` [Blade](/docs/{{version}}/blade) directive to quickly d - + class="@error('title') is-invalid @enderror" +/> @error('title')
{{ $message }}
@@ -236,7 +261,9 @@ When Laravel generates a redirect response due to a validation error, the framew To retrieve flashed input from the previous request, invoke the `old` method on an instance of `Illuminate\Http\Request`. The `old` method will pull the previously flashed input data from the [session](/docs/{{version}}/session): - $title = $request->old('title'); +```php +$title = $request->old('title'); +``` Laravel also provides a global `old` helper. If you are displaying old input within a [Blade template](/docs/{{version}}/blade), it is more convenient to use the `old` helper to repopulate the form. If no old input exists for the given field, `null` will be returned: @@ -245,18 +272,48 @@ Laravel also provides a global `old` helper. If you are displaying old input wit ``` -### A Note On Optional Fields +### A Note on Optional Fields -By default, Laravel includes the `TrimStrings` and `ConvertEmptyStringsToNull` middleware in your application's global middleware stack. These middleware are listed in the stack by the `App\Http\Kernel` class. Because of this, you will often need to mark your "optional" request fields as `nullable` if you do not want the validator to consider `null` values as invalid. For example: +By default, Laravel includes the `TrimStrings` and `ConvertEmptyStringsToNull` middleware in your application's global middleware stack. Because of this, you will often need to mark your "optional" request fields as `nullable` if you do not want the validator to consider `null` values as invalid. For example: - $request->validate([ - 'title' => 'required|unique:posts|max:255', - 'body' => 'required', - 'publish_at' => 'nullable|date', - ]); +```php +$request->validate([ + 'title' => 'required|unique:posts|max:255', + 'body' => 'required', + 'publish_at' => 'nullable|date', +]); +``` In this example, we are specifying that the `publish_at` field may be either `null` or a valid date representation. If the `nullable` modifier is not added to the rule definition, the validator would consider `null` an invalid date. + +### Validation Error Response Format + +When your application throws a `Illuminate\Validation\ValidationException` exception and the incoming HTTP request is expecting a JSON response, Laravel will automatically format the error messages for you and return a `422 Unprocessable Entity` HTTP response. + +Below, you can review an example of the JSON response format for validation errors. Note that nested error keys are flattened into "dot" notation format: + +```json +{ + "message": "The team name must be a string. (and 4 more errors)", + "errors": { + "team_name": [ + "The team name must be a string.", + "The team name must be at least 1 characters." + ], + "authorization.role": [ + "The selected authorization.role is invalid." + ], + "users.0.email": [ + "The users.0.email field is required." + ], + "users.2.email": [ + "The users.2.email must be a valid email address." + ] + } +} +``` + ## Form Request Validation @@ -273,274 +330,348 @@ The generated form request class will be placed in the `app/Http/Requests` direc As you might have guessed, the `authorize` method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the `rules` method returns the validation rules that should apply to the request's data: - /** - * Get the validation rules that apply to the request. - * - * @return array - */ - public function rules() - { - return [ - 'title' => 'required|unique:posts|max:255', - 'body' => 'required', - ]; - } +```php +/** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ +public function rules(): array +{ + return [ + 'title' => 'required|unique:posts|max:255', + 'body' => 'required', + ]; +} +``` -> {tip} You may type-hint any dependencies you require within the `rules` method's signature. They will automatically be resolved via the Laravel [service container](/docs/{{version}}/container). +> [!NOTE] +> You may type-hint any dependencies you require within the `rules` method's signature. They will automatically be resolved via the Laravel [service container](/docs/{{version}}/container). So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic: - /** - * Store a new blog post. - * - * @param \App\Http\Requests\StorePostRequest $request - * @return Illuminate\Http\Response - */ - public function store(StorePostRequest $request) - { - // The incoming request is valid... +```php +/** + * Store a new blog post. + */ +public function store(StorePostRequest $request): RedirectResponse +{ + // The incoming request is valid... - // Retrieve the validated input data... - $validated = $request->validated(); + // Retrieve the validated input data... + $validated = $request->validated(); - // Retrieve a portion of the validated input data... - $validated = $request->safe()->only(['name', 'email']); - $validated = $request->safe()->except(['name', 'email']); - } + // Retrieve a portion of the validated input data... + $validated = $request->safe()->only(['name', 'email']); + $validated = $request->safe()->except(['name', 'email']); -If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors. + // Store the blog post... - -#### Adding After Hooks To Form Requests + return redirect('/posts'); +} +``` -If you would like to add an "after" validation hook to a form request, you may use the `withValidator` method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated: +If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a [JSON representation of the validation errors](#validation-error-response-format). - /** - * Configure the validator instance. - * - * @param \Illuminate\Validation\Validator $validator - * @return void - */ - public function withValidator($validator) - { - $validator->after(function ($validator) { +> [!NOTE] +> Need to add real-time form request validation to your Inertia powered Laravel frontend? Check out [Laravel Precognition](/docs/{{version}}/precognition). + + +#### Performing Additional Validation + +Sometimes you need to perform additional validation after your initial validation is complete. You can accomplish this using the form request's `after` method. + +The `after` method should return an array of callables or closures which will be invoked after validation is complete. The given callables will receive an `Illuminate\Validation\Validator` instance, allowing you to raise additional error messages if necessary: + +```php +use Illuminate\Validation\Validator; + +/** + * Get the "after" validation callables for the request. + */ +public function after(): array +{ + return [ + function (Validator $validator) { if ($this->somethingElseIsInvalid()) { - $validator->errors()->add('field', 'Something is wrong with this field!'); + $validator->errors()->add( + 'field', + 'Something is wrong with this field!' + ); } - }); - } + } + ]; +} +``` + +As noted, the array returned by the `after` method may also contain invokable classes. The `__invoke` method of these classes will receive an `Illuminate\Validation\Validator` instance: +```php +use App\Validation\ValidateShippingTime; +use App\Validation\ValidateUserStatus; +use Illuminate\Validation\Validator; + +/** + * Get the "after" validation callables for the request. + */ +public function after(): array +{ + return [ + new ValidateUserStatus, + new ValidateShippingTime, + function (Validator $validator) { + // + } + ]; +} +``` -#### Stopping On First Validation Failure Attribute +#### Stopping on the First Validation Failure By adding a `stopOnFirstFailure` property to your request class, you may inform the validator that it should stop validating all attributes once a single validation failure has occurred: - /** - * Indicates if the validator should stop on the first rule failure. - * - * @var bool - */ - protected $stopOnFirstFailure = true; +```php +/** + * Indicates if the validator should stop on the first rule failure. + * + * @var bool + */ +protected $stopOnFirstFailure = true; +``` -#### Customizing The Redirect Location +#### Customizing the Redirect Location -As previously discussed, a redirect response will be generated to send the user back to their previous location when form request validation fails. However, you are free to customize this behavior. To do so, define a `$redirect` property on your form request: +When form request validation fails, a redirect response will be generated to send the user back to their previous location. However, you are free to customize this behavior. To do so, define a `$redirect` property on your form request: - /** - * The URI that users should be redirected to if validation fails. - * - * @var string - */ - protected $redirect = '/dashboard'; +```php +/** + * The URI that users should be redirected to if validation fails. + * + * @var string + */ +protected $redirect = '/dashboard'; +``` Or, if you would like to redirect users to a named route, you may define a `$redirectRoute` property instead: - /** - * The route that users should be redirected to if validation fails. - * - * @var string - */ - protected $redirectRoute = 'dashboard'; +```php +/** + * The route that users should be redirected to if validation fails. + * + * @var string + */ +protected $redirectRoute = 'dashboard'; +``` ### Authorizing Form Requests The form request class also contains an `authorize` method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update. Most likely, you will interact with your [authorization gates and policies](/docs/{{version}}/authorization) within this method: - use App\Models\Comment; +```php +use App\Models\Comment; - /** - * Determine if the user is authorized to make this request. - * - * @return bool - */ - public function authorize() - { - $comment = Comment::find($this->route('comment')); +/** + * Determine if the user is authorized to make this request. + */ +public function authorize(): bool +{ + $comment = Comment::find($this->route('comment')); - return $comment && $this->user()->can('update', $comment); - } + return $comment && $this->user()->can('update', $comment); +} +``` Since all form requests extend the base Laravel request class, we may use the `user` method to access the currently authenticated user. Also, note the call to the `route` method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the `{comment}` parameter in the example below: - Route::post('/comment/{comment}'); +```php +Route::post('/comment/{comment}'); +``` Therefore, if your application is taking advantage of [route model binding](/docs/{{version}}/routing#route-model-binding), your code may be made even more succinct by accessing the resolved model as a property of the request: - return $this->user()->can('update', $this->comment); +```php +return $this->user()->can('update', $this->comment); +``` If the `authorize` method returns `false`, an HTTP response with a 403 status code will automatically be returned and your controller method will not execute. -If you plan to handle authorization logic for the request in another part of your application, you may simply return `true` from the `authorize` method: +If you plan to handle authorization logic for the request in another part of your application, you may remove the `authorize` method completely, or simply return `true`: - /** - * Determine if the user is authorized to make this request. - * - * @return bool - */ - public function authorize() - { - return true; - } +```php +/** + * Determine if the user is authorized to make this request. + */ +public function authorize(): bool +{ + return true; +} +``` -> {tip} You may type-hint any dependencies you need within the `authorize` method's signature. They will automatically be resolved via the Laravel [service container](/docs/{{version}}/container). +> [!NOTE] +> You may type-hint any dependencies you need within the `authorize` method's signature. They will automatically be resolved via the Laravel [service container](/docs/{{version}}/container). -### Customizing The Error Messages +### Customizing the Error Messages You may customize the error messages used by the form request by overriding the `messages` method. This method should return an array of attribute / rule pairs and their corresponding error messages: - /** - * Get the error messages for the defined validation rules. - * - * @return array - */ - public function messages() - { - return [ - 'title.required' => 'A title is required', - 'body.required' => 'A message is required', - ]; - } +```php +/** + * Get the error messages for the defined validation rules. + * + * @return array + */ +public function messages(): array +{ + return [ + 'title.required' => 'A title is required', + 'body.required' => 'A message is required', + ]; +} +``` -#### Customizing The Validation Attributes +#### Customizing the Validation Attributes Many of Laravel's built-in validation rule error messages contain an `:attribute` placeholder. If you would like the `:attribute` placeholder of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the `attributes` method. This method should return an array of attribute / name pairs: - /** - * Get custom attributes for validator errors. - * - * @return array - */ - public function attributes() - { - return [ - 'email' => 'email address', - ]; - } +```php +/** + * Get custom attributes for validator errors. + * + * @return array + */ +public function attributes(): array +{ + return [ + 'email' => 'email address', + ]; +} +``` -### Preparing Input For Validation +### Preparing Input for Validation If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the `prepareForValidation` method: - use Illuminate\Support\Str; +```php +use Illuminate\Support\Str; - /** - * Prepare the data for validation. - * - * @return void - */ - protected function prepareForValidation() - { - $this->merge([ - 'slug' => Str::slug($this->slug), - ]); - } +/** + * Prepare the data for validation. + */ +protected function prepareForValidation(): void +{ + $this->merge([ + 'slug' => Str::slug($this->slug), + ]); +} +``` + +Likewise, if you need to normalize any request data after validation is complete, you may use the `passedValidation` method: + +```php +/** + * Handle a passed validation attempt. + */ +protected function passedValidation(): void +{ + $this->replace(['name' => 'Taylor']); +} +``` ## Manually Creating Validators If you do not want to use the `validate` method on the request, you may create a validator instance manually using the `Validator` [facade](/docs/{{version}}/facades). The `make` method on the facade generates a new validator instance: - all(), [ - 'title' => 'required|unique:posts|max:255', - 'body' => 'required', - ]); - - if ($validator->fails()) { - return redirect('post/create') - ->withErrors($validator) - ->withInput(); - } + $validator = Validator::make($request->all(), [ + 'title' => 'required|unique:posts|max:255', + 'body' => 'required', + ]); - // Retrieve the validated input... - $validated = $validator->validated(); + if ($validator->fails()) { + return redirect('/post/create') + ->withErrors($validator) + ->withInput(); + } - // Retrieve a portion of the validated input... - $validated = $validator->safe()->only(['name', 'email']); - $validated = $validator->safe()->except(['name', 'email']); + // Retrieve the validated input... + $validated = $validator->validated(); - // Store the blog post... - } + // Retrieve a portion of the validated input... + $validated = $validator->safe()->only(['name', 'email']); + $validated = $validator->safe()->except(['name', 'email']); + + // Store the blog post... + + return redirect('/posts'); } +} +``` The first argument passed to the `make` method is the data under validation. The second argument is an array of the validation rules that should be applied to the data. After determining whether the request validation failed, you may use the `withErrors` method to flash the error messages to the session. When using this method, the `$errors` variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The `withErrors` method accepts a validator, a `MessageBag`, or a PHP `array`. -#### Stopping On First Validation Failure +#### Stopping on First Validation Failure The `stopOnFirstFailure` method will inform the validator that it should stop validating all attributes once a single validation failure has occurred: - if ($validator->stopOnFirstFailure()->fails()) { - // ... - } +```php +if ($validator->stopOnFirstFailure()->fails()) { + // ... +} +``` ### Automatic Redirection -If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the HTTP request's `validate` method, you may call the `validate` method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an XHR request, a JSON response will be returned: +If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the HTTP request's `validate` method, you may call the `validate` method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an XHR request, a [JSON response will be returned](#validation-error-response-format): - Validator::make($request->all(), [ - 'title' => 'required|unique:posts|max:255', - 'body' => 'required', - ])->validate(); +```php +Validator::make($request->all(), [ + 'title' => 'required|unique:posts|max:255', + 'body' => 'required', +])->validate(); +``` You may use the `validateWithBag` method to store the error messages in a [named error bag](#named-error-bags) if validation fails: - Validator::make($request->all(), [ - 'title' => 'required|unique:posts|max:255', - 'body' => 'required', - ])->validateWithBag('post'); +```php +Validator::make($request->all(), [ + 'title' => 'required|unique:posts|max:255', + 'body' => 'required', +])->validateWithBag('post'); +``` ### Named Error Bags If you have multiple forms on a single page, you may wish to name the `MessageBag` containing the validation errors, allowing you to retrieve the error messages for a specific form. To achieve this, pass a name as the second argument to `withErrors`: - return redirect('register')->withErrors($validator, 'login'); +```php +return redirect('/register')->withErrors($validator, 'login'); +``` You may then access the named `MessageBag` instance from the `$errors` variable: @@ -549,96 +680,133 @@ You may then access the named `MessageBag` instance from the `$errors` variable: ``` -### Customizing The Error Messages +### Customizing the Error Messages If needed, you may provide custom error messages that a validator instance should use instead of the default error messages provided by Laravel. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the `Validator::make` method: - $validator = Validator::make($input, $rules, $messages = [ - 'required' => 'The :attribute field is required.', - ]); +```php +$validator = Validator::make($input, $rules, $messages = [ + 'required' => 'The :attribute field is required.', +]); +``` In this example, the `:attribute` placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example: - $messages = [ - 'same' => 'The :attribute and :other must match.', - 'size' => 'The :attribute must be exactly :size.', - 'between' => 'The :attribute value :input is not between :min - :max.', - 'in' => 'The :attribute must be one of the following types: :values', - ]; +```php +$messages = [ + 'same' => 'The :attribute and :other must match.', + 'size' => 'The :attribute must be exactly :size.', + 'between' => 'The :attribute value :input is not between :min - :max.', + 'in' => 'The :attribute must be one of the following types: :values', +]; +``` -#### Specifying A Custom Message For A Given Attribute +#### Specifying a Custom Message for a Given Attribute Sometimes you may wish to specify a custom error message only for a specific attribute. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule: - $messages = [ - 'email.required' => 'We need to know your email address!', - ]; +```php +$messages = [ + 'email.required' => 'We need to know your email address!', +]; +``` #### Specifying Custom Attribute Values Many of Laravel's built-in error messages include an `:attribute` placeholder that is replaced with the name of the field or attribute under validation. To customize the values used to replace these placeholders for specific fields, you may pass an array of custom attributes as the fourth argument to the `Validator::make` method: - $validator = Validator::make($input, $rules, $messages, [ - 'email' => 'email address', - ]); +```php +$validator = Validator::make($input, $rules, $messages, [ + 'email' => 'email address', +]); +``` - -### After Validation Hook + +### Performing Additional Validation -You may also attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, call the `after` method on a validator instance: +Sometimes you need to perform additional validation after your initial validation is complete. You can accomplish this using the validator's `after` method. The `after` method accepts a closure or an array of callables which will be invoked after validation is complete. The given callables will receive an `Illuminate\Validation\Validator` instance, allowing you to raise additional error messages if necessary: - $validator = Validator::make(...); +```php +use Illuminate\Support\Facades\Validator; - $validator->after(function ($validator) { - if ($this->somethingElseIsInvalid()) { - $validator->errors()->add( - 'field', 'Something is wrong with this field!' - ); - } - }); +$validator = Validator::make(/* ... */); - if ($validator->fails()) { - // +$validator->after(function ($validator) { + if ($this->somethingElseIsInvalid()) { + $validator->errors()->add( + 'field', 'Something is wrong with this field!' + ); } +}); + +if ($validator->fails()) { + // ... +} +``` + +As noted, the `after` method also accepts an array of callables, which is particularly convenient if your "after validation" logic is encapsulated in invokable classes, which will receive an `Illuminate\Validation\Validator` instance via their `__invoke` method: + +```php +use App\Validation\ValidateShippingTime; +use App\Validation\ValidateUserStatus; + +$validator->after([ + new ValidateUserStatus, + new ValidateShippingTime, + function ($validator) { + // ... + }, +]); +``` ## Working With Validated Input After validating incoming request data using a form request or a manually created validator instance, you may wish to retrieve the incoming request data that actually underwent validation. This can be accomplished in several ways. First, you may call the `validated` method on a form request or validator instance. This method returns an array of the data that was validated: - $validated = $request->validated(); +```php +$validated = $request->validated(); - $validated = $validator->validated(); +$validated = $validator->validated(); +``` Alternatively, you may call the `safe` method on a form request or validator instance. This method returns an instance of `Illuminate\Support\ValidatedInput`. This object exposes `only`, `except`, and `all` methods to retrieve a subset of the validated data or the entire array of validated data: - $validated = $request->safe()->only(['name', 'email']); +```php +$validated = $request->safe()->only(['name', 'email']); - $validated = $request->safe()->except(['name', 'email']); +$validated = $request->safe()->except(['name', 'email']); - $validated = $request->safe()->all(); +$validated = $request->safe()->all(); +``` In addition, the `Illuminate\Support\ValidatedInput` instance may be iterated over and accessed like an array: - // Validated data may be iterated... - foreach ($request->safe() as $key => $value) { - // - } +```php +// Validated data may be iterated... +foreach ($request->safe() as $key => $value) { + // ... +} - // Validated data may be accessed as an array... - $validated = $request->safe(); +// Validated data may be accessed as an array... +$validated = $request->safe(); - $email = $validated['email']; +$email = $validated['email']; +``` If you would like to add additional fields to the validated data, you may call the `merge` method: - $validated = $request->safe()->merge(['name' => 'Taylor Otwell']); +```php +$validated = $request->safe()->merge(['name' => 'Taylor Otwell']); +``` If you would like to retrieve the validated data as a [collection](/docs/{{version}}/collections) instance, you may call the `collect` method: - $collection = $request->safe()->collect(); +```php +$collection = $request->safe()->collect(); +``` ## Working With Error Messages @@ -646,101 +814,130 @@ If you would like to retrieve the validated data as a [collection](/docs/{{versi After calling the `errors` method on a `Validator` instance, you will receive an `Illuminate\Support\MessageBag` instance, which has a variety of convenient methods for working with error messages. The `$errors` variable that is automatically made available to all views is also an instance of the `MessageBag` class. -#### Retrieving The First Error Message For A Field +#### Retrieving the First Error Message for a Field To retrieve the first error message for a given field, use the `first` method: - $errors = $validator->errors(); +```php +$errors = $validator->errors(); - echo $errors->first('email'); +echo $errors->first('email'); +``` -#### Retrieving All Error Messages For A Field +#### Retrieving All Error Messages for a Field If you need to retrieve an array of all the messages for a given field, use the `get` method: - foreach ($errors->get('email') as $message) { - // - } +```php +foreach ($errors->get('email') as $message) { + // ... +} +``` If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the `*` character: - foreach ($errors->get('attachments.*') as $message) { - // - } +```php +foreach ($errors->get('attachments.*') as $message) { + // ... +} +``` -#### Retrieving All Error Messages For All Fields +#### Retrieving All Error Messages for All Fields To retrieve an array of all messages for all fields, use the `all` method: - foreach ($errors->all() as $message) { - // - } +```php +foreach ($errors->all() as $message) { + // ... +} +``` -#### Determining If Messages Exist For A Field +#### Determining if Messages Exist for a Field The `has` method may be used to determine if any error messages exist for a given field: - if ($errors->has('email')) { - // - } +```php +if ($errors->has('email')) { + // ... +} +``` -### Specifying Custom Messages In Language Files +### Specifying Custom Messages in Language Files -Laravel's built-in validation rules each has an error message that is located in your application's `lang/en/validation.php` file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application. +Laravel's built-in validation rules each have an error message that is located in your application's `lang/en/validation.php` file. If your application does not have a `lang` directory, you may instruct Laravel to create it using the `lang:publish` Artisan command. -In addition, you may copy this file to another translation language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete [localization documentation](/docs/{{version}}/localization). +Within the `lang/en/validation.php` file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application. + +In addition, you may copy this file to another language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete [localization documentation](/docs/{{version}}/localization). + +> [!WARNING] +> By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. -#### Custom Messages For Specific Attributes +#### Custom Messages for Specific Attributes You may customize the error messages used for specified attribute and rule combinations within your application's validation language files. To do so, add your message customizations to the `custom` array of your application's `lang/xx/validation.php` language file: - 'custom' => [ - 'email' => [ - 'required' => 'We need to know your email address!', - 'max' => 'Your email address is too long!' - ], +```php +'custom' => [ + 'email' => [ + 'required' => 'We need to know your email address!', + 'max' => 'Your email address is too long!' ], +], +``` -### Specifying Attributes In Language Files +### Specifying Attributes in Language Files Many of Laravel's built-in error messages include an `:attribute` placeholder that is replaced with the name of the field or attribute under validation. If you would like the `:attribute` portion of your validation message to be replaced with a custom value, you may specify the custom attribute name in the `attributes` array of your `lang/xx/validation.php` language file: - 'attributes' => [ - 'email' => 'email address', - ], +```php +'attributes' => [ + 'email' => 'email address', +], +``` + +> [!WARNING] +> By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. -### Specifying Values In Language Files +### Specifying Values in Language Files Some of Laravel's built-in validation rule error messages contain a `:value` placeholder that is replaced with the current value of the request attribute. However, you may occasionally need the `:value` portion of your validation message to be replaced with a custom representation of the value. For example, consider the following rule that specifies that a credit card number is required if the `payment_type` has a value of `cc`: - Validator::make($request->all(), [ - 'credit_card_number' => 'required_if:payment_type,cc' - ]); +```php +Validator::make($request->all(), [ + 'credit_card_number' => 'required_if:payment_type,cc' +]); +``` If this validation rule fails, it will produce the following error message: -```none +```text The credit card number field is required when payment type is cc. ``` Instead of displaying `cc` as the payment type value, you may specify a more user-friendly value representation in your `lang/xx/validation.php` language file by defining a `values` array: - 'values' => [ - 'payment_type' => [ - 'cc' => 'credit card' - ], +```php +'values' => [ + 'payment_type' => [ + 'cc' => 'credit card' ], +], +``` + +> [!WARNING] +> By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command. After defining this value, the validation rule will produce the following error message: -```none +```text The credit card number field is required when payment type is credit card. ``` @@ -751,109 +948,204 @@ Below is a list of all available validation rules and their function: +#### Booleans +
[Accepted](#rule-accepted) [Accepted If](#rule-accepted-if) +[Boolean](#rule-boolean) +[Declined](#rule-declined) +[Declined If](#rule-declined-if) + +
+ +#### Strings + +
+ [Active URL](#rule-active-url) -[After (Date)](#rule-after) -[After Or Equal (Date)](#rule-after-or-equal) [Alpha](#rule-alpha) [Alpha Dash](#rule-alpha-dash) [Alpha Numeric](#rule-alpha-num) -[Array](#rule-array) -[Bail](#rule-bail) -[Before (Date)](#rule-before) -[Before Or Equal (Date)](#rule-before-or-equal) -[Between](#rule-between) -[Boolean](#rule-boolean) +[Ascii](#rule-ascii) [Confirmed](#rule-confirmed) [Current Password](#rule-current-password) -[Date](#rule-date) -[Date Equals](#rule-date-equals) -[Date Format](#rule-date-format) -[Declined](#rule-declined) -[Declined If](#rule-declined-if) [Different](#rule-different) -[Digits](#rule-digits) -[Digits Between](#rule-digits-between) -[Dimensions (Image Files)](#rule-dimensions) -[Distinct](#rule-distinct) +[Doesnt Start With](#rule-doesnt-start-with) +[Doesnt End With](#rule-doesnt-end-with) [Email](#rule-email) [Ends With](#rule-ends-with) [Enum](#rule-enum) -[Exclude](#rule-exclude) -[Exclude If](#rule-exclude-if) -[Exclude Unless](#rule-exclude-unless) -[Exclude Without](#rule-exclude-without) -[Exists (Database)](#rule-exists) -[File](#rule-file) -[Filled](#rule-filled) -[Greater Than](#rule-gt) -[Greater Than Or Equal](#rule-gte) -[Image (File)](#rule-image) +[Hex Color](#rule-hex-color) [In](#rule-in) -[In Array](#rule-in-array) -[Integer](#rule-integer) [IP Address](#rule-ip) -[MAC Address](#rule-mac) [JSON](#rule-json) +[Lowercase](#rule-lowercase) +[MAC Address](#rule-mac) +[Max](#rule-max) +[Min](#rule-min) +[Not In](#rule-not-in) +[Regular Expression](#rule-regex) +[Not Regular Expression](#rule-not-regex) +[Same](#rule-same) +[Size](#rule-size) +[Starts With](#rule-starts-with) +[String](#rule-string) +[Uppercase](#rule-uppercase) +[URL](#rule-url) +[ULID](#rule-ulid) +[UUID](#rule-uuid) + +
+ +#### Numbers + +
+ +[Between](#rule-between) +[Decimal](#rule-decimal) +[Different](#rule-different) +[Digits](#rule-digits) +[Digits Between](#rule-digits-between) +[Greater Than](#rule-gt) +[Greater Than Or Equal](#rule-gte) +[Integer](#rule-integer) [Less Than](#rule-lt) [Less Than Or Equal](#rule-lte) [Max](#rule-max) +[Max Digits](#rule-max-digits) +[Min](#rule-min) +[Min Digits](#rule-min-digits) +[Multiple Of](#rule-multiple-of) +[Numeric](#rule-numeric) +[Same](#rule-same) +[Size](#rule-size) + +
+ +#### Arrays + +
+ +[Array](#rule-array) +[Between](#rule-between) +[Contains](#rule-contains) +[Doesnt Contain](#rule-doesnt-contain) +[Distinct](#rule-distinct) +[In Array](#rule-in-array) +[In Array Keys](#rule-in-array-keys) +[List](#rule-list) +[Max](#rule-max) +[Min](#rule-min) +[Size](#rule-size) + +
+ +#### Dates + +
+ +[After](#rule-after) +[After Or Equal](#rule-after-or-equal) +[Before](#rule-before) +[Before Or Equal](#rule-before-or-equal) +[Date](#rule-date) +[Date Equals](#rule-date-equals) +[Date Format](#rule-date-format) +[Different](#rule-different) +[Timezone](#rule-timezone) + +
+ +#### Files + +
+ +[Between](#rule-between) +[Dimensions](#rule-dimensions) +[Extensions](#rule-extensions) +[File](#rule-file) +[Image](#rule-image) +[Max](#rule-max) [MIME Types](#rule-mimetypes) [MIME Type By File Extension](#rule-mimes) -[Min](#rule-min) -[Multiple Of](#multiple-of) -[Not In](#rule-not-in) -[Not Regex](#rule-not-regex) +[Size](#rule-size) + +
+ +#### Database + +
+ +[Exists](#rule-exists) +[Unique](#rule-unique) + +
+ +#### Utilities + +
+ +[Any Of](#rule-anyof) +[Bail](#rule-bail) +[Exclude](#rule-exclude) +[Exclude If](#rule-exclude-if) +[Exclude Unless](#rule-exclude-unless) +[Exclude With](#rule-exclude-with) +[Exclude Without](#rule-exclude-without) +[Filled](#rule-filled) +[Missing](#rule-missing) +[Missing If](#rule-missing-if) +[Missing Unless](#rule-missing-unless) +[Missing With](#rule-missing-with) +[Missing With All](#rule-missing-with-all) [Nullable](#rule-nullable) -[Numeric](#rule-numeric) -[Password](#rule-password) [Present](#rule-present) +[Present If](#rule-present-if) +[Present Unless](#rule-present-unless) +[Present With](#rule-present-with) +[Present With All](#rule-present-with-all) [Prohibited](#rule-prohibited) [Prohibited If](#rule-prohibited-if) +[Prohibited If Accepted](#rule-prohibited-if-accepted) +[Prohibited If Declined](#rule-prohibited-if-declined) [Prohibited Unless](#rule-prohibited-unless) [Prohibits](#rule-prohibits) -[Regular Expression](#rule-regex) [Required](#rule-required) [Required If](#rule-required-if) +[Required If Accepted](#rule-required-if-accepted) +[Required If Declined](#rule-required-if-declined) [Required Unless](#rule-required-unless) [Required With](#rule-required-with) [Required With All](#rule-required-with-all) [Required Without](#rule-required-without) [Required Without All](#rule-required-without-all) [Required Array Keys](#rule-required-array-keys) -[Same](#rule-same) -[Size](#rule-size) [Sometimes](#validating-when-present) -[Starts With](#rule-starts-with) -[String](#rule-string) -[Timezone](#rule-timezone) -[Unique (Database)](#rule-unique) -[URL](#rule-url) -[UUID](#rule-uuid)
#### accepted -The field under validation must be `"yes"`, `"on"`, `1`, or `true`. This is useful for validating "Terms of Service" acceptance or similar fields. +The field under validation must be `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"`. This is useful for validating "Terms of Service" acceptance or similar fields. #### accepted_if:anotherfield,value,... -The field under validation must be `"yes"`, `"on"`, `1`, or `true` if another field under validation is equal to a specified value. This is useful for validating "Terms of Service" acceptance or similar fields. +The field under validation must be `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"` if another field under validation is equal to a specified value. This is useful for validating "Terms of Service" acceptance or similar fields. #### active_url @@ -865,31 +1157,101 @@ The field under validation must have a valid A or AAAA record according to the ` The field under validation must be a value after a given date. The dates will be passed into the `strtotime` PHP function in order to be converted to a valid `DateTime` instance: - 'start_date' => 'required|date|after:tomorrow' +```php +'start_date' => 'required|date|after:tomorrow' +``` + +Instead of passing a date string to be evaluated by `strtotime`, you may specify another field to compare against the date: + +```php +'finish_date' => 'required|date|after:start_date' +``` + +For convenience, date-based rules may be constructed using the fluent `date` rule builder: + +```php +use Illuminate\Validation\Rule; + +'start_date' => [ + 'required', + Rule::date()->after(today()->addDays(7)), +], +``` -Instead of passing a date string to be evaluated by `strtotime`, you may specify another field to compare against the date: +The `afterToday` and `todayOrAfter` methods may be used to fluently express the date and must be after today, or today or after, respectively: - 'finish_date' => 'required|date|after:start_date' +```php +'start_date' => [ + 'required', + Rule::date()->afterToday(), +], +``` #### after\_or\_equal:_date_ The field under validation must be a value after or equal to the given date. For more information, see the [after](#rule-after) rule. +For convenience, date-based rules may be constructed using the fluent `date` rule builder: + +```php +use Illuminate\Validation\Rule; + +'start_date' => [ + 'required', + Rule::date()->afterOrEqual(today()->addDays(7)), +], +``` + + +#### anyOf + +The `Rule::anyOf` validation rule allows you to specify that the field under validation must satisfy any of the given validation rulesets. For example, the following rule will validate that the `username` field is either an email address or an alpha-numeric string (including dashes) that is at least 6 characters long: + +```php +use Illuminate\Validation\Rule; + +'username' => [ + 'required', + Rule::anyOf([ + ['string', 'email'], + ['string', 'alpha_dash', 'min:6'], + ]), +], +``` + #### alpha -The field under validation must be entirely alphabetic characters. +The field under validation must be entirely Unicode alphabetic characters contained in [\p{L}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=) and [\p{M}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=). + +To restrict this validation rule to characters in the ASCII range (`a-z` and `A-Z`), you may provide the `ascii` option to the validation rule: + +```php +'username' => 'alpha:ascii', +``` #### alpha_dash -The field under validation may have alpha-numeric characters, as well as dashes and underscores. +The field under validation must be entirely Unicode alpha-numeric characters contained in [\p{L}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=), [\p{M}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=), [\p{N}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AN%3A%5D&g=&i=), as well as ASCII dashes (`-`) and ASCII underscores (`_`). + +To restrict this validation rule to characters in the ASCII range (`a-z`, `A-Z`, and `0-9`), you may provide the `ascii` option to the validation rule: + +```php +'username' => 'alpha_dash:ascii', +``` #### alpha_num -The field under validation must be entirely alpha-numeric characters. +The field under validation must be entirely Unicode alpha-numeric characters contained in [\p{L}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=), [\p{M}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=), and [\p{N}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AN%3A%5D&g=&i=). + +To restrict this validation rule to characters in the ASCII range (`a-z`, `A-Z`, and `0-9`), you may provide the `ascii` option to the validation rule: + +```php +'username' => 'alpha_num:ascii', +``` #### array @@ -898,22 +1260,29 @@ The field under validation must be a PHP `array`. When additional values are provided to the `array` rule, each key in the input array must be present within the list of values provided to the rule. In the following example, the `admin` key in the input array is invalid since it is not contained in the list of values provided to the `array` rule: - use Illuminate\Support\Facades\Validator; +```php +use Illuminate\Support\Facades\Validator; - $input = [ - 'user' => [ - 'name' => 'Taylor Otwell', - 'username' => 'taylorotwell', - 'admin' => true, - ], - ]; +$input = [ + 'user' => [ + 'name' => 'Taylor Otwell', + 'username' => 'taylorotwell', + 'admin' => true, + ], +]; - Validator::make($input, [ - 'user' => 'array:username,locale', - ]); +Validator::make($input, [ + 'user' => 'array:name,username', +]); +``` In general, you should always specify the array keys that are allowed to be present within your array. + +#### ascii + +The field under validation must be entirely 7-bit ASCII characters. + #### bail @@ -921,41 +1290,120 @@ Stop running validation rules for the field after the first validation failure. While the `bail` rule will only stop validating a specific field when it encounters a validation failure, the `stopOnFirstFailure` method will inform the validator that it should stop validating all attributes once a single validation failure has occurred: - if ($validator->stopOnFirstFailure()->fails()) { - // ... - } +```php +if ($validator->stopOnFirstFailure()->fails()) { + // ... +} +``` #### before:_date_ -The field under validation must be a value preceding the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. In addition, like the [`after`](#rule-after) rule, the name of another field under validation may be supplied as the value of `date`. +The field under validation must be a value preceding the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. In addition, like the [after](#rule-after) rule, the name of another field under validation may be supplied as the value of `date`. + +For convenience, date-based rules may also be constructed using the fluent `date` rule builder: + +```php +use Illuminate\Validation\Rule; + +'start_date' => [ + 'required', + Rule::date()->before(today()->subDays(7)), +], +``` + +The `beforeToday` and `todayOrBefore` methods may be used to fluently express the date and must be before today, or today or before, respectively: + +```php +'start_date' => [ + 'required', + Rule::date()->beforeToday(), +], +``` #### before\_or\_equal:_date_ -The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. In addition, like the [`after`](#rule-after) rule, the name of another field under validation may be supplied as the value of `date`. +The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. In addition, like the [after](#rule-after) rule, the name of another field under validation may be supplied as the value of `date`. + +For convenience, date-based rules may also be constructed using the fluent `date` rule builder: + +```php +use Illuminate\Validation\Rule; + +'start_date' => [ + 'required', + Rule::date()->beforeOrEqual(today()->subDays(7)), +], +``` #### between:_min_,_max_ -The field under validation must have a size between the given _min_ and _max_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule. +The field under validation must have a size between the given _min_ and _max_ (inclusive). Strings, numerics, arrays, and files are evaluated in the same fashion as the [size](#rule-size) rule. #### boolean The field under validation must be able to be cast as a boolean. Accepted input are `true`, `false`, `1`, `0`, `"1"`, and `"0"`. +You may use the `strict` parameter to only consider the field valid if its value is `true` or `false`: + +```php +'foo' => 'boolean:strict' +``` + #### confirmed The field under validation must have a matching field of `{field}_confirmation`. For example, if the field under validation is `password`, a matching `password_confirmation` field must be present in the input. +You may also pass a custom confirmation field name. For example, `confirmed:repeat_username` will expect the field `repeat_username` to match the field under validation. + + +#### contains:_foo_,_bar_,... + +The field under validation must be an array that contains all of the given parameter values. Since this rule often requires you to `implode` an array, the `Rule::contains` method may be used to fluently construct the rule: + +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; + +Validator::make($data, [ + 'roles' => [ + 'required', + 'array', + Rule::contains(['admin', 'editor']), + ], +]); +``` + + +#### doesnt_contain:_foo_,_bar_,... + +The field under validation must be an array that does not contain any of the given parameter values. Since this rule often requires you to `implode` an array, the `Rule::doesntContain` method may be used to fluently construct the rule: + +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; + +Validator::make($data, [ + 'roles' => [ + 'required', + 'array', + Rule::doesntContain(['admin', 'editor']), + ], +]); +``` + #### current_password The field under validation must match the authenticated user's password. You may specify an [authentication guard](/docs/{{version}}/authentication) using the rule's first parameter: - 'password' => 'current_password:api' +```php +'password' => 'current_password:api' +``` #### date @@ -968,19 +1416,43 @@ The field under validation must be a valid, non-relative date according to the ` The field under validation must be equal to the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. -#### date_format:_format_ +#### date_format:_format_,... + +The field under validation must match one of the given _formats_. You should use **either** `date` or `date_format` when validating a field, not both. This validation rule supports all formats supported by PHP's [DateTime](https://www.php.net/manual/en/class.datetime.php) class. + +For convenience, date-based rules may be constructed using the fluent `date` rule builder: + +```php +use Illuminate\Validation\Rule; + +'start_date' => [ + 'required', + Rule::date()->format('Y-m-d'), +], +``` + + +#### decimal:_min_,_max_ + +The field under validation must be numeric and must contain the specified number of decimal places: + +```php +// Must have exactly two decimal places (9.99)... +'price' => 'decimal:2' -The field under validation must match the given _format_. You should use **either** `date` or `date_format` when validating a field, not both. This validation rule supports all formats supported by PHP's [DateTime](https://www.php.net/manual/en/class.datetime.php) class. +// Must have between 2 and 4 decimal places... +'price' => 'decimal:2,4' +``` #### declined -The field under validation must be `"no"`, `"off"`, `0`, or `false`. +The field under validation must be `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"`. #### declined_if:anotherfield,value,... -The field under validation must be `"no"`, `"off"`, `0`, or `false` if another field under validation is equal to a specified value. +The field under validation must be `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"` if another field under validation is equal to a specified value. #### different:_field_ @@ -990,75 +1462,118 @@ The field under validation must have a different value than _field_. #### digits:_value_ -The field under validation must be _numeric_ and must have an exact length of _value_. +The integer under validation must have an exact length of _value_. #### digits_between:_min_,_max_ -The field under validation must be _numeric_ and must have a length between the given _min_ and _max_. +The integer under validation must have a length between the given _min_ and _max_. #### dimensions The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters: - 'avatar' => 'dimensions:min_width=100,min_height=200' +```php +'avatar' => 'dimensions:min_width=100,min_height=200' +``` Available constraints are: _min\_width_, _max\_width_, _min\_height_, _max\_height_, _width_, _height_, _ratio_. A _ratio_ constraint should be represented as width divided by height. This can be specified either by a fraction like `3/2` or a float like `1.5`: - 'avatar' => 'dimensions:ratio=3/2' - -Since this rule requires several arguments, you may use the `Rule::dimensions` method to fluently construct the rule: +```php +'avatar' => 'dimensions:ratio=3/2' +``` - use Illuminate\Support\Facades\Validator; - use Illuminate\Validation\Rule; +Since this rule requires several arguments, it is often more convenient to use the `Rule::dimensions` method to fluently construct the rule: - Validator::make($data, [ - 'avatar' => [ - 'required', - Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2), - ], - ]); +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; + +Validator::make($data, [ + 'avatar' => [ + 'required', + Rule::dimensions() + ->maxWidth(1000) + ->maxHeight(500) + ->ratio(3 / 2), + ], +]); +``` #### distinct When validating arrays, the field under validation must not have any duplicate values: - 'foo.*.id' => 'distinct' +```php +'foo.*.id' => 'distinct' +``` Distinct uses loose variable comparisons by default. To use strict comparisons, you may add the `strict` parameter to your validation rule definition: - 'foo.*.id' => 'distinct:strict' +```php +'foo.*.id' => 'distinct:strict' +``` You may add `ignore_case` to the validation rule's arguments to make the rule ignore capitalization differences: - 'foo.*.id' => 'distinct:ignore_case' +```php +'foo.*.id' => 'distinct:ignore_case' +``` + + +#### doesnt_start_with:_foo_,_bar_,... + +The field under validation must not start with one of the given values. + + +#### doesnt_end_with:_foo_,_bar_,... + +The field under validation must not end with one of the given values. #### email -The field under validation must be formatted as an email address. This validation rule utilizes the [`egulias/email-validator`](https://github.com/egulias/EmailValidator) package for validating the email address. By default, the `RFCValidation` validator is applied, but you can apply other validation styles as well: +The field under validation must be formatted as an email address. This validation rule utilizes the [egulias/email-validator](https://github.com/egulias/EmailValidator) package for validating the email address. By default, the `RFCValidation` validator is applied, but you can apply other validation styles as well: - 'email' => 'email:rfc,dns' +```php +'email' => 'email:rfc,dns' +``` The example above will apply the `RFCValidation` and `DNSCheckValidation` validations. Here's a full list of validation styles you can apply:
-- `rfc`: `RFCValidation` -- `strict`: `NoRFCWarningsValidation` -- `dns`: `DNSCheckValidation` -- `spoof`: `SpoofCheckValidation` -- `filter`: `FilterEmailValidation` +- `rfc`: `RFCValidation` - Validate the email address according to [supported RFCs](https://github.com/egulias/EmailValidator?tab=readme-ov-file#supported-rfcs). +- `strict`: `NoRFCWarningsValidation` - Validate the email according to [supported RFCs](https://github.com/egulias/EmailValidator?tab=readme-ov-file#supported-rfcs), failing when warnings are found (e.g. trailing periods and multiple consecutive periods). +- `dns`: `DNSCheckValidation` - Ensure the email address's domain has a valid MX record. +- `spoof`: `SpoofCheckValidation` - Ensure the email address does not contain homograph or deceptive Unicode characters. +- `filter`: `FilterEmailValidation` - Ensure the email address is valid according to PHP's `filter_var` function. +- `filter_unicode`: `FilterEmailValidation::unicode()` - Ensure the email address is valid according to PHP's `filter_var` function, allowing some Unicode characters.
-The `filter` validator, which uses PHP's `filter_var` function, ships with Laravel and was Laravel's default email validation behavior prior to Laravel version 5.8. +For convenience, email validation rules may be built using the fluent rule builder: -> {note} The `dns` and `spoof` validators require the PHP `intl` extension. +```php +use Illuminate\Validation\Rule; + +$request->validate([ + 'email' => [ + 'required', + Rule::email() + ->rfcCompliant(strict: false) + ->validateMxRecord() + ->preventSpoofing() + ], +]); +``` + +> [!WARNING] +> The `dns` and `spoof` validators require the PHP `intl` extension. #### ends_with:_foo_,_bar_,... @@ -1068,16 +1583,40 @@ The field under validation must end with one of the given values. #### enum -The `Enum` rule is a class based rule that validates whether the field under validation contains a valid enum value. The `Enum` rule accepts the name of the enum as its only constructor argument: +The `Enum` rule is a class-based rule that validates whether the field under validation contains a valid enum value. The `Enum` rule accepts the name of the enum as its only constructor argument. When validating primitive values, a backed Enum should be provided to the `Enum` rule: - use App\Enums\ServerStatus; - use Illuminate\Validation\Rules\Enum; +```php +use App\Enums\ServerStatus; +use Illuminate\Validation\Rule; - $request->validate([ - 'status' => [new Enum(ServerStatus::class)], - ]); +$request->validate([ + 'status' => [Rule::enum(ServerStatus::class)], +]); +``` + +The `Enum` rule's `only` and `except` methods may be used to limit which enum cases should be considered valid: -> {note} Enums are only available on PHP 8.1+. +```php +Rule::enum(ServerStatus::class) + ->only([ServerStatus::Pending, ServerStatus::Active]); + +Rule::enum(ServerStatus::class) + ->except([ServerStatus::Pending, ServerStatus::Active]); +``` + +The `when` method may be used to conditionally modify the `Enum` rule: + +```php +use Illuminate\Support\Facades\Auth; +use Illuminate\Validation\Rule; + +Rule::enum(ServerStatus::class) + ->when( + Auth::user()->isAdmin(), + fn ($rule) => $rule->only(...), + fn ($rule) => $rule->only(...), + ); +``` #### exclude @@ -1089,11 +1628,31 @@ The field under validation will be excluded from the request data returned by th The field under validation will be excluded from the request data returned by the `validate` and `validated` methods if the _anotherfield_ field is equal to _value_. +If complex conditional exclusion logic is required, you may utilize the `Rule::excludeIf` method. This method accepts a boolean or a closure. When given a closure, the closure should return `true` or `false` to indicate if the field under validation should be excluded: + +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; + +Validator::make($request->all(), [ + 'role_id' => Rule::excludeIf($request->user()->is_admin), +]); + +Validator::make($request->all(), [ + 'role_id' => Rule::excludeIf(fn () => $request->user()->is_admin), +]); +``` + #### exclude_unless:_anotherfield_,_value_ The field under validation will be excluded from the request data returned by the `validate` and `validated` methods unless _anotherfield_'s field is equal to _value_. If _value_ is `null` (`exclude_unless:name,null`), the field under validation will be excluded unless the comparison field is `null` or the comparison field is missing from the request data. + +#### exclude_with:_anotherfield_ + +The field under validation will be excluded from the request data returned by the `validate` and `validated` methods if the _anotherfield_ field is present. + #### exclude_without:_anotherfield_ @@ -1105,40 +1664,77 @@ The field under validation will be excluded from the request data returned by th The field under validation must exist in a given database table. -#### Basic Usage Of Exists Rule +#### Basic Usage of Exists Rule - 'state' => 'exists:states' +```php +'state' => 'exists:states' +``` If the `column` option is not specified, the field name will be used. So, in this case, the rule will validate that the `states` database table contains a record with a `state` column value matching the request's `state` attribute value. -#### Specifying A Custom Column Name +#### Specifying a Custom Column Name You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name: - 'state' => 'exists:states,abbreviation' +```php +'state' => 'exists:states,abbreviation' +``` Occasionally, you may need to specify a specific database connection to be used for the `exists` query. You can accomplish this by prepending the connection name to the table name: - 'email' => 'exists:connection.staff,email' +```php +'email' => 'exists:connection.staff,email' +``` Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name: - 'user_id' => 'exists:App\Models\User,id' +```php +'user_id' => 'exists:App\Models\User,id' +``` If you would like to customize the query executed by the validation rule, you may use the `Rule` class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the `|` character to delimit them: - use Illuminate\Support\Facades\Validator; - use Illuminate\Validation\Rule; +```php +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; + +Validator::make($data, [ + 'email' => [ + 'required', + Rule::exists('staff')->where(function (Builder $query) { + $query->where('account_id', 1); + }), + ], +]); +``` + +You may explicitly specify the database column name that should be used by the `exists` rule generated by the `Rule::exists` method by providing the column name as the second argument to the `exists` method: - Validator::make($data, [ - 'email' => [ - 'required', - Rule::exists('staff')->where(function ($query) { - return $query->where('account_id', 1); - }), - ], - ]); +```php +'state' => Rule::exists('states', 'abbreviation'), +``` + +Sometimes, you may wish to validate whether an array of values exists in the database. You can do so by adding both the `exists` and [array](#rule-array) rules to the field being validated: + +```php +'states' => ['array', Rule::exists('states', 'abbreviation')], +``` + +When both of these rules are assigned to a field, Laravel will automatically build a single query to determine if all of the given values exist in the specified table. + + +#### extensions:_foo_,_bar_,... + +The file under validation must have a user-assigned extension corresponding to one of the listed extensions: + +```php +'photo' => ['required', 'extensions:jpg,png'], +``` + +> [!WARNING] +> You should never rely on validating a file by its user-assigned extension alone. This rule should typically always be used in combination with the [mimes](#rule-mimes) or [mimetypes](#rule-mimetypes) rules. #### file @@ -1153,61 +1749,89 @@ The field under validation must not be empty when it is present. #### gt:_field_ -The field under validation must be greater than the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule. +The field under validation must be greater than the given _field_ or _value_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [size](#rule-size) rule. #### gte:_field_ -The field under validation must be greater than or equal to the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule. +The field under validation must be greater than or equal to the given _field_ or _value_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [size](#rule-size) rule. + + +#### hex_color + +The field under validation must contain a valid color value in [hexadecimal](https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color) format. #### image -The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp). +The file under validation must be an image (jpg, jpeg, png, bmp, gif, or webp). + +> [!WARNING] +> By default, the image rule does not allow SVG files due to the possibility of XSS vulnerabilities. If you need to allow SVG files, you may provide the `allow_svg` directive to the `image` rule (`image:allow_svg`). #### in:_foo_,_bar_,... The field under validation must be included in the given list of values. Since this rule often requires you to `implode` an array, the `Rule::in` method may be used to fluently construct the rule: - use Illuminate\Support\Facades\Validator; - use Illuminate\Validation\Rule; +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; - Validator::make($data, [ - 'zones' => [ - 'required', - Rule::in(['first-zone', 'second-zone']), - ], - ]); +Validator::make($data, [ + 'zones' => [ + 'required', + Rule::in(['first-zone', 'second-zone']), + ], +]); +``` When the `in` rule is combined with the `array` rule, each value in the input array must be present within the list of values provided to the `in` rule. In the following example, the `LAS` airport code in the input array is invalid since it is not contained in the list of airports provided to the `in` rule: - use Illuminate\Support\Facades\Validator; - use Illuminate\Validation\Rule; +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; - $input = [ - 'airports' => ['NYC', 'LAS'], - ]; +$input = [ + 'airports' => ['NYC', 'LAS'], +]; - Validator::make($input, [ - 'airports' => [ - 'required', - 'array', - Rule::in(['NYC', 'LIT']), - ], - ]); +Validator::make($input, [ + 'airports' => [ + 'required', + 'array', + ], + 'airports.*' => Rule::in(['NYC', 'LIT']), +]); +``` #### in_array:_anotherfield_.* The field under validation must exist in _anotherfield_'s values. + +#### in_array_keys:_value_.* + +The field under validation must be an array having at least one of the given _values_ as a key within the array: + +```php +'config' => 'array|in_array_keys:timezone' +``` + #### integer The field under validation must be an integer. -> {note} This validation rule does not verify that the input is of the "integer" variable type, only that the input is of a type accepted by PHP's `FILTER_VALIDATE_INT` rule. If you need to validate the input as being a number please use this rule in combination with [the `numeric` validation rule](#rule-numeric). +You may use the `strict` parameter to only consider the field valid if its type is `integer`. Strings with integer values will be considered invalid: + +```php +'age' => 'integer:strict' +``` + +> [!WARNING] +> This validation rule does not verify that the input is of the "integer" variable type, only that the input is of a type accepted by PHP's `FILTER_VALIDATE_INT` rule. If you need to validate the input as being a number please use this rule in combination with [the `numeric` validation rule](#rule-numeric). #### ip @@ -1224,11 +1848,6 @@ The field under validation must be an IPv4 address. The field under validation must be an IPv6 address. - -#### mac_address - -The field under validation must be a MAC address. - #### json @@ -1237,66 +1856,122 @@ The field under validation must be a valid JSON string. #### lt:_field_ -The field under validation must be less than the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule. +The field under validation must be less than the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [size](#rule-size) rule. #### lte:_field_ -The field under validation must be less than or equal to the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule. +The field under validation must be less than or equal to the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [size](#rule-size) rule. + + +#### lowercase + +The field under validation must be lowercase. + + +#### list + +The field under validation must be an array that is a list. An array is considered a list if its keys consist of consecutive numbers from 0 to `count($array) - 1`. + + +#### mac_address + +The field under validation must be a MAC address. #### max:_value_ -The field under validation must be less than or equal to a maximum _value_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule. +The field under validation must be less than or equal to a maximum _value_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [size](#rule-size) rule. + + +#### max_digits:_value_ + +The integer under validation must have a maximum length of _value_. #### mimetypes:_text/plain_,... The file under validation must match one of the given MIME types: - 'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime' +```php +'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime' +``` To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client's provided MIME type. #### mimes:_foo_,_bar_,... -The file under validation must have a MIME type corresponding to one of the listed extensions. +The file under validation must have a MIME type corresponding to one of the listed extensions: - -#### Basic Usage Of MIME Rule - - 'photo' => 'mimes:jpg,bmp,png' +```php +'photo' => 'mimes:jpg,bmp,png' +``` Even though you only need to specify the extensions, this rule actually validates the MIME type of the file by reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location: [https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + +#### MIME Types and Extensions + +This validation rule does not verify agreement between the MIME type and the extension the user assigned to the file. For example, the `mimes:png` validation rule would consider a file containing valid PNG content to be a valid PNG image, even if the file is named `photo.txt`. If you would like to validate the user-assigned extension of the file, you may use the [extensions](#rule-extensions) rule. + #### min:_value_ -The field under validation must have a minimum _value_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule. +The field under validation must have a minimum _value_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [size](#rule-size) rule. + + +#### min_digits:_value_ - +The integer under validation must have a minimum length of _value_. + + #### multiple_of:_value_ The field under validation must be a multiple of _value_. -> {note} The [`bcmath` PHP extension](https://www.php.net/manual/en/book.bc.php) is required in order to use the `multiple_of` rule. + +#### missing + +The field under validation must not be present in the input data. + + +#### missing_if:_anotherfield_,_value_,... + +The field under validation must not be present if the _anotherfield_ field is equal to any _value_. + + +#### missing_unless:_anotherfield_,_value_ + +The field under validation must not be present unless the _anotherfield_ field is equal to any _value_. + + +#### missing_with:_foo_,_bar_,... + +The field under validation must not be present _only if_ any of the other specified fields are present. + + +#### missing_with_all:_foo_,_bar_,... + +The field under validation must not be present _only if_ all of the other specified fields are present. #### not_in:_foo_,_bar_,... The field under validation must not be included in the given list of values. The `Rule::notIn` method may be used to fluently construct the rule: - use Illuminate\Validation\Rule; +```php +use Illuminate\Validation\Rule; - Validator::make($data, [ - 'toppings' => [ - 'required', - Rule::notIn(['sprinkles', 'cherries']), - ], - ]); +Validator::make($data, [ + 'toppings' => [ + 'required', + Rule::notIn(['sprinkles', 'cherries']), + ], +]); +``` #### not_regex:_pattern_ @@ -1305,7 +1980,8 @@ The field under validation must not match the given regular expression. Internally, this rule uses the PHP `preg_match` function. The pattern specified should obey the same formatting required by `preg_match` and thus also include valid delimiters. For example: `'email' => 'not_regex:/^.+$/i'`. -> {note} When using the `regex` / `not_regex` patterns, it may be necessary to specify your validation rules using an array instead of using `|` delimiters, especially if the regular expression contains a `|` character. +> [!WARNING] +> When using the `regex` / `not_regex` patterns, it may be necessary to specify your validation rules using an array instead of using `|` delimiters, especially if the regular expression contains a `|` character. #### nullable @@ -1317,37 +1993,116 @@ The field under validation may be `null`. The field under validation must be [numeric](https://www.php.net/manual/en/function.is-numeric.php). - -#### password - -The field under validation must match the authenticated user's password. +You may use the `strict` parameter to only consider the field valid if its value is an integer or float type. Numeric strings will be considered invalid: -> {note} This rule was renamed to `current_password` with the intention of removing it in Laravel 9. Please use the [Current Password](#rule-current-password) rule instead. +```php +'amount' => 'numeric:strict' +``` #### present -The field under validation must be present in the input data but can be empty. +The field under validation must exist in the input data. + + +#### present_if:_anotherfield_,_value_,... + +The field under validation must be present if the _anotherfield_ field is equal to any _value_. + + +#### present_unless:_anotherfield_,_value_ + +The field under validation must be present unless the _anotherfield_ field is equal to any _value_. + + +#### present_with:_foo_,_bar_,... + +The field under validation must be present _only if_ any of the other specified fields are present. + + +#### present_with_all:_foo_,_bar_,... + +The field under validation must be present _only if_ all of the other specified fields are present. + + +#### prohibited + +The field under validation must be missing or empty. A field is "empty" if it meets one of the following criteria: + +
+ +- The value is `null`. +- The value is an empty string. +- The value is an empty array or empty `Countable` object. +- The value is an uploaded file with an empty path. + +
+ + +#### prohibited_if:_anotherfield_,_value_,... + +The field under validation must be missing or empty if the _anotherfield_ field is equal to any _value_. A field is "empty" if it meets one of the following criteria: + +
+ +- The value is `null`. +- The value is an empty string. +- The value is an empty array or empty `Countable` object. +- The value is an uploaded file with an empty path. + +
+ +If complex conditional prohibition logic is required, you may utilize the `Rule::prohibitedIf` method. This method accepts a boolean or a closure. When given a closure, the closure should return `true` or `false` to indicate if the field under validation should be prohibited: + +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; + +Validator::make($request->all(), [ + 'role_id' => Rule::prohibitedIf($request->user()->is_admin), +]); - -#### prohibited +Validator::make($request->all(), [ + 'role_id' => Rule::prohibitedIf(fn () => $request->user()->is_admin), +]); +``` + +#### prohibited_if_accepted:_anotherfield_,... -The field under validation must be empty or not present. +The field under validation must be missing or empty if the _anotherfield_ field is equal to `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"`. - -#### prohibited_if:_anotherfield_,_value_,... + +#### prohibited_if_declined:_anotherfield_,... -The field under validation must be empty or not present if the _anotherfield_ field is equal to any _value_. +The field under validation must be missing or empty if the _anotherfield_ field is equal to `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"`. #### prohibited_unless:_anotherfield_,_value_,... -The field under validation must be empty or not present unless the _anotherfield_ field is equal to any _value_. +The field under validation must be missing or empty unless the _anotherfield_ field is equal to any _value_. A field is "empty" if it meets one of the following criteria: + +
+ +- The value is `null`. +- The value is an empty string. +- The value is an empty array or empty `Countable` object. +- The value is an uploaded file with an empty path. + +
#### prohibits:_anotherfield_,... -If the field under validation is present, no fields in _anotherfield_ can be present, even if empty. +If the field under validation is not missing or empty, all fields in _anotherfield_ must be missing or empty. A field is "empty" if it meets one of the following criteria: + +
+ +- The value is `null`. +- The value is an empty string. +- The value is an empty array or empty `Countable` object. +- The value is an uploaded file with an empty path. + +
#### regex:_pattern_ @@ -1356,12 +2111,13 @@ The field under validation must match the given regular expression. Internally, this rule uses the PHP `preg_match` function. The pattern specified should obey the same formatting required by `preg_match` and thus also include valid delimiters. For example: `'email' => 'regex:/^.+@.+$/i'`. -> {note} When using the `regex` / `not_regex` patterns, it may be necessary to specify rules in an array instead of using `|` delimiters, especially if the regular expression contains a `|` character. +> [!WARNING] +> When using the `regex` / `not_regex` patterns, it may be necessary to specify rules in an array instead of using `|` delimiters, especially if the regular expression contains a `|` character. #### required -The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true: +The field under validation must be present in the input data and not empty. A field is "empty" if it meets one of the following criteria:
@@ -1379,18 +2135,28 @@ The field under validation must be present and not empty if the _anotherfield_ f If you would like to construct a more complex condition for the `required_if` rule, you may use the `Rule::requiredIf` method. This method accepts a boolean or a closure. When passed a closure, the closure should return `true` or `false` to indicate if the field under validation is required: - use Illuminate\Support\Facades\Validator; - use Illuminate\Validation\Rule; +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; - Validator::make($request->all(), [ - 'role_id' => Rule::requiredIf($request->user()->is_admin), - ]); +Validator::make($request->all(), [ + 'role_id' => Rule::requiredIf($request->user()->is_admin), +]); - Validator::make($request->all(), [ - 'role_id' => Rule::requiredIf(function () use ($request) { - return $request->user()->is_admin; - }), - ]); +Validator::make($request->all(), [ + 'role_id' => Rule::requiredIf(fn () => $request->user()->is_admin), +]); +``` + + +#### required_if_accepted:_anotherfield_,... + +The field under validation must be present and not empty if the _anotherfield_ field is equal to `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"`. + + +#### required_if_declined:_anotherfield_,... + +The field under validation must be present and not empty if the _anotherfield_ field is equal to `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"`. #### required_unless:_anotherfield_,_value_,... @@ -1432,17 +2198,19 @@ The given _field_ must match the field under validation. The field under validation must have a size matching the given _value_. For string data, _value_ corresponds to the number of characters. For numeric data, _value_ corresponds to a given integer value (the attribute must also have the `numeric` or `integer` rule). For an array, _size_ corresponds to the `count` of the array. For files, _size_ corresponds to the file size in kilobytes. Let's look at some examples: - // Validate that a string is exactly 12 characters long... - 'title' => 'size:12'; +```php +// Validate that a string is exactly 12 characters long... +'title' => 'size:12'; - // Validate that a provided integer equals 10... - 'seats' => 'integer|size:10'; +// Validate that a provided integer equals 10... +'seats' => 'integer|size:10'; - // Validate that an array has exactly 5 elements... - 'tags' => 'array|size:5'; +// Validate that an array has exactly 5 elements... +'tags' => 'array|size:5'; - // Validate that an uploaded file is exactly 512 kilobytes... - 'image' => 'file|size:512'; +// Validate that an uploaded file is exactly 512 kilobytes... +'image' => 'file|size:512'; +``` #### starts_with:_foo_,_bar_,... @@ -1457,76 +2225,139 @@ The field under validation must be a string. If you would like to allow the fiel #### timezone -The field under validation must be a valid timezone identifier according to the `timezone_identifiers_list` PHP function. +The field under validation must be a valid timezone identifier according to the `DateTimeZone::listIdentifiers` method. + +The arguments [accepted by the `DateTimeZone::listIdentifiers` method](https://www.php.net/manual/en/datetimezone.listidentifiers.php) may also be provided to this validation rule: + +```php +'timezone' => 'required|timezone:all'; + +'timezone' => 'required|timezone:Africa'; + +'timezone' => 'required|timezone:per_country,US'; +``` #### unique:_table_,_column_ The field under validation must not exist within the given database table. -**Specifying A Custom Table / Column Name:** +**Specifying a Custom Table / Column Name:** Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name: - 'email' => 'unique:App\Models\User,email_address' +```php +'email' => 'unique:App\Models\User,email_address' +``` The `column` option may be used to specify the field's corresponding database column. If the `column` option is not specified, the name of the field under validation will be used. - 'email' => 'unique:users,email_address' +```php +'email' => 'unique:users,email_address' +``` -**Specifying A Custom Database Connection** +**Specifying a Custom Database Connection** Occasionally, you may need to set a custom connection for database queries made by the Validator. To accomplish this, you may prepend the connection name to the table name: - 'email' => 'unique:connection.users,email_address' +```php +'email' => 'unique:connection.users,email_address' +``` -**Forcing A Unique Rule To Ignore A Given ID:** +**Forcing a Unique Rule to Ignore a Given ID:** Sometimes, you may wish to ignore a given ID during unique validation. For example, consider an "update profile" screen that includes the user's name, email address, and location. You will probably want to verify that the email address is unique. However, if the user only changes the name field and not the email field, you do not want a validation error to be thrown because the user is already the owner of the email address in question. To instruct the validator to ignore the user's ID, we'll use the `Rule` class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the `|` character to delimit the rules: - use Illuminate\Support\Facades\Validator; - use Illuminate\Validation\Rule; +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; - Validator::make($data, [ - 'email' => [ - 'required', - Rule::unique('users')->ignore($user->id), - ], - ]); +Validator::make($data, [ + 'email' => [ + 'required', + Rule::unique('users')->ignore($user->id), + ], +]); +``` -> {note} You should never pass any user controlled request input into the `ignore` method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack. +> [!WARNING] +> You should never pass any user controlled request input into the `ignore` method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack. Instead of passing the model key's value to the `ignore` method, you may also pass the entire model instance. Laravel will automatically extract the key from the model: - Rule::unique('users')->ignore($user) +```php +Rule::unique('users')->ignore($user) +``` If your table uses a primary key column name other than `id`, you may specify the name of the column when calling the `ignore` method: - Rule::unique('users')->ignore($user->id, 'user_id') +```php +Rule::unique('users')->ignore($user->id, 'user_id') +``` By default, the `unique` rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the `unique` method: - Rule::unique('users', 'email_address')->ignore($user->id), +```php +Rule::unique('users', 'email_address')->ignore($user->id) +``` **Adding Additional Where Clauses:** You may specify additional query conditions by customizing the query using the `where` method. For example, let's add a query condition that scopes the query to only search records that have an `account_id` column value of `1`: - 'email' => Rule::unique('users')->where(function ($query) { - return $query->where('account_id', 1); - }) +```php +'email' => Rule::unique('users')->where(fn (Builder $query) => $query->where('account_id', 1)) +``` + +**Ignoring Soft Deleted Records in Unique Checks:** + +By default, the unique rule includes soft deleted records when determining uniqueness. To exclude soft deleted records from the uniqueness check, you may invoke the `withoutTrashed` method: + +```php +Rule::unique('users')->withoutTrashed(); +``` + +If your model uses a column name other than `deleted_at` for soft deleted records, you may provide the column name when invoking the `withoutTrashed` method: + +```php +Rule::unique('users')->withoutTrashed('was_deleted_at'); +``` + + +#### uppercase + +The field under validation must be uppercase. #### url The field under validation must be a valid URL. +If you would like to specify the URL protocols that should be considered valid, you may pass the protocols as validation rule parameters: + +```php +'url' => 'url:http,https', + +'game' => 'url:minecraft,steam', +``` + + +#### ulid + +The field under validation must be a valid [Universally Unique Lexicographically Sortable Identifier](https://github.com/ulid/spec) (ULID). + #### uuid -The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID). +The field under validation must be a valid RFC 9562 (version 1, 3, 4, 5, 6, 7, or 8) universally unique identifier (UUID). + +You may also validate that the given UUID matches a UUID specification by version: + +```php +'uuid' => 'uuid:4' +``` ## Conditionally Adding Rules @@ -1536,202 +2367,361 @@ The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) univ You may occasionally wish to not validate a given field if another field has a given value. You may accomplish this using the `exclude_if` validation rule. In this example, the `appointment_date` and `doctor_name` fields will not be validated if the `has_appointment` field has a value of `false`: - use Illuminate\Support\Facades\Validator; +```php +use Illuminate\Support\Facades\Validator; - $validator = Validator::make($data, [ - 'has_appointment' => 'required|boolean', - 'appointment_date' => 'exclude_if:has_appointment,false|required|date', - 'doctor_name' => 'exclude_if:has_appointment,false|required|string', - ]); +$validator = Validator::make($data, [ + 'has_appointment' => 'required|boolean', + 'appointment_date' => 'exclude_if:has_appointment,false|required|date', + 'doctor_name' => 'exclude_if:has_appointment,false|required|string', +]); +``` Alternatively, you may use the `exclude_unless` rule to not validate a given field unless another field has a given value: - $validator = Validator::make($data, [ - 'has_appointment' => 'required|boolean', - 'appointment_date' => 'exclude_unless:has_appointment,true|required|date', - 'doctor_name' => 'exclude_unless:has_appointment,true|required|string', - ]); +```php +$validator = Validator::make($data, [ + 'has_appointment' => 'required|boolean', + 'appointment_date' => 'exclude_unless:has_appointment,true|required|date', + 'doctor_name' => 'exclude_unless:has_appointment,true|required|string', +]); +``` #### Validating When Present In some situations, you may wish to run validation checks against a field **only** if that field is present in the data being validated. To quickly accomplish this, add the `sometimes` rule to your rule list: - $v = Validator::make($data, [ - 'email' => 'sometimes|required|email', - ]); +```php +$validator = Validator::make($data, [ + 'email' => 'sometimes|required|email', +]); +``` In the example above, the `email` field will only be validated if it is present in the `$data` array. -> {tip} If you are attempting to validate a field that should always be present but may be empty, check out [this note on optional fields](#a-note-on-optional-fields). +> [!NOTE] +> If you are attempting to validate a field that should always be present but may be empty, check out [this note on optional fields](#a-note-on-optional-fields). #### Complex Conditional Validation Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn't have to be a pain. First, create a `Validator` instance with your _static rules_ that never change: - use Illuminate\Support\Facades\Validator; +```php +use Illuminate\Support\Facades\Validator; - $validator = Validator::make($request->all(), [ - 'email' => 'required|email', - 'games' => 'required|numeric', - ]); +$validator = Validator::make($request->all(), [ + 'email' => 'required|email', + 'games' => 'required|integer|min:0', +]); +``` Let's assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting games. To conditionally add this requirement, we can use the `sometimes` method on the `Validator` instance. - $validator->sometimes('reason', 'required|max:500', function ($input) { - return $input->games >= 100; - }); +```php +use Illuminate\Support\Fluent; + +$validator->sometimes('reason', 'required|max:500', function (Fluent $input) { + return $input->games >= 100; +}); +``` The first argument passed to the `sometimes` method is the name of the field we are conditionally validating. The second argument is a list of the rules we want to add. If the closure passed as the third argument returns `true`, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once: - $validator->sometimes(['reason', 'cost'], 'required', function ($input) { - return $input->games >= 100; - }); +```php +$validator->sometimes(['reason', 'cost'], 'required', function (Fluent $input) { + return $input->games >= 100; +}); +``` -> {tip} The `$input` parameter passed to your closure will be an instance of `Illuminate\Support\Fluent` and may be used to access your input and files under validation. +> [!NOTE] +> The `$input` parameter passed to your closure will be an instance of `Illuminate\Support\Fluent` and may be used to access your input and files under validation. #### Complex Conditional Array Validation Sometimes you may want to validate a field based on another field in the same nested array whose index you do not know. In these situations, you may allow your closure to receive a second argument which will be the current individual item in the array being validated: - $input = [ - 'channels' => [ - [ - 'type' => 'email', - 'address' => 'abigail@example.com', - ], - [ - 'type' => 'url', - 'address' => 'https://example.com/', - ], +```php +$input = [ + 'channels' => [ + [ + 'type' => 'email', + 'address' => 'abigail@example.com', ], - ]; + [ + 'type' => 'url', + 'address' => 'https://example.com/', + ], + ], +]; - $validator->sometimes('channels.*.address', 'email', function ($input, $item) { - return $item->type === 'email'; - }); +$validator->sometimes('channels.*.address', 'email', function (Fluent $input, Fluent $item) { + return $item->type === 'email'; +}); - $validator->sometimes('channels.*.address', 'url', function ($input, $item) { - return $item->type !== 'email'; - }); +$validator->sometimes('channels.*.address', 'url', function (Fluent $input, Fluent $item) { + return $item->type !== 'email'; +}); +``` Like the `$input` parameter passed to the closure, the `$item` parameter is an instance of `Illuminate\Support\Fluent` when the attribute data is an array; otherwise, it is a string. ## Validating Arrays -As discussed in the [`array` validation rule documentation](#rule-array), the `array` rule accepts a list of allowed array keys. If any additional keys are present within the array, validation will fail: +As discussed in the [array validation rule documentation](#rule-array), the `array` rule accepts a list of allowed array keys. If any additional keys are present within the array, validation will fail: - use Illuminate\Support\Facades\Validator; +```php +use Illuminate\Support\Facades\Validator; - $input = [ - 'user' => [ - 'name' => 'Taylor Otwell', - 'username' => 'taylorotwell', - 'admin' => true, - ], - ]; +$input = [ + 'user' => [ + 'name' => 'Taylor Otwell', + 'username' => 'taylorotwell', + 'admin' => true, + ], +]; - Validator::make($input, [ - 'user' => 'array:username,locale', - ]); +Validator::make($input, [ + 'user' => 'array:name,username', +]); +``` In general, you should always specify the array keys that are allowed to be present within your array. Otherwise, the validator's `validate` and `validated` methods will return all of the validated data, including the array and all of its keys, even if those keys were not validated by other nested array validation rules. ### Validating Nested Array Input -Validating nested array based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a `photos[profile]` field, you may validate it like so: +Validating nested array-based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a `photos[profile]` field, you may validate it like so: - use Illuminate\Support\Facades\Validator; +```php +use Illuminate\Support\Facades\Validator; - $validator = Validator::make($request->all(), [ - 'photos.profile' => 'required|image', - ]); +$validator = Validator::make($request->all(), [ + 'photos.profile' => 'required|image', +]); +``` You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following: - $validator = Validator::make($request->all(), [ - 'person.*.email' => 'email|unique:users', - 'person.*.first_name' => 'required_with:person.*.last_name', - ]); +```php +$validator = Validator::make($request->all(), [ + 'users.*.email' => 'email|unique:users', + 'users.*.first_name' => 'required_with:users.*.last_name', +]); +``` -Likewise, you may use the `*` character when specifying [custom validation messages in your language files](#custom-messages-for-specific-attributes), making it a breeze to use a single validation message for array based fields: +Likewise, you may use the `*` character when specifying [custom validation messages in your language files](#custom-messages-for-specific-attributes), making it a breeze to use a single validation message for array-based fields: - 'custom' => [ - 'person.*.email' => [ - 'unique' => 'Each person must have a unique email address', - ] - ], +```php +'custom' => [ + 'users.*.email' => [ + 'unique' => 'Each user must have a unique email address', + ] +], +``` #### Accessing Nested Array Data -Sometimes you may need to access the value for a given nested array element when assigning validation rules to the attribute. You may accomplish this using the `Rule::foreEach` method. The `forEach` method accepts a closure that will be invoked for each iteration of the array attribute under validation and will receive the attribute's value and explicit, fully-expanded attribute name. The closure should return an array of rules to assign to the array element: +Sometimes you may need to access the value for a given nested array element when assigning validation rules to the attribute. You may accomplish this using the `Rule::forEach` method. The `forEach` method accepts a closure that will be invoked for each iteration of the array attribute under validation and will receive the attribute's value and explicit, fully-expanded attribute name. The closure should return an array of rules to assign to the array element: - use App\Rules\HasPermission; - use Illuminate\Support\Facades\Validator; - use Illuminate\Validation\Rule; +```php +use App\Rules\HasPermission; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; - $validator = Validator::make($request->all(), [ - 'companies.*.id' => Rule::forEach(function ($value, $attribute) { - return [ - Rule::exists(Company::class, 'id'), - new HasPermission('manage-company', $value), - ]; - }), - ]); +$validator = Validator::make($request->all(), [ + 'companies.*.id' => Rule::forEach(function (string|null $value, string $attribute) { + return [ + Rule::exists(Company::class, 'id'), + new HasPermission('manage-company', $value), + ]; + }), +]); +``` + + +### Error Message Indexes and Positions + +When validating arrays, you may want to reference the index or position of a particular item that failed validation within the error message displayed by your application. To accomplish this, you may include the `:index` (starts from `0`), `:position` (starts from `1`), or `:ordinal-position` (starts from `1st`) placeholders within your [custom validation message](#manual-customizing-the-error-messages): + +```php +use Illuminate\Support\Facades\Validator; + +$input = [ + 'photos' => [ + [ + 'name' => 'BeachVacation.jpg', + 'description' => 'A photo of my beach vacation!', + ], + [ + 'name' => 'GrandCanyon.jpg', + 'description' => '', + ], + ], +]; + +Validator::validate($input, [ + 'photos.*.description' => 'required', +], [ + 'photos.*.description.required' => 'Please describe photo #:position.', +]); +``` + +Given the example above, validation will fail and the user will be presented with the following error of _"Please describe photo #2."_ + +If necessary, you may reference more deeply nested indexes and positions via `second-index`, `second-position`, `third-index`, `third-position`, etc. + +```php +'photos.*.attributes.*.string' => 'Invalid attribute for photo #:second-position.', +``` + + +## Validating Files + +Laravel provides a variety of validation rules that may be used to validate uploaded files, such as `mimes`, `image`, `min`, and `max`. While you are free to specify these rules individually when validating files, Laravel also offers a fluent file validation rule builder that you may find convenient: + +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rules\File; + +Validator::validate($input, [ + 'attachment' => [ + 'required', + File::types(['mp3', 'wav']) + ->min(1024) + ->max(12 * 1024), + ], +]); +``` + + +#### Validating File Types + +Even though you only need to specify the extensions when invoking the `types` method, this method actually validates the MIME type of the file by reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location: + +[https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + + +#### Validating File Sizes + +For convenience, minimum and maximum file sizes may be specified as a string with a suffix indicating the file size units. The `kb`, `mb`, `gb`, and `tb` suffixes are supported: + +```php +File::types(['mp3', 'wav']) + ->min('1kb') + ->max('10mb'); +``` + + +#### Validating Image Files + +If your application accepts images uploaded by your users, you may use the `File` rule's `image` constructor method to ensure that the file under validation is an image (jpg, jpeg, png, bmp, gif, or webp). + +In addition, the `dimensions` rule may be used to limit the dimensions of the image: + +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; +use Illuminate\Validation\Rules\File; + +Validator::validate($input, [ + 'photo' => [ + 'required', + File::image() + ->min(1024) + ->max(12 * 1024) + ->dimensions(Rule::dimensions()->maxWidth(1000)->maxHeight(500)), + ], +]); +``` + +> [!NOTE] +> More information regarding validating image dimensions may be found in the [dimension rule documentation](#rule-dimensions). + +> [!WARNING] +> By default, the `image` rule does not allow SVG files due to the possibility of XSS vulnerabilities. If you need to allow SVG files, you may pass `allowSvg: true` to the `image` rule: `File::image(allowSvg: true)`. + + +#### Validating Image Dimensions + +You may also validate the dimensions of an image. For example, to validate that an uploaded image is at least 1000 pixels wide and 500 pixels tall, you may use the `dimensions` rule: + +```php +use Illuminate\Validation\Rule; +use Illuminate\Validation\Rules\File; + +File::image()->dimensions( + Rule::dimensions() + ->maxWidth(1000) + ->maxHeight(500) +) +``` + +> [!NOTE] +> More information regarding validating image dimensions may be found in the [dimension rule documentation](#rule-dimensions). ## Validating Passwords To ensure that passwords have an adequate level of complexity, you may use Laravel's `Password` rule object: - use Illuminate\Support\Facades\Validator; - use Illuminate\Validation\Rules\Password; +```php +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rules\Password; - $validator = Validator::make($request->all(), [ - 'password' => ['required', 'confirmed', Password::min(8)], - ]); +$validator = Validator::make($request->all(), [ + 'password' => ['required', 'confirmed', Password::min(8)], +]); +``` The `Password` rule object allows you to easily customize the password complexity requirements for your application, such as specifying that passwords require at least one letter, number, symbol, or characters with mixed casing: - // Require at least 8 characters... - Password::min(8) +```php +// Require at least 8 characters... +Password::min(8) - // Require at least one letter... - Password::min(8)->letters() +// Require at least one letter... +Password::min(8)->letters() - // Require at least one uppercase and one lowercase letter... - Password::min(8)->mixedCase() +// Require at least one uppercase and one lowercase letter... +Password::min(8)->mixedCase() - // Require at least one number... - Password::min(8)->numbers() +// Require at least one number... +Password::min(8)->numbers() - // Require at least one symbol... - Password::min(8)->symbols() +// Require at least one symbol... +Password::min(8)->symbols() +``` In addition, you may ensure that a password has not been compromised in a public password data breach leak using the `uncompromised` method: - Password::min(8)->uncompromised() +```php +Password::min(8)->uncompromised() +``` Internally, the `Password` rule object uses the [k-Anonymity](https://en.wikipedia.org/wiki/K-anonymity) model to determine if a password has been leaked via the [haveibeenpwned.com](https://haveibeenpwned.com) service without sacrificing the user's privacy or security. By default, if a password appears at least once in a data leak, it will be considered compromised. You can customize this threshold using the first argument of the `uncompromised` method: - // Ensure the password appears less than 3 times in the same data leak... - Password::min(8)->uncompromised(3); +```php +// Ensure the password appears less than 3 times in the same data leak... +Password::min(8)->uncompromised(3); +``` Of course, you may chain all the methods in the examples above: - Password::min(8) - ->letters() - ->mixedCase() - ->numbers() - ->symbols() - ->uncompromised() +```php +Password::min(8) + ->letters() + ->mixedCase() + ->numbers() + ->symbols() + ->uncompromised() +``` #### Defining Default Password Rules @@ -1743,34 +2733,36 @@ use Illuminate\Validation\Rules\Password; /** * Bootstrap any application services. - * - * @return void */ -public function boot() +public function boot(): void { Password::defaults(function () { $rule = Password::min(8); return $this->app->isProduction() - ? $rule->mixedCase()->uncompromised() - : $rule; + ? $rule->mixedCase()->uncompromised() + : $rule; }); } ``` Then, when you would like to apply the default rules to a particular password undergoing validation, you may invoke the `defaults` method with no arguments: - 'password' => ['required', Password::defaults()], +```php +'password' => ['required', Password::defaults()], +``` Occasionally, you may want to attach additional validation rules to your default password validation rules. You may use the `rules` method to accomplish this: - use App\Rules\ZxcvbnRule; +```php +use App\Rules\ZxcvbnRule; - Password::defaults(function () { - $rule = Password::min(8)->rules([new ZxcvbnRule]); +Password::defaults(function () { + $rule = Password::min(8)->rules([new ZxcvbnRule]); - // ... - }); + // ... +}); +``` ## Custom Validation Rules @@ -1784,167 +2776,171 @@ Laravel provides a variety of helpful validation rules; however, you may wish to php artisan make:rule Uppercase ``` -Once the rule has been created, we are ready to define its behavior. A rule object contains two methods: `passes` and `message`. The `passes` method receives the attribute value and name, and should return `true` or `false` depending on whether the attribute value is valid or not. The `message` method should return the validation error message that should be used when validation fails: +Once the rule has been created, we are ready to define its behavior. A rule object contains a single method: `validate`. This method receives the attribute name, its value, and a callback that should be invoked on failure with the validation error message: - validate([ - 'name' => ['required', 'string', new Uppercase], - ]); +$request->validate([ + 'name' => ['required', 'string', new Uppercase], +]); +``` + +#### Translating Validation Messages + +Instead of providing a literal error message to the `$fail` closure, you may also provide a [translation string key](/docs/{{version}}/localization) and instruct Laravel to translate the error message: + +```php +if (strtoupper($value) !== $value) { + $fail('validation.uppercase')->translate(); +} +``` + +If necessary, you may provide placeholder replacements and the preferred language as the first and second arguments to the `translate` method: + +```php +$fail('validation.location')->translate([ + 'value' => $this->value, +], 'fr'); +``` #### Accessing Additional Data If your custom validation rule class needs to access all of the other data undergoing validation, your rule class may implement the `Illuminate\Contracts\Validation\DataAwareRule` interface. This interface requires your class to define a `setData` method. This method will automatically be invoked by Laravel (before validation proceeds) with all of the data under validation: - + */ + protected $data = []; - // ... + // ... - /** - * Set the data under validation. - * - * @param array $data - * @return $this - */ - public function setData($data) - { - $this->data = $data; - - return $this; - } + /** + * Set the data under validation. + * + * @param array $data + */ + public function setData(array $data): static + { + $this->data = $data; + + return $this; } +} +``` Or, if your validation rule requires access to the validator instance performing the validation, you may implement the `ValidatorAwareRule` interface: - validator = $validator; - - return $this; - } + /** + * Set the current validator. + */ + public function setValidator(Validator $validator): static + { + $this->validator = $validator; + + return $this; } +} +``` ### Using Closures If you only need the functionality of a custom rule once throughout your application, you may use a closure instead of a rule object. The closure receives the attribute's name, the attribute's value, and a `$fail` callback that should be called if validation fails: - use Illuminate\Support\Facades\Validator; - - $validator = Validator::make($request->all(), [ - 'title' => [ - 'required', - 'max:255', - function ($attribute, $value, $fail) { - if ($value === 'foo') { - $fail('The '.$attribute.' is invalid.'); - } - }, - ], - ]); +```php +use Illuminate\Support\Facades\Validator; +use Closure; + +$validator = Validator::make($request->all(), [ + 'title' => [ + 'required', + 'max:255', + function (string $attribute, mixed $value, Closure $fail) { + if ($value === 'foo') { + $fail("The {$attribute} is invalid."); + } + }, + ], +]); +``` ### Implicit Rules -By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the [`unique`](#rule-unique) rule will not be run against an empty string: - - use Illuminate\Support\Facades\Validator; +By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the [unique](#rule-unique) rule will not be run against an empty string: - $rules = ['name' => 'unique:users,name']; +```php +use Illuminate\Support\Facades\Validator; - $input = ['name' => '']; +$rules = ['name' => 'unique:users,name']; - Validator::make($input, $rules)->passes(); // true +$input = ['name' => '']; -For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create an "implicit" rule, implement the `Illuminate\Contracts\Validation\ImplicitRule` interface. This interface serves as a "marker interface" for the validator; therefore, it does not contain any additional methods you need to implement beyond the methods required by the typical `Rule` interface. +Validator::make($input, $rules)->passes(); // true +``` -To generate a new implicit rule object, you may use the `make:rule` Artisan command with the `--implicit` option : +For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To quickly generate a new implicit rule object, you may use the `make:rule` Artisan command with the `--implicit` option: ```shell php artisan make:rule Uppercase --implicit ``` -> {note} An "implicit" rule only _implies_ that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you. +> [!WARNING] +> An "implicit" rule only _implies_ that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you. diff --git a/verification.md b/verification.md index 9caf5baf084..b8d05eebbdc 100644 --- a/verification.md +++ b/verification.md @@ -6,7 +6,7 @@ - [Routing](#verification-routing) - [The Email Verification Notice](#the-email-verification-notice) - [The Email Verification Handler](#the-email-verification-handler) - - [Resending The Verification Email](#resending-the-verification-email) + - [Resending the Verification Email](#resending-the-verification-email) - [Protecting Routes](#protecting-routes) - [Customization](#customization) - [Events](#events) @@ -16,44 +16,45 @@ Many web applications require users to verify their email addresses before using the application. Rather than forcing you to re-implement this feature by hand for each application you create, Laravel provides convenient built-in services for sending and verifying email verification requests. -> {tip} Want to get started fast? Install one of the [Laravel application starter kits](/docs/{{version}}/starter-kits) in a fresh Laravel application. The starter kits will take care of scaffolding your entire authentication system, including email verification support. +> [!NOTE] +> Want to get started fast? Install one of the [Laravel application starter kits](/docs/{{version}}/starter-kits) in a fresh Laravel application. The starter kits will take care of scaffolding your entire authentication system, including email verification support. ### Model Preparation Before getting started, verify that your `App\Models\User` model implements the `Illuminate\Contracts\Auth\MustVerifyEmail` contract: - ### Database Preparation -Next, your `users` table must contain an `email_verified_at` column to store the date and time that the user's email address was verified. By default, the `users` table migration included with the Laravel framework already includes this column. So, all you need to do is run your database migrations: - -```shell -php artisan migrate -``` +Next, your `users` table must contain an `email_verified_at` column to store the date and time that the user's email address was verified. Typically, this is included in Laravel's default `0001_01_01_000000_create_users_table.php` database migration. ## Routing @@ -69,52 +70,61 @@ Third, a route will be needed to resend a verification link if the user accident As mentioned previously, a route should be defined that will return a view instructing the user to click the email verification link that was emailed to them by Laravel after registration. This view will be displayed to users when they try to access other parts of the application without verifying their email address first. Remember, the link is automatically emailed to the user as long as your `App\Models\User` model implements the `MustVerifyEmail` interface: - Route::get('/email/verify', function () { - return view('auth.verify-email'); - })->middleware('auth')->name('verification.notice'); +```php +Route::get('/email/verify', function () { + return view('auth.verify-email'); +})->middleware('auth')->name('verification.notice'); +``` The route that returns the email verification notice should be named `verification.notice`. It is important that the route is assigned this exact name since the `verified` middleware [included with Laravel](#protecting-routes) will automatically redirect to this route name if a user has not verified their email address. -> {tip} When manually implementing email verification, you are required to define the contents of the verification notice view yourself. If you would like scaffolding that includes all necessary authentication and verification views, check out the [Laravel application starter kits](/docs/{{version}}/starter-kits). +> [!NOTE] +> When manually implementing email verification, you are required to define the contents of the verification notice view yourself. If you would like scaffolding that includes all necessary authentication and verification views, check out the [Laravel application starter kits](/docs/{{version}}/starter-kits). ### The Email Verification Handler Next, we need to define a route that will handle requests generated when the user clicks the email verification link that was emailed to them. This route should be named `verification.verify` and be assigned the `auth` and `signed` middlewares: - use Illuminate\Foundation\Auth\EmailVerificationRequest; +```php +use Illuminate\Foundation\Auth\EmailVerificationRequest; - Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) { - $request->fulfill(); +Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) { + $request->fulfill(); - return redirect('/home'); - })->middleware(['auth', 'signed'])->name('verification.verify'); + return redirect('/home'); +})->middleware(['auth', 'signed'])->name('verification.verify'); +``` Before moving on, let's take a closer look at this route. First, you'll notice we are using an `EmailVerificationRequest` request type instead of the typical `Illuminate\Http\Request` instance. The `EmailVerificationRequest` is a [form request](/docs/{{version}}/validation#form-request-validation) that is included with Laravel. This request will automatically take care of validating the request's `id` and `hash` parameters. Next, we can proceed directly to calling the `fulfill` method on the request. This method will call the `markEmailAsVerified` method on the authenticated user and dispatch the `Illuminate\Auth\Events\Verified` event. The `markEmailAsVerified` method is available to the default `App\Models\User` model via the `Illuminate\Foundation\Auth\User` base class. Once the user's email address has been verified, you may redirect them wherever you wish. -### Resending The Verification Email +### Resending the Verification Email Sometimes a user may misplace or accidentally delete the email address verification email. To accommodate this, you may wish to define a route to allow the user to request that the verification email be resent. You may then make a request to this route by placing a simple form submission button within your [verification notice view](#the-email-verification-notice): - use Illuminate\Http\Request; +```php +use Illuminate\Http\Request; - Route::post('/email/verification-notification', function (Request $request) { - $request->user()->sendEmailVerificationNotification(); +Route::post('/email/verification-notification', function (Request $request) { + $request->user()->sendEmailVerificationNotification(); - return back()->with('message', 'Verification link sent!'); - })->middleware(['auth', 'throttle:6,1'])->name('verification.send'); + return back()->with('message', 'Verification link sent!'); +})->middleware(['auth', 'throttle:6,1'])->name('verification.send'); +``` ### Protecting Routes -[Route middleware](/docs/{{version}}/middleware) may be used to only allow verified users to access a given route. Laravel ships with a `verified` middleware, which references the `Illuminate\Auth\Middleware\EnsureEmailIsVerified` class. Since this middleware is already registered in your application's HTTP kernel, all you need to do is attach the middleware to a route definition: +[Route middleware](/docs/{{version}}/middleware) may be used to only allow verified users to access a given route. Laravel includes a `verified` [middleware alias](/docs/{{version}}/middleware#middleware-aliases), which is an alias for the `Illuminate\Auth\Middleware\EnsureEmailIsVerified` middleware class. Since this alias is already automatically registered by Laravel, all you need to do is attach the `verified` middleware to a route definition. Typically, this middleware is paired with the `auth` middleware: - Route::get('/profile', function () { - // Only verified users may access this route... - })->middleware('verified'); +```php +Route::get('/profile', function () { + // Only verified users may access this route... +})->middleware(['auth', 'verified']); +``` If an unverified user attempts to access a route that has been assigned this middleware, they will automatically be redirected to the `verification.notice` [named route](/docs/{{version}}/routing#named-routes). @@ -126,42 +136,32 @@ If an unverified user attempts to access a route that has been assigned this mid Although the default email verification notification should satisfy the requirements of most applications, Laravel allows you to customize how the email verification mail message is constructed. -To get started, pass a closure to the `toMailUsing` method provided by the `Illuminate\Auth\Notifications\VerifyEmail` notification. The closure will receive the notifiable model instance that is receiving the notification as well as the signed email verification URL that the user must visit to verify their email address. The closure should return an instance of `Illuminate\Notifications\Messages\MailMessage`. Typically, you should call the `toMailUsing` method from the `boot` method of your application's `App\Providers\AuthServiceProvider` class: - - use Illuminate\Auth\Notifications\VerifyEmail; - use Illuminate\Notifications\Messages\MailMessage; - - /** - * Register any authentication / authorization services. - * - * @return void - */ - public function boot() - { - // ... - - VerifyEmail::toMailUsing(function ($notifiable, $url) { - return (new MailMessage) - ->subject('Verify Email Address') - ->line('Click the button below to verify your email address.') - ->action('Verify Email Address', $url); - }); - } +To get started, pass a closure to the `toMailUsing` method provided by the `Illuminate\Auth\Notifications\VerifyEmail` notification. The closure will receive the notifiable model instance that is receiving the notification as well as the signed email verification URL that the user must visit to verify their email address. The closure should return an instance of `Illuminate\Notifications\Messages\MailMessage`. Typically, you should call the `toMailUsing` method from the `boot` method of your application's `AppServiceProvider` class: + +```php +use Illuminate\Auth\Notifications\VerifyEmail; +use Illuminate\Notifications\Messages\MailMessage; + +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + // ... + + VerifyEmail::toMailUsing(function (object $notifiable, string $url) { + return (new MailMessage) + ->subject('Verify Email Address') + ->line('Click the button below to verify your email address.') + ->action('Verify Email Address', $url); + }); +} +``` -> {tip} To learn more about mail notifications, please consult the [mail notification documentation](/docs/{{version}}/notifications#mail-notifications). +> [!NOTE] +> To learn more about mail notifications, please consult the [mail notification documentation](/docs/{{version}}/notifications#mail-notifications). ## Events -When using the [Laravel application starter kits](/docs/{{version}}/starter-kits), Laravel dispatches [events](/docs/{{version}}/events) during the email verification process. If you are manually handling email verification for your application, you may wish to manually dispatch these events after verification is completed. You may attach listeners to these events in your application's `EventServiceProvider`: - - /** - * The event listener mappings for the application. - * - * @var array - */ - protected $listen = [ - 'Illuminate\Auth\Events\Verified' => [ - 'App\Listeners\LogVerifiedUser', - ], - ]; +When using the [Laravel application starter kits](/docs/{{version}}/starter-kits), Laravel dispatches an `Illuminate\Auth\Events\Verified` [event](/docs/{{version}}/events) during the email verification process. If you are manually handling email verification for your application, you may wish to manually dispatch these events after verification is completed. diff --git a/views.md b/views.md index 68ff7b776fe..5a10f9b25d2 100644 --- a/views.md +++ b/views.md @@ -1,11 +1,12 @@ # Views - [Introduction](#introduction) -- [Creating & Rendering Views](#creating-and-rendering-views) + - [Writing Views in React / Vue](#writing-views-in-react-or-vue) +- [Creating and Rendering Views](#creating-and-rendering-views) - [Nested View Directories](#nested-view-directories) - - [Creating The First Available View](#creating-the-first-available-view) - - [Determining If A View Exists](#determining-if-a-view-exists) -- [Passing Data To Views](#passing-data-to-views) + - [Creating the First Available View](#creating-the-first-available-view) + - [Determining if a View Exists](#determining-if-a-view-exists) +- [Passing Data to Views](#passing-data-to-views) - [Sharing Data With All Views](#sharing-data-with-all-views) - [View Composers](#view-composers) - [View Creators](#view-creators) @@ -14,7 +15,9 @@ ## Introduction -Of course, it's not practical to return entire HTML documents strings directly from your routes and controllers. Thankfully, views provide a convenient way to place all of our HTML in separate files. Views separate your controller / application logic from your presentation logic and are stored in the `resources/views` directory. A simple view might look something like this: +Of course, it's not practical to return entire HTML documents strings directly from your routes and controllers. Thankfully, views provide a convenient way to place all of our HTML in separate files. + +Views separate your controller / application logic from your presentation logic and are stored in the `resources/views` directory. When using Laravel, view templates are usually written using the [Blade templating language](/docs/{{version}}/blade). A simple view might look something like this: ```blade @@ -28,28 +31,48 @@ Of course, it's not practical to return entire HTML documents strings directly f Since this view is stored at `resources/views/greeting.blade.php`, we may return it using the global `view` helper like so: - Route::get('/', function () { - return view('greeting', ['name' => 'James']); - }); +```php +Route::get('/', function () { + return view('greeting', ['name' => 'James']); +}); +``` + +> [!NOTE] +> Looking for more information on how to write Blade templates? Check out the full [Blade documentation](/docs/{{version}}/blade) to get started. + + +### Writing Views in React / Vue + +Instead of writing their frontend templates in PHP via Blade, many developers have begun to prefer to write their templates using React or Vue. Laravel makes this painless thanks to [Inertia](https://inertiajs.com/), a library that makes it a cinch to tie your React / Vue frontend to your Laravel backend without the typical complexities of building an SPA. -> {tip} Looking for more information on how to write Blade templates? Check out the full [Blade documentation](/docs/{{version}}/blade) to get started. +Our [React and Vue application starter kits](/docs/{{version}}/starter-kits) give you a great starting point for your next Laravel application powered by Inertia. -## Creating & Rendering Views +## Creating and Rendering Views + +You may create a view by placing a file with the `.blade.php` extension in your application's `resources/views` directory or by using the `make:view` Artisan command: + +```shell +php artisan make:view greeting +``` -You may create a view by placing a file with the `.blade.php` extension in your application's `resources/views` directory. The `.blade.php` extension informs the framework that the file contains a [Blade template](/docs/{{version}}/blade). Blade templates contain HTML as well as Blade directives that allow you to easily echo values, create "if" statements, iterate over data, and more. +The `.blade.php` extension informs the framework that the file contains a [Blade template](/docs/{{version}}/blade). Blade templates contain HTML as well as Blade directives that allow you to easily echo values, create "if" statements, iterate over data, and more. Once you have created a view, you may return it from one of your application's routes or controllers using the global `view` helper: - Route::get('/', function () { - return view('greeting', ['name' => 'James']); - }); +```php +Route::get('/', function () { + return view('greeting', ['name' => 'James']); +}); +``` Views may also be returned using the `View` facade: - use Illuminate\Support\Facades\View; +```php +use Illuminate\Support\Facades\View; - return View::make('greeting', ['name' => 'James']); +return View::make('greeting', ['name' => 'James']); +``` As you can see, the first argument passed to the `view` helper corresponds to the name of the view file in the `resources/views` directory. The second argument is an array of data that should be made available to the view. In this case, we are passing the `name` variable, which is displayed in the view using [Blade syntax](/docs/{{version}}/blade). @@ -58,198 +81,205 @@ As you can see, the first argument passed to the `view` helper corresponds to th Views may also be nested within subdirectories of the `resources/views` directory. "Dot" notation may be used to reference nested views. For example, if your view is stored at `resources/views/admin/profile.blade.php`, you may return it from one of your application's routes / controllers like so: - return view('admin.profile', $data); +```php +return view('admin.profile', $data); +``` -> {note} View directory names should not contain the `.` character. +> [!WARNING] +> View directory names should not contain the `.` character. -### Creating The First Available View +### Creating the First Available View Using the `View` facade's `first` method, you may create the first view that exists in a given array of views. This may be useful if your application or package allows views to be customized or overwritten: - use Illuminate\Support\Facades\View; +```php +use Illuminate\Support\Facades\View; - return View::first(['custom.admin', 'admin'], $data); +return View::first(['custom.admin', 'admin'], $data); +``` -### Determining If A View Exists +### Determining if a View Exists If you need to determine if a view exists, you may use the `View` facade. The `exists` method will return `true` if the view exists: - use Illuminate\Support\Facades\View; +```php +use Illuminate\Support\Facades\View; - if (View::exists('emails.customer')) { - // - } +if (View::exists('admin.profile')) { + // ... +} +``` -## Passing Data To Views +## Passing Data to Views As you saw in the previous examples, you may pass an array of data to views to make that data available to the view: - return view('greetings', ['name' => 'Victoria']); +```php +return view('greetings', ['name' => 'Victoria']); +``` When passing information in this manner, the data should be an array with key / value pairs. After providing data to a view, you can then access each value within your view using the data's keys, such as ``. As an alternative to passing a complete array of data to the `view` helper function, you may use the `with` method to add individual pieces of data to the view. The `with` method returns an instance of the view object so that you can continue chaining methods before returning the view: - return view('greeting') - ->with('name', 'Victoria') - ->with('occupation', 'Astronaut'); +```php +return view('greeting') + ->with('name', 'Victoria') + ->with('occupation', 'Astronaut'); +``` ### Sharing Data With All Views Occasionally, you may need to share data with all views that are rendered by your application. You may do so using the `View` facade's `share` method. Typically, you should place calls to the `share` method within a service provider's `boot` method. You are free to add them to the `App\Providers\AppServiceProvider` class or generate a separate service provider to house them: - ## View Composers View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location. View composers may prove particularly useful if the same view is returned by multiple routes or controllers within your application and always needs a particular piece of data. -Typically, view composers will be registered within one of your application's [service providers](/docs/{{version}}/providers). In this example, we'll assume that we have created a new `App\Providers\ViewServiceProvider` to house this logic. +Typically, view composers will be registered within one of your application's [service providers](/docs/{{version}}/providers). In this example, we'll assume that the `App\Providers\AppServiceProvider` will house this logic. -We'll use the `View` facade's `composer` method to register the view composer. Laravel does not include a default directory for class based view composers, so you are free to organize them however you wish. For example, you could create an `app/View/Composers` directory to house all of your application's view composers: +We'll use the `View` facade's `composer` method to register the view composer. Laravel does not include a default directory for class-based view composers, so you are free to organize them however you wish. For example, you could create an `app/View/Composers` directory to house all of your application's view composers: - {note} Remember, if you create a new service provider to contain your view composer registrations, you will need to add the service provider to the `providers` array in the `config/app.php` configuration file. + /** + * Bootstrap any application services. + */ + public function boot(): void + { + // Using class-based composers... + Facades\View::composer('profile', ProfileComposer::class); + + // Using closure-based composers... + Facades\View::composer('welcome', function (View $view) { + // ... + }); + + Facades\View::composer('dashboard', function (View $view) { + // ... + }); + } +} +``` Now that we have registered the composer, the `compose` method of the `App\View\Composers\ProfileComposer` class will be executed each time the `profile` view is being rendered. Let's take a look at an example of the composer class: - users = $users; - } - - /** - * Bind data to the view. - * - * @param \Illuminate\View\View $view - * @return void - */ - public function compose(View $view) - { - $view->with('count', $this->users->count()); - } + $view->with('count', $this->users->count()); } +} +``` As you can see, all view composers are resolved via the [service container](/docs/{{version}}/container), so you may type-hint any dependencies you need within a composer's constructor. -#### Attaching A Composer To Multiple Views +#### Attaching a Composer to Multiple Views You may attach a view composer to multiple views at once by passing an array of views as the first argument to the `composer` method: - use App\Views\Composers\MultiComposer; +```php +use App\Views\Composers\MultiComposer; +use Illuminate\Support\Facades\View; - View::composer( - ['profile', 'dashboard'], - MultiComposer::class - ); +View::composer( + ['profile', 'dashboard'], + MultiComposer::class +); +``` The `composer` method also accepts the `*` character as a wildcard, allowing you to attach a composer to all views: - View::composer('*', function ($view) { - // - }); +```php +use Illuminate\Support\Facades; +use Illuminate\View\View; + +Facades\View::composer('*', function (View $view) { + // ... +}); +``` ### View Creators View "creators" are very similar to view composers; however, they are executed immediately after the view is instantiated instead of waiting until the view is about to render. To register a view creator, use the `creator` method: - use App\View\Creators\ProfileCreator; - use Illuminate\Support\Facades\View; +```php +use App\View\Creators\ProfileCreator; +use Illuminate\Support\Facades\View; - View::creator('profile', ProfileCreator::class); +View::creator('profile', ProfileCreator::class); +``` ## Optimizing Views @@ -267,4 +297,3 @@ You may use the `view:clear` command to clear the view cache: ```shell php artisan view:clear ``` - diff --git a/vite.md b/vite.md new file mode 100644 index 00000000000..805092d3b22 --- /dev/null +++ b/vite.md @@ -0,0 +1,1018 @@ +# Asset Bundling (Vite) + +- [Introduction](#introduction) +- [Installation & Setup](#installation) + - [Installing Node](#installing-node) + - [Installing Vite and the Laravel Plugin](#installing-vite-and-laravel-plugin) + - [Configuring Vite](#configuring-vite) + - [Loading Your Scripts and Styles](#loading-your-scripts-and-styles) +- [Running Vite](#running-vite) +- [Working With JavaScript](#working-with-scripts) + - [Aliases](#aliases) + - [Vue](#vue) + - [React](#react) + - [Inertia](#inertia) + - [URL Processing](#url-processing) +- [Working With Stylesheets](#working-with-stylesheets) +- [Working With Blade and Routes](#working-with-blade-and-routes) + - [Processing Static Assets With Vite](#blade-processing-static-assets) + - [Refreshing on Save](#blade-refreshing-on-save) + - [Aliases](#blade-aliases) +- [Asset Prefetching](#asset-prefetching) +- [Custom Base URLs](#custom-base-urls) +- [Environment Variables](#environment-variables) +- [Disabling Vite in Tests](#disabling-vite-in-tests) +- [Server-Side Rendering (SSR)](#ssr) +- [Script and Style Tag Attributes](#script-and-style-attributes) + - [Content Security Policy (CSP) Nonce](#content-security-policy-csp-nonce) + - [Subresource Integrity (SRI)](#subresource-integrity-sri) + - [Arbitrary Attributes](#arbitrary-attributes) +- [Advanced Customization](#advanced-customization) + - [Dev Server Cross-Origin Resource Sharing (CORS)](#cors) + - [Correcting Dev Server URLs](#correcting-dev-server-urls) + + +## Introduction + +[Vite](https://vitejs.dev) is a modern frontend build tool that provides an extremely fast development environment and bundles your code for production. When building applications with Laravel, you will typically use Vite to bundle your application's CSS and JavaScript files into production-ready assets. + +Laravel integrates seamlessly with Vite by providing an official plugin and Blade directive to load your assets for development and production. + + +## Installation & Setup + +> [!NOTE] +> The following documentation discusses how to manually install and configure the Laravel Vite plugin. However, Laravel's [starter kits](/docs/{{version}}/starter-kits) already include all of this scaffolding and are the fastest way to get started with Laravel and Vite. + + +### Installing Node + +You must ensure that Node.js (16+) and NPM are installed before running Vite and the Laravel plugin: + +```shell +node -v +npm -v +``` + +You can easily install the latest version of Node and NPM using simple graphical installers from [the official Node website](https://nodejs.org/en/download/). Or, if you are using [Laravel Sail](https://laravel.com/docs/{{version}}/sail), you may invoke Node and NPM through Sail: + +```shell +./vendor/bin/sail node -v +./vendor/bin/sail npm -v +``` + + +### Installing Vite and the Laravel Plugin + +Within a fresh installation of Laravel, you will find a `package.json` file in the root of your application's directory structure. The default `package.json` file already includes everything you need to get started using Vite and the Laravel plugin. You may install your application's frontend dependencies via NPM: + +```shell +npm install +``` + + +### Configuring Vite + +Vite is configured via a `vite.config.js` file in the root of your project. You are free to customize this file based on your needs, and you may also install any other plugins your application requires, such as `@vitejs/plugin-vue` or `@vitejs/plugin-react`. + +The Laravel Vite plugin requires you to specify the entry points for your application. These may be JavaScript or CSS files, and include preprocessed languages such as TypeScript, JSX, TSX, and Sass. + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel([ + 'resources/css/app.css', + 'resources/js/app.js', + ]), + ], +}); +``` + +If you are building an SPA, including applications built using Inertia, Vite works best without CSS entry points: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel([ + 'resources/css/app.css', // [tl! remove] + 'resources/js/app.js', + ]), + ], +}); +``` + +Instead, you should import your CSS via JavaScript. Typically, this would be done in your application's `resources/js/app.js` file: + +```js +import './bootstrap'; +import '../css/app.css'; // [tl! add] +``` + +The Laravel plugin also supports multiple entry points and advanced configuration options such as [SSR entry points](#ssr). + + +#### Working With a Secure Development Server + +If your local development web server is serving your application via HTTPS, you may run into issues connecting to the Vite development server. + +If you are using [Laravel Herd](https://herd.laravel.com) and have secured the site or you are using [Laravel Valet](/docs/{{version}}/valet) and have run the [secure command](/docs/{{version}}/valet#securing-sites) against your application, the Laravel Vite plugin will automatically detect and use the generated TLS certificate for you. + +If you secured the site using a host that does not match the application's directory name, you may manually specify the host in your application's `vite.config.js` file: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel({ + // ... + detectTls: 'my-app.test', // [tl! add] + }), + ], +}); +``` + +When using another web server, you should generate a trusted certificate and manually configure Vite to use the generated certificates: + +```js +// ... +import fs from 'fs'; // [tl! add] + +const host = 'my-app.test'; // [tl! add] + +export default defineConfig({ + // ... + server: { // [tl! add] + host, // [tl! add] + hmr: { host }, // [tl! add] + https: { // [tl! add] + key: fs.readFileSync(`/path/to/${host}.key`), // [tl! add] + cert: fs.readFileSync(`/path/to/${host}.crt`), // [tl! add] + }, // [tl! add] + }, // [tl! add] +}); +``` + +If you are unable to generate a trusted certificate for your system, you may install and configure the [@vitejs/plugin-basic-ssl plugin](https://github.com/vitejs/vite-plugin-basic-ssl). When using untrusted certificates, you will need to accept the certificate warning for Vite's development server in your browser by following the "Local" link in your console when running the `npm run dev` command. + + +#### Running the Development Server in Sail on WSL2 + +When running the Vite development server within [Laravel Sail](/docs/{{version}}/sail) on Windows Subsystem for Linux 2 (WSL2), you should add the following configuration to your `vite.config.js` file to ensure the browser can communicate with the development server: + +```js +// ... + +export default defineConfig({ + // ... + server: { // [tl! add:start] + hmr: { + host: 'localhost', + }, + }, // [tl! add:end] +}); +``` + +If your file changes are not being reflected in the browser while the development server is running, you may also need to configure Vite's [server.watch.usePolling option](https://vitejs.dev/config/server-options.html#server-watch). + + +### Loading Your Scripts and Styles + +With your Vite entry points configured, you may now reference them in a `@vite()` Blade directive that you add to the `` of your application's root template: + +```blade + + + {{-- ... --}} + + @vite(['resources/css/app.css', 'resources/js/app.js']) + +``` + +If you're importing your CSS via JavaScript, you only need to include the JavaScript entry point: + +```blade + + + {{-- ... --}} + + @vite('resources/js/app.js') + +``` + +The `@vite` directive will automatically detect the Vite development server and inject the Vite client to enable Hot Module Replacement. In build mode, the directive will load your compiled and versioned assets, including any imported CSS. + +If needed, you may also specify the build path of your compiled assets when invoking the `@vite` directive: + +```blade + + + {{-- Given build path is relative to public path. --}} + + @vite('resources/js/app.js', 'vendor/courier/build') + +``` + + +#### Inline Assets + +Sometimes it may be necessary to include the raw content of assets rather than linking to the versioned URL of the asset. For example, you may need to include asset content directly into your page when passing HTML content to a PDF generator. You may output the content of Vite assets using the `content` method provided by the `Vite` facade: + +```blade +@use('Illuminate\Support\Facades\Vite') + + + + {{-- ... --}} + + + + +``` + + +## Running Vite + +There are two ways you can run Vite. You may run the development server via the `dev` command, which is useful while developing locally. The development server will automatically detect changes to your files and instantly reflect them in any open browser windows. + +Or, running the `build` command will version and bundle your application's assets and get them ready for you to deploy to production: + +```shell +# Run the Vite development server... +npm run dev + +# Build and version the assets for production... +npm run build +``` + +If you are running the development server in [Sail](/docs/{{version}}/sail) on WSL2, you may need some [additional configuration](#configuring-hmr-in-sail-on-wsl2) options. + + +## Working With JavaScript + + +### Aliases + +By default, The Laravel plugin provides a common alias to help you hit the ground running and conveniently import your application's assets: + +```js +{ + '@' => '/resources/js' +} +``` + +You may overwrite the `'@'` alias by adding your own to the `vite.config.js` configuration file: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel(['resources/ts/app.tsx']), + ], + resolve: { + alias: { + '@': '/resources/ts', + }, + }, +}); +``` + + +### Vue + +If you would like to build your frontend using the [Vue](https://vuejs.org/) framework, then you will also need to install the `@vitejs/plugin-vue` plugin: + +```shell +npm install --save-dev @vitejs/plugin-vue +``` + +You may then include the plugin in your `vite.config.js` configuration file. There are a few additional options you will need when using the Vue plugin with Laravel: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; +import vue from '@vitejs/plugin-vue'; + +export default defineConfig({ + plugins: [ + laravel(['resources/js/app.js']), + vue({ + template: { + transformAssetUrls: { + // The Vue plugin will re-write asset URLs, when referenced + // in Single File Components, to point to the Laravel web + // server. Setting this to `null` allows the Laravel plugin + // to instead re-write asset URLs to point to the Vite + // server instead. + base: null, + + // The Vue plugin will parse absolute URLs and treat them + // as absolute paths to files on disk. Setting this to + // `false` will leave absolute URLs un-touched so they can + // reference assets in the public directory as expected. + includeAbsolute: false, + }, + }, + }), + ], +}); +``` + +> [!NOTE] +> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Vue, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Vue, and Vite. + + +### React + +If you would like to build your frontend using the [React](https://reactjs.org/) framework, then you will also need to install the `@vitejs/plugin-react` plugin: + +```shell +npm install --save-dev @vitejs/plugin-react +``` + +You may then include the plugin in your `vite.config.js` configuration file: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; +import react from '@vitejs/plugin-react'; + +export default defineConfig({ + plugins: [ + laravel(['resources/js/app.jsx']), + react(), + ], +}); +``` + +You will need to ensure that any files containing JSX have a `.jsx` or `.tsx` extension, remembering to update your entry point, if required, as [shown above](#configuring-vite). + +You will also need to include the additional `@viteReactRefresh` Blade directive alongside your existing `@vite` directive. + +```blade +@viteReactRefresh +@vite('resources/js/app.jsx') +``` + +The `@viteReactRefresh` directive must be called before the `@vite` directive. + +> [!NOTE] +> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, React, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, React, and Vite. + + +### Inertia + +The Laravel Vite plugin provides a convenient `resolvePageComponent` function to help you resolve your Inertia page components. Below is an example of the helper in use with Vue 3; however, you may also utilize the function in other frameworks such as React: + +```js +import { createApp, h } from 'vue'; +import { createInertiaApp } from '@inertiajs/vue3'; +import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'; + +createInertiaApp({ + resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')), + setup({ el, App, props, plugin }) { + createApp({ render: () => h(App, props) }) + .use(plugin) + .mount(el) + }, +}); +``` + +If you are using Vite's code splitting feature with Inertia, we recommend configuring [asset prefetching](#asset-prefetching). + +> [!NOTE] +> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Inertia, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Inertia, and Vite. + + +### URL Processing + +When using Vite and referencing assets in your application's HTML, CSS, or JS, there are a couple of caveats to consider. First, if you reference assets with an absolute path, Vite will not include the asset in the build; therefore, you should ensure that the asset is available in your public directory. You should avoid using absolute paths when using a [dedicated CSS entrypoint](#configuring-vite) because, during development, browsers will try to load these paths from the Vite development server, where the CSS is hosted, rather than from your public directory. + +When referencing relative asset paths, you should remember that the paths are relative to the file where they are referenced. Any assets referenced via a relative path will be re-written, versioned, and bundled by Vite. + +Consider the following project structure: + +```text +public/ + taylor.png +resources/ + js/ + Pages/ + Welcome.vue + images/ + abigail.png +``` + +The following example demonstrates how Vite will treat relative and absolute URLs: + +```html + + + + + +``` + + +## Working With Stylesheets + +> [!NOTE] +> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Tailwind and Vite configuration. Or, if you would like to use Tailwind and Laravel without using one of our starter kits, check out [Tailwind's installation guide for Laravel](https://tailwindcss.com/docs/guides/laravel). + +All Laravel applications already include Tailwind and a properly configured `vite.config.js` file. So, you only need to start the Vite development server or run the `dev` Composer command, which will start both the Laravel and Vite development servers: + +```shell +composer run dev +``` + +Your application's CSS may be placed within the `resources/css/app.css` file. + + +## Working With Blade and Routes + + +### Processing Static Assets With Vite + +When referencing assets in your JavaScript or CSS, Vite automatically processes and versions them. In addition, when building Blade based applications, Vite can also process and version static assets that you reference solely in Blade templates. + +However, in order to accomplish this, you need to make Vite aware of your assets by importing the static assets into the application's entry point. For example, if you want to process and version all images stored in `resources/images` and all fonts stored in `resources/fonts`, you should add the following in your application's `resources/js/app.js` entry point: + +```js +import.meta.glob([ + '../images/**', + '../fonts/**', +]); +``` + +These assets will now be processed by Vite when running `npm run build`. You can then reference these assets in Blade templates using the `Vite::asset` method, which will return the versioned URL for a given asset: + +```blade + +``` + + +### Refreshing on Save + +When your application is built using traditional server-side rendering with Blade, Vite can improve your development workflow by automatically refreshing the browser when you make changes to view files in your application. To get started, you can simply specify the `refresh` option as `true`. + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel({ + // ... + refresh: true, + }), + ], +}); +``` + +When the `refresh` option is `true`, saving files in the following directories will trigger the browser to perform a full page refresh while you are running `npm run dev`: + +- `app/Livewire/**` +- `app/View/Components/**` +- `lang/**` +- `resources/lang/**` +- `resources/views/**` +- `routes/**` + +Watching the `routes/**` directory is useful if you are utilizing [Ziggy](https://github.com/tighten/ziggy) to generate route links within your application's frontend. + +If these default paths do not suit your needs, you can specify your own list of paths to watch: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel({ + // ... + refresh: ['resources/views/**'], + }), + ], +}); +``` + +Under the hood, the Laravel Vite plugin uses the [vite-plugin-full-reload](https://github.com/ElMassimo/vite-plugin-full-reload) package, which offers some advanced configuration options to fine-tune this feature's behavior. If you need this level of customization, you may provide a `config` definition: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel({ + // ... + refresh: [{ + paths: ['path/to/watch/**'], + config: { delay: 300 } + }], + }), + ], +}); +``` + + +### Aliases + +It is common in JavaScript applications to [create aliases](#aliases) to regularly referenced directories. But, you may also create aliases to use in Blade by using the `macro` method on the `Illuminate\Support\Facades\Vite` class. Typically, "macros" should be defined within the `boot` method of a [service provider](/docs/{{version}}/providers): + +```php +/** + * Bootstrap any application services. + */ +public function boot(): void +{ + Vite::macro('image', fn (string $asset) => $this->asset("resources/images/{$asset}")); +} +``` + +Once a macro has been defined, it can be invoked within your templates. For example, we can use the `image` macro defined above to reference an asset located at `resources/images/logo.png`: + +```blade +Laravel Logo +``` + + +## Asset Prefetching + +When building an SPA using Vite's code splitting feature, required assets are fetched on each page navigation. This behavior can lead to delayed UI rendering. If this is a problem for your frontend framework of choice, Laravel offers the ability to eagerly prefetch your application's JavaScript and CSS assets on initial page load. + +You can instruct Laravel to eagerly prefetch your assets by invoking the `Vite::prefetch` method in the `boot` method of a [service provider](/docs/{{version}}/providers): + +```php + + addEventListener('load', () => setTimeout(() => { + dispatchEvent(new Event('vite:prefetch')) + }, 3000)) + +``` + + +## Custom Base URLs + +If your Vite compiled assets are deployed to a domain separate from your application, such as via a CDN, you must specify the `ASSET_URL` environment variable within your application's `.env` file: + +```env +ASSET_URL=https://cdn.example.com +``` + +After configuring the asset URL, all re-written URLs to your assets will be prefixed with the configured value: + +```text +https://cdn.example.com/build/assets/app.9dce8d17.js +``` + +Remember that [absolute URLs are not re-written by Vite](#url-processing), so they will not be prefixed. + + +## Environment Variables + +You may inject environment variables into your JavaScript by prefixing them with `VITE_` in your application's `.env` file: + +```env +VITE_SENTRY_DSN_PUBLIC=http://example.com +``` + +You may access injected environment variables via the `import.meta.env` object: + +```js +import.meta.env.VITE_SENTRY_DSN_PUBLIC +``` + + +## Disabling Vite in Tests + +Laravel's Vite integration will attempt to resolve your assets while running your tests, which requires you to either run the Vite development server or build your assets. + +If you would prefer to mock Vite during testing, you may call the `withoutVite` method, which is available for any tests that extend Laravel's `TestCase` class: + +```php tab=Pest +test('without vite example', function () { + $this->withoutVite(); + + // ... +}); +``` + +```php tab=PHPUnit +use Tests\TestCase; + +class ExampleTest extends TestCase +{ + public function test_without_vite_example(): void + { + $this->withoutVite(); + + // ... + } +} +``` + +If you would like to disable Vite for all tests, you may call the `withoutVite` method from the `setUp` method on your base `TestCase` class: + +```php +withoutVite(); + }// [tl! add:end] +} +``` + + +## Server-Side Rendering (SSR) + +The Laravel Vite plugin makes it painless to set up server-side rendering with Vite. To get started, create an SSR entry point at `resources/js/ssr.js` and specify the entry point by passing a configuration option to the Laravel plugin: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel({ + input: 'resources/js/app.js', + ssr: 'resources/js/ssr.js', + }), + ], +}); +``` + +To ensure you don't forget to rebuild the SSR entry point, we recommend augmenting the "build" script in your application's `package.json` to create your SSR build: + +```json +"scripts": { + "dev": "vite", + "build": "vite build" // [tl! remove] + "build": "vite build && vite build --ssr" // [tl! add] +} +``` + +Then, to build and start the SSR server, you may run the following commands: + +```shell +npm run build +node bootstrap/ssr/ssr.js +``` + +If you are using [SSR with Inertia](https://inertiajs.com/server-side-rendering), you may instead use the `inertia:start-ssr` Artisan command to start the SSR server: + +```shell +php artisan inertia:start-ssr +``` + +> [!NOTE] +> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Inertia SSR, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Inertia SSR, and Vite. + + +## Script and Style Tag Attributes + + +### Content Security Policy (CSP) Nonce + +If you wish to include a [nonce attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) on your script and style tags as part of your [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), you may generate or specify a nonce using the `useCspNonce` method within a custom [middleware](/docs/{{version}}/middleware): + +```php +withHeaders([ + 'Content-Security-Policy' => "script-src 'nonce-".Vite::cspNonce()."'", + ]); + } +} +``` + +After invoking the `useCspNonce` method, Laravel will automatically include the `nonce` attributes on all generated script and style tags. + +If you need to specify the nonce elsewhere, including the [Ziggy `@route` directive](https://github.com/tighten/ziggy#using-routes-with-a-content-security-policy) included with Laravel's [starter kits](/docs/{{version}}/starter-kits), you may retrieve it using the `cspNonce` method: + +```blade +@routes(nonce: Vite::cspNonce()) +``` + +If you already have a nonce that you would like to instruct Laravel to use, you may pass the nonce to the `useCspNonce` method: + +```php +Vite::useCspNonce($nonce); +``` + + +### Subresource Integrity (SRI) + +If your Vite manifest includes `integrity` hashes for your assets, Laravel will automatically add the `integrity` attribute on any script and style tags it generates in order to enforce [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). By default, Vite does not include the `integrity` hash in its manifest, but you may enable it by installing the [vite-plugin-manifest-sri](https://www.npmjs.com/package/vite-plugin-manifest-sri) NPM plugin: + +```shell +npm install --save-dev vite-plugin-manifest-sri +``` + +You may then enable this plugin in your `vite.config.js` file: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; +import manifestSRI from 'vite-plugin-manifest-sri';// [tl! add] + +export default defineConfig({ + plugins: [ + laravel({ + // ... + }), + manifestSRI(),// [tl! add] + ], +}); +``` + +If required, you may also customize the manifest key where the integrity hash can be found: + +```php +use Illuminate\Support\Facades\Vite; + +Vite::useIntegrityKey('custom-integrity-key'); +``` + +If you would like to disable this auto-detection completely, you may pass `false` to the `useIntegrityKey` method: + +```php +Vite::useIntegrityKey(false); +``` + + +### Arbitrary Attributes + +If you need to include additional attributes on your script and style tags, such as the [data-turbo-track](https://turbo.hotwired.dev/handbook/drive#reloading-when-assets-change) attribute, you may specify them via the `useScriptTagAttributes` and `useStyleTagAttributes` methods. Typically, this methods should be invoked from a [service provider](/docs/{{version}}/providers): + +```php +use Illuminate\Support\Facades\Vite; + +Vite::useScriptTagAttributes([ + 'data-turbo-track' => 'reload', // Specify a value for the attribute... + 'async' => true, // Specify an attribute without a value... + 'integrity' => false, // Exclude an attribute that would otherwise be included... +]); + +Vite::useStyleTagAttributes([ + 'data-turbo-track' => 'reload', +]); +``` + +If you need to conditionally add attributes, you may pass a callback that will receive the asset source path, its URL, its manifest chunk, and the entire manifest: + +```php +use Illuminate\Support\Facades\Vite; + +Vite::useScriptTagAttributes(fn (string $src, string $url, array|null $chunk, array|null $manifest) => [ + 'data-turbo-track' => $src === 'resources/js/app.js' ? 'reload' : false, +]); + +Vite::useStyleTagAttributes(fn (string $src, string $url, array|null $chunk, array|null $manifest) => [ + 'data-turbo-track' => $chunk && $chunk['isEntry'] ? 'reload' : false, +]); +``` + +> [!WARNING] +> The `$chunk` and `$manifest` arguments will be `null` while the Vite development server is running. + + +## Advanced Customization + +Out of the box, Laravel's Vite plugin uses sensible conventions that should work for the majority of applications; however, sometimes you may need to customize Vite's behavior. To enable additional customization options, we offer the following methods and options which can be used in place of the `@vite` Blade directive: + +```blade + + + {{-- ... --}} + + {{ + Vite::useHotFile(storage_path('vite.hot')) // Customize the "hot" file... + ->useBuildDirectory('bundle') // Customize the build directory... + ->useManifestFilename('assets.json') // Customize the manifest filename... + ->withEntryPoints(['resources/js/app.js']) // Specify the entry points... + ->createAssetPathsUsing(function (string $path, ?bool $secure) { // Customize the backend path generation for built assets... + return "https://cdn.example.com/%7B$path%7D"; + }) + }} + +``` + +Within the `vite.config.js` file, you should then specify the same configuration: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel({ + hotFile: 'storage/vite.hot', // Customize the "hot" file... + buildDirectory: 'bundle', // Customize the build directory... + input: ['resources/js/app.js'], // Specify the entry points... + }), + ], + build: { + manifest: 'assets.json', // Customize the manifest filename... + }, +}); +``` + + +### Dev Server Cross-Origin Resource Sharing (CORS) + +If you are experiencing Cross-Origin Resource Sharing (CORS) issues in the browser while fetching assets from the Vite dev server, you may need to grant your custom origin access to the dev server. Vite combined with the Laravel plugin allows the following origins without any additional configuration: + +- `::1` +- `127.0.0.1` +- `localhost` +- `*.test` +- `*.localhost` +- `APP_URL` in the project's `.env` + +The easiest way to allow a custom origin for your project is to ensure that your application's `APP_URL` environment variable matches the origin you are visiting in your browser. For example, if you visiting `https://my-app.laravel`, you should update your `.env` to match: + +```env +APP_URL=https://my-app.laravel +``` + +If you need more fine-grained control over the origins, such as supporting multiple origins, you should utilize [Vite's comprehensive and flexible built-in CORS server configuration](https://vite.dev/config/server-options.html#server-cors). For example, you may specify multiple origins in the `server.cors.origin` configuration option in the project's `vite.config.js` file: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel({ + input: 'resources/js/app.js', + refresh: true, + }), + ], + server: { // [tl! add] + cors: { // [tl! add] + origin: [ // [tl! add] + 'https://backend.laravel/', // [tl! add] + 'http://admin.laravel:8566/', // [tl! add] + ], // [tl! add] + }, // [tl! add] + }, // [tl! add] +}); +``` + +You may also include regex patterns, which can be helpful if you would like to allow all origins for a given top-level domain, such as `*.laravel`: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; + +export default defineConfig({ + plugins: [ + laravel({ + input: 'resources/js/app.js', + refresh: true, + }), + ], + server: { // [tl! add] + cors: { // [tl! add] + origin: [ // [tl! add] + // Supports: SCHEME://DOMAIN.laravel[:PORT] [tl! add] + /^https?:\/\/.*\.laravel(:\d+)?$/, //[tl! add] + ], // [tl! add] + }, // [tl! add] + }, // [tl! add] +}); +``` + + +### Correcting Dev Server URLs + +Some plugins within the Vite ecosystem assume that URLs which begin with a forward-slash will always point to the Vite dev server. However, due to the nature of the Laravel integration, this is not the case. + +For example, the `vite-imagetools` plugin outputs URLs like the following while Vite is serving your assets: + +```html + +``` + +The `vite-imagetools` plugin is expecting that the output URL will be intercepted by Vite and the plugin may then handle all URLs that start with `/@imagetools`. If you are using plugins that are expecting this behavior, you will need to manually correct the URLs. You can do this in your `vite.config.js` file by using the `transformOnServe` option. + +In this particular example, we will prepend the dev server URL to all occurrences of `/@imagetools` within the generated code: + +```js +import { defineConfig } from 'vite'; +import laravel from 'laravel-vite-plugin'; +import { imagetools } from 'vite-imagetools'; + +export default defineConfig({ + plugins: [ + laravel({ + // ... + transformOnServe: (code, devServerUrl) => code.replaceAll('/@imagetools', devServerUrl+'/@imagetools'), + }), + imagetools(), + ], +}); +``` + +Now, while Vite is serving Assets, it will output URLs that point to the Vite dev server: + +```html +- ++ +```