id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
243002
# Views - [Introduction](#introduction) - [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) - [Sharing Data With All Views](#sharing-data-with-all-views) - [View Composers](#view-composers) - [View Creators](#view-creators) - [Optimizing Views](#optimizing-views) <a name="introduction"></a> ## 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. 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 <!-- View stored in resources/views/greeting.blade.php --> <html> <body> <h1>Hello, {{ $name }}</h1> </body> </html> ``` 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']); }); > [!NOTE] > Looking for more information on how to write Blade templates? Check out the full [Blade documentation](/docs/{{version}}/blade) to get started. <a name="writing-views-in-react-or-vue"></a> ### 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. Our Breeze and Jetstream [starter kits](/docs/{{version}}/starter-kits) give you a great starting point for your next Laravel application powered by Inertia. In addition, the [Laravel Bootcamp](https://bootcamp.laravel.com) provides a full demonstration of building a Laravel application powered by Inertia, including examples in Vue and React. <a name="creating-and-rendering-views"></a> ## 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 ``` 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']); }); Views may also be returned using the `View` facade: use Illuminate\Support\Facades\View; 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). <a name="nested-view-directories"></a> ### Nested View Directories 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); > [!WARNING] > View directory names should not contain the `.` character. <a name="creating-the-first-available-view"></a> ### 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; return View::first(['custom.admin', 'admin'], $data); <a name="determining-if-a-view-exists"></a> ### 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; if (View::exists('admin.profile')) { // ... } <a name="passing-data-to-views"></a> ## 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']); 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 `<?php echo $name; ?>`. 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'); <a name="sharing-data-with-all-views"></a> ### 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: <?php namespace App\Providers; use Illuminate\Support\Facades\View; class AppServiceProvider extends ServiceProvider { /** * Register any application services. */ public function register(): void { // ... } /** * Bootstrap any application services. */ public function boot(): void { View::share('key', 'value'); } } <a name="view-composers"></a>
243004
# Middleware - [Introduction](#introduction) - [Defining Middleware](#defining-middleware) - [Registering Middleware](#registering-middleware) - [Global Middleware](#global-middleware) - [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) <a name="introduction"></a> ## Introduction 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. 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. <a name="defining-middleware"></a> ## Defining Middleware To create a new middleware, use the `make:middleware` Artisan command: ```shell 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: <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class EnsureTokenIsValid { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { 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. > [!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. <a name="middleware-and-responses"></a> #### 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: <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class BeforeMiddleware { public function handle(Request $request, Closure $next): Response { // Perform action return $next($request); } } However, this middleware would perform its task **after** the request is handled by the application: <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class AfterMiddleware { public function handle(Request $request, Closure $next): Response { $response = $next($request); // Perform action return $response; } } <a name="registering-middleware"></a>
243005
## Registering Middleware <a name="global-middleware"></a> ### Global Middleware 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: use App\Http\Middleware\EnsureTokenIsValid; ->withMiddleware(function (Middleware $middleware) { $middleware->append(EnsureTokenIsValid::class); }) 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. <a name="manually-managing-laravels-default-global-middleware"></a> #### 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: ->withMiddleware(function (Middleware $middleware) { $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, ]); }) <a name="assigning-middleware-to-routes"></a> ### Assigning Middleware to Routes If you would like to assign middleware to specific routes, you may invoke the `middleware` method when defining the route: use App\Http\Middleware\EnsureTokenIsValid; Route::get('/profile', function () { // ... })->middleware(EnsureTokenIsValid::class); You may assign multiple middleware to the route by passing an array of middleware names to the `middleware` method: Route::get('/', function () { // ... })->middleware([First::class, Second::class]); <a name="excluding-middleware"></a> #### 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 () { // ... }); 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; 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). <a name="middleware-groups"></a> ### 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 `appendToGroup` method within your application's `bootstrap/app.php` file: use App\Http\Middleware\First; use App\Http\Middleware\Second; ->withMiddleware(function (Middleware $middleware) { $middleware->appendToGroup('group-name', [ First::class, Second::class, ]); $middleware->prependToGroup('group-name', [ First::class, Second::class, ]); }) Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware: Route::get('/', function () { // ... })->middleware('group-name'); Route::middleware(['group-name'])->group(function () { // ... }); <a name="laravels-default-middleware-groups"></a> #### 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: <div class="overflow-auto"> | 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` | </div> <div class="overflow-auto"> | The `api` Middleware Group | | --- | | `Illuminate\Routing\Middleware\SubstituteBindings` | </div> 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: use App\Http\Middleware\EnsureTokenIsValid; use App\Http\Middleware\EnsureUserIsSubscribed; ->withMiddleware(function (Middleware $middleware) { $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: use App\Http\Middleware\StartCustomSession; use Illuminate\Session\Middleware\StartSession; $middleware->web(replace: [ StartSession::class => StartCustomSession::class, ]); Or, you may remove a middleware entirely: $middleware->web(remove: [ StartSession::class, ]); <a name="manually-managing-laravels-default-middleware-groups"></a> #### 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: ->withMiddleware(function (Middleware $middleware) { $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. <a name="middleware-aliases"></a>
243006
### 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: use App\Http\Middleware\EnsureUserIsSubscribed; ->withMiddleware(function (Middleware $middleware) { $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: 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: <div class="overflow-auto"> | 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` | </div> <a name="sorting-middleware"></a> ### 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 these situations, you may specify your middleware priority using the `priority` method in your application's `bootstrap/app.php` file: ->withMiddleware(function (Middleware $middleware) { $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\Foundation\Http\Middleware\ValidateCsrfToken::class, \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, \Illuminate\Routing\Middleware\ThrottleRequests::class, \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class, \Illuminate\Auth\Middleware\Authorize::class, ]); }) <a name="middleware-parameters"></a> ## Middleware Parameters Middleware can also receive additional parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create an `EnsureUserHasRole` middleware that receives a role name as an additional argument. Additional middleware parameters will be passed to the middleware after the `$next` argument: <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class EnsureUserHasRole { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next, string $role): Response { 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 `:`: use App\Http\Middleware\EnsureUserHasRole; Route::put('/post/{id}', function (string $id) { // ... })->middleware(EnsureUserHasRole::class.':editor'); Multiple parameters may be delimited by commas: Route::put('/post/{id}', function (string $id) { // ... })->middleware(EnsureUserHasRole::class.':editor,publisher'); <a name="terminable-middleware"></a> ## 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: <?php namespace Illuminate\Session\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class TerminatingMiddleware { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { return $next($request); } /** * Handle tasks after the response has been sent to the browser. */ public function terminate(Request $request, Response $response): void { // ... } } The `terminate` method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of routes or global middleware in your application's `bootstrap/app.php` file. When calling the `terminate` method on your middleware, Laravel will resolve a fresh instance of the middleware from the [service container](/docs/{{version}}/container). If you would like to use the same middleware instance when the `handle` and `terminate` methods are called, register the middleware with the container using the container's `singleton` method. Typically this should be done in the `register` method of your `AppServiceProvider`: use App\Http\Middleware\TerminatingMiddleware; /** * Register any application services. */ public function register(): void { $this->app->singleton(TerminatingMiddleware::class); }
243007
# Database: Pagination - [Introduction](#introduction) - [Basic Usage](#basic-usage) - [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) - [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) - [Using Bootstrap](#using-bootstrap) - [Paginator and LengthAwarePaginator Instance Methods](#paginator-instance-methods) - [Cursor Paginator Instance Methods](#cursor-paginator-instance-methods) <a name="introduction"></a> ## Introduction 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. <a name="tailwind-jit"></a> #### Tailwind JIT 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: ```js content: [ './resources/**/*.blade.php', './resources/**/*.js', './resources/**/*.vue', './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php', ], ``` <a name="basic-usage"></a>
243008
## Basic Usage <a name="paginating-query-builder-results"></a> ### Paginating Query Builder Results There are several ways to paginate items. The simplest is by using the `paginate` method on the [query builder](/docs/{{version}}/queries) or an [Eloquent query](/docs/{{version}}/eloquent). The `paginate` method automatically takes care of setting the query's "limit" and "offset" based on the current page being viewed by the user. By default, the current page is detected by the value of the `page` query string argument on the HTTP request. This value is automatically detected by Laravel, and is also automatically inserted into links generated by the paginator. 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: <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class UserController extends Controller { /** * Show all application users. */ public function index(): View { return view('user.index', [ 'users' => DB::table('users')->paginate(15) ]); } } <a name="simple-pagination"></a> #### Simple Pagination The `paginate` method counts the total number of records matched by the query before retrieving the records from the database. This is done so that the paginator knows how many pages of records there are in total. However, if you do not plan to show the total number of pages in your application's UI then the record count query is unnecessary. 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); <a name="paginating-eloquent-results"></a> ### 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; $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); You may also use the `simplePaginate` method when paginating Eloquent models: $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); <a name="multiple-paginator-instances-per-page"></a> #### 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: use App\Models\User; $users = User::where('votes', '>', 100)->paginate( $perPage = 15, $columns = ['*'], $pageName = 'users' ); <a name="cursor-pagination"></a> ### 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: ```nothing 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`: $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). > [!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. <a name="cursor-vs-offset-pagination"></a> #### Cursor vs. Offset Pagination To illustrate the differences between offset pagination and cursor pagination, let's examine some example SQL queries. Both of the following queries will both display the "second page" of results for a `users` table ordered by `id`: ```sql # Offset Pagination... select * from users order by id asc limit 15 offset 15; # Cursor Pagination... select * from users where id > 15 order by id asc limit 15; ``` The cursor pagination query offers the following advantages over offset pagination: - For large data-sets, cursor pagination will offer better performance if the "order by" columns are indexed. This is because the "offset" clause scans through all previously matched data. - For data-sets with frequent writes, offset pagination may skip records or show duplicates if results have been recently added to or deleted from the page a user is currently viewing. 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. <a name="manually-creating-a-paginator"></a> ### 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. The `Paginator` and `CursorPaginator` classes do not need to know the total number of items in the result set; however, because of this, these classes do not have methods for retrieving the index of the last page. The `LengthAwarePaginator` accepts almost the same arguments as the `Paginator`; however, it requires a count of the total number of items in the result set. 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. > [!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. <a name="customizing-pagination-urls"></a>
243009
### 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; Route::get('/users', function () { $users = User::paginate(15); $users->withPath('/admin/users'); // ... }); <a name="appending-query-string-values"></a> #### 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; Route::get('/users', function () { $users = User::paginate(15); $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(); <a name="appending-hash-fragments"></a> #### 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'); <a name="displaying-pagination-results"></a> ## 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 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 <div class="container"> @foreach ($users as $user) {{ $user->name }} @endforeach </div> {{ $users->links() }} ``` 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). <a name="adjusting-the-pagination-link-window"></a> ### 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: ```blade {{ $users->onEachSide(5)->links() }} ``` <a name="converting-results-to-json"></a> ### 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; 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... } ] } <a name="customizing-the-pagination-view"></a> ## 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: ```blade {{ $paginator->links('view.name') }} <!-- Passing additional data to the view... --> {{ $paginator->links('view.name', ['foo' => 'bar']) }} ``` However, the easiest way to customize the pagination views is by exporting them to your `resources/views/vendor` directory using the `vendor:publish` command: ```shell php artisan vendor:publish --tag=laravel-pagination ``` This command will place the views in your application's `resources/views/vendor/pagination` directory. The `tailwind.blade.php` file within this directory corresponds to the default pagination view. You may edit this file to modify the pagination HTML. 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: <?php namespace App\Providers; use Illuminate\Pagination\Paginator; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. */ public function boot(): void { Paginator::defaultView('view-name'); Paginator::defaultSimpleView('view-name'); } } <a name="using-bootstrap"></a> ### 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. */ public function boot(): void { Paginator::useBootstrapFive(); Paginator::useBootstrapFour(); } <a name="paginator-instance-methods"></a> ## Paginator / LengthAwarePaginator Instance Methods Each paginator instance provides additional pagination information via the following methods: <div class="overflow-auto"> | 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($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. | </div> <a name="cursor-paginator-instance-methods"></a>
243012
## Routing 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. <a name="requesting-the-password-reset-link"></a> ### Requesting the Password Reset Link <a name="the-password-reset-link-request-form"></a> #### 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'); 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. <a name="password-reset-link-handling-the-form-submission"></a> #### 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; Route::post('/forgot-password', function (Request $request) { $request->validate(['email' => 'required|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'); 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). > [!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). <a name="resetting-the-password"></a> ### Resetting the Password <a name="the-password-reset-form"></a> #### 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 (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. <a name="password-reset-handling-the-form-submission"></a> #### 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 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::PASSWORD_RESET ? 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. 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). <a name="deleting-expired-tokens"></a> ## 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: ```shell 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): use Illuminate\Support\Facades\Schedule; Schedule::command('auth:clear-resets')->everyFifteenMinutes(); <a name="password-customization"></a>
243014
# Laravel Telescope - [Introduction](#introduction) - [Installation](#installation) - [Local Only Installation](#local-only-installation) - [Configuration](#configuration) - [Data Pruning](#data-pruning) - [Dashboard Authorization](#dashboard-authorization) - [Upgrading Telescope](#upgrading-telescope) - [Filtering](#filtering) - [Entries](#filtering-entries) - [Batches](#filtering-batches) - [Tagging](#tagging) - [Available Watchers](#available-watchers) - [Batch Watcher](#batch-watcher) - [Cache Watcher](#cache-watcher) - [Command Watcher](#command-watcher) - [Dump Watcher](#dump-watcher) - [Event Watcher](#event-watcher) - [Exception Watcher](#exception-watcher) - [Gate Watcher](#gate-watcher) - [HTTP Client Watcher](#http-client-watcher) - [Job Watcher](#job-watcher) - [Log Watcher](#log-watcher) - [Mail Watcher](#mail-watcher) - [Model Watcher](#model-watcher) - [Notification Watcher](#notification-watcher) - [Query Watcher](#query-watcher) - [Redis Watcher](#redis-watcher) - [Request Watcher](#request-watcher) - [Schedule Watcher](#schedule-watcher) - [View Watcher](#view-watcher) - [Displaying User Avatars](#displaying-user-avatars) <a name="introduction"></a> ## Introduction [Laravel Telescope](https://github.com/laravel/telescope) makes a wonderful companion to your local Laravel development environment. Telescope provides insight into the requests coming into your application, exceptions, log entries, database queries, queued jobs, mail, notifications, cache operations, scheduled tasks, variable dumps, and more. <img src="https://laravel.com/img/docs/telescope-example.png"> <a name="installation"></a> ## Installation You may use the Composer package manager to install Telescope into your Laravel project: ```shell composer require laravel/telescope ``` 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 php artisan migrate ``` Finally, you may access the Telescope dashboard via the `/telescope` route. <a name="local-only-installation"></a> ### Local Only Installation If you plan to only use Telescope to assist your local development, you may install Telescope using the `--dev` flag: ```shell composer require laravel/telescope --dev php artisan telescope:install php artisan migrate ``` 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. */ public function register(): void { if ($this->app->environment('local')) { $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: ```json "extra": { "laravel": { "dont-discover": [ "laravel/telescope" ] } }, ``` <a name="configuration"></a> ### Configuration After publishing Telescope's assets, its primary configuration file will be located at `config/telescope.php`. This configuration file allows you to configure your [watcher options](#available-watchers). Each configuration option includes a description of its purpose, so be sure to thoroughly explore this file. If desired, you may disable Telescope's data collection entirely using the `enabled` configuration option: 'enabled' => env('TELESCOPE_ENABLED', true), <a name="data-pruning"></a> ### 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: 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: use Illuminate\Support\Facades\Schedule; Schedule::command('telescope:prune --hours=48')->daily(); <a name="dashboard-authorization"></a> ### Dashboard Authorization 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: 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', ]); }); } > [!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. <a name="upgrading-telescope"></a> ## Upgrading Telescope When upgrading to a new major version of Telescope, it's important that you carefully review [the upgrade guide](https://github.com/laravel/telescope/blob/master/UPGRADE.md). In addition, when upgrading to any new Telescope version, you should re-publish Telescope's assets: ```shell php artisan telescope:publish ``` 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 vendor:publish --tag=laravel-assets --ansi --force" ] } } ``` <a name="filtering"></a> ## Filtering <a name="filtering-entries"></a> ### Entries 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; /** * Register any application services. */ public function register(): void { $this->hideSensitiveRequestDetails(); Telescope::filter(function (IncomingEntry $entry) { if ($this->app->environment('local')) { return true; } return $entry->isReportableException() || $entry->isFailedJob() || $entry->isScheduledTask() || $entry->isSlowQuery() || $entry->hasMonitoredTag(); }); } <a name="filtering-batches"></a> ### 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\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(); }); }); } <a name="tagging"></a>
243017
# Error Handling - [Introduction](#introduction) - [Configuration](#configuration) - [Handling Exceptions](#handling-exceptions) - [Reporting Exceptions](#reporting-exceptions) - [Exception Log Levels](#exception-log-levels) - [Ignoring Exceptions by Type](#ignoring-exceptions-by-type) - [Rendering Exceptions](#rendering-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) <a name="introduction"></a> ## Introduction 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. <a name="configuration"></a> ## Configuration 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. 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.** <a name="handling-exceptions"></a> ## Handling Exceptions <a name="reporting-exceptions"></a> ### Reporting Exceptions In Laravel, exception reporting is used to log exceptions or send them to an external service [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. 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: ->withExceptions(function (Exceptions $exceptions) { $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: ->withExceptions(function (Exceptions $exceptions) { $exceptions->report(function (InvalidOrderException $e) { // ... })->stop(); $exceptions->report(function (InvalidOrderException $e) { return false; }); }) > [!NOTE] > To customize the exception reporting for a given exception, you may also utilize [reportable exceptions](/docs/{{version}}/errors#renderable-exceptions). <a name="global-log-context"></a> #### 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 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: ->withExceptions(function (Exceptions $exceptions) { $exceptions->context(fn () => [ 'foo' => 'bar', ]); }) <a name="exception-log-context"></a> #### 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 exceptions, you may specify any data relevant to that exception that should be added to the exception's log entry: <?php namespace App\Exceptions; use Exception; class InvalidOrderException extends Exception { // ... /** * Get the exception's context information. * * @return array<string, mixed> */ public function context(): array { return ['order_id' => $this->orderId]; } } <a name="the-report-helper"></a> #### 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 without rendering an error page to the user: public function isValid(string $value): bool { try { // Validate the value... } catch (Throwable $e) { report($e); return false; } } <a name="deduplicating-reported-exceptions"></a> #### 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: ->withExceptions(function (Exceptions $exceptions) { $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 ``` <a name="exception-log-levels"></a> ### 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: use PDOException; use Psr\Log\LogLevel; ->withExceptions(function (Exceptions $exceptions) { $exceptions->level(PDOException::class, LogLevel::CRITICAL); }) <a name="ignoring-exceptions-by-type"></a> ### Ignoring Exceptions by Type 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; ->withExceptions(function (Exceptions $exceptions) { $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 <?php namespace App\Exceptions; use Exception; use Illuminate\Contracts\Debug\ShouldntReport; class PodcastProcessingException extends Exception implements ShouldntReport { // } ``` 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: use Symfony\Component\HttpKernel\Exception\HttpException; ->withExceptions(function (Exceptions $exceptions) { $exceptions->stopIgnoring(HttpException::class); }) <a name="rendering-exceptions"></a>
243018
### 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 by using the `render` exception method in your application's `bootstrap/app.php` file. 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; use Illuminate\Http\Request; ->withExceptions(function (Exceptions $exceptions) { $exceptions->render(function (InvalidOrderException $e, Request $request) { return response()->view('errors.invalid-order', status: 500); }); }) 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 Illuminate\Http\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; ->withExceptions(function (Exceptions $exceptions) { $exceptions->render(function (NotFoundHttpException $e, Request $request) { if ($request->is('api/*')) { return response()->json([ 'message' => 'Record not found.' ], 404); } }); }) <a name="rendering-exceptions-as-json"></a> #### 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: use Illuminate\Http\Request; use Throwable; ->withExceptions(function (Exceptions $exceptions) { $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { if ($request->is('admin/*')) { return true; } return $request->expectsJson(); }); }) <a name="customizing-the-exception-response"></a> #### Customizing the Exception Response 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: use Symfony\Component\HttpFoundation\Response; ->withExceptions(function (Exceptions $exceptions) { $exceptions->respond(function (Response $response) { if ($response->getStatusCode() === 419) { return back()->with([ 'message' => 'The page expired, please try again.', ]); } return $response; }); }) <a name="renderable-exceptions"></a> ### 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 namespace App\Exceptions; use Exception; use Illuminate\Http\Request; use Illuminate\Http\Response; class InvalidOrderException extends Exception { /** * Report the exception. */ public function report(): void { // ... } /** * Render the exception into an HTTP response. */ public function render(Request $request): Response { return response(/* ... */); } } 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: /** * Render the exception into an HTTP response. */ public function render(Request $request): Response|bool { if (/** Determine if the exception needs custom rendering */) { return response(/* ... */); } return false; } If your exception contains custom reporting logic that is only necessary when certain conditions are met, you may need to instruct Laravel to sometimes report the exception using the default exception handling configuration. To accomplish this, you may return `false` from the exception's `report` method: /** * Report the exception. */ public function report(): bool { if (/** Determine if the exception needs custom reporting */) { // ... return true; } 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). <a name="throttling-reported-exceptions"></a> ### 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: use Illuminate\Support\Lottery; use Throwable; ->withExceptions(function (Exceptions $exceptions) { $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: use App\Exceptions\ApiMonitoringException; use Illuminate\Support\Lottery; use Throwable; ->withExceptions(function (Exceptions $exceptions) { $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: use Illuminate\Broadcasting\BroadcastException; use Illuminate\Cache\RateLimiting\Limit; use Throwable; ->withExceptions(function (Exceptions $exceptions) { $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`: use Illuminate\Broadcasting\BroadcastException; use Illuminate\Cache\RateLimiting\Limit; use Throwable; ->withExceptions(function (Exceptions $exceptions) { $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: use App\Exceptions\ApiMonitoringException; use Illuminate\Broadcasting\BroadcastException; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Support\Lottery; use Throwable; ->withExceptions(function (Exceptions $exceptions) { $exceptions->throttle(function (Throwable $e) { return match (true) { $e instanceof BroadcastException => Limit::perMinute(300), $e instanceof ApiMonitoringException => Lottery::odds(1, 1000), default => Limit::none(), }; }); }) <a name="http-exceptions"></a>
243019
## 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: abort(404); <a name="custom-http-error-pages"></a> ### Custom HTTP Error Pages 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: <h2>{{ $exception->getMessage() }}</h2> 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: ```shell php artisan vendor:publish --tag=laravel-errors ``` <a name="fallback-http-error-pages"></a> #### 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.
243021
# URL Generation - [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) - [Signed URLs](#signed-urls) - [URLs for Controller Actions](#urls-for-controller-actions) - [Default Values](#default-values) <a name="introduction"></a> ## Introduction Laravel provides several helpers to assist you in generating URLs for your application. These helpers are primarily helpful when building links in your templates and API responses, or when generating redirect responses to another part of your application. <a name="the-basics"></a> ## The Basics <a name="generating-urls"></a> ### Generating URLs 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); echo url("/posts/{$post->id}"); // http://example.com/posts/1 To generate a URL with query string parameters, you may use the `query` method: 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: 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: 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 <a name="accessing-the-current-url"></a> ### 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(); // Get the current URL including the query string... echo url()->full(); // Get the full URL for the previous request... echo url()->previous(); Each of these methods may also be accessed via the `URL` [facade](/docs/{{version}}/facades): use Illuminate\Support\Facades\URL; echo URL::current(); <a name="urls-for-named-routes"></a> ## 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'); To generate a URL to this route, you may use the `route` helper like so: echo route('post.show', ['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'); echo route('comment.show', ['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']); // http://example.com/post/1?search=rocket <a name="eloquent-models"></a> #### 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]); <a name="signed-urls"></a> ### Signed URLs Laravel allows you to easily create "signed" URLs to named routes. These URLs have a "signature" hash appended to the query string which allows Laravel to verify that the URL has not been modified since it was created. Signed URLs are especially useful for routes that are publicly accessible yet need a layer of protection against URL manipulation. 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; 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], 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; return URL::temporarySignedRoute( 'unsubscribe', now()->addMinutes(30), ['user' => 1] ); <a name="validating-signed-route-requests"></a> #### 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; Route::get('/unsubscribe/{user}', function (Request $request) { if (! $request->hasValidSignature()) { abort(401); } // ... })->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); } 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: Route::post('/unsubscribe/{user}', function (Request $request) { // ... })->name('unsubscribe')->middleware('signed'); 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:relative'); <a name="responding-to-invalid-signed-routes"></a> #### 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 "render" closure for the `InvalidSignatureException` exception in your application's `bootstrap/app.php` file: use Illuminate\Routing\Exceptions\InvalidSignatureException; ->withExceptions(function (Exceptions $exceptions) { $exceptions->render(function (InvalidSignatureException $e) { return response()->view('errors.link-expired', status: 403); }); }) <a name="urls-for-controller-actions"></a> ## URLs for Controller Actions The `action` function generates a URL for the given controller action: use App\Http\Controllers\HomeController; $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]); <a name="default-values"></a>
243022
## 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'); 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: <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\URL; use Symfony\Component\HttpFoundation\Response; class SetDefaultLocaleForUrls { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { 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. <a name="url-defaults-middleware-priority"></a> #### 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 using the `priority` middleware method in your application's `bootstrap/app.php` file: ```php ->withMiddleware(function (Middleware $middleware) { $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\Foundation\Http\Middleware\ValidateCsrfToken::class, \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class, \Illuminate\Routing\Middleware\ThrottleRequests::class, \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class, \Illuminate\Session\Middleware\AuthenticateSession::class, \App\Http\Middleware\SetDefaultLocaleForUrls::class, // [tl! add] \Illuminate\Routing\Middleware\SubstituteBindings::class, \Illuminate\Auth\Middleware\Authorize::class, ]); }) ```
243024
## 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. <a name="generating-commands"></a> ### Generating Commands To create a new command, you may use the `make:command` Artisan command. This command will create a new command class in the `app/Console/Commands` directory. Don't worry if this directory does not exist in your application - it will be created the first time you run the `make:command` Artisan command: ```shell php artisan make:command SendEmails ``` <a name="command-structure"></a> ### Command Structure After generating your command, you should define appropriate values for the `signature` and `description` properties of the class. These properties will be used when displaying your command on the `list` screen. The `signature` property also allows you to define [your command's input expectations](#defining-input-expectations). The `handle` method will be called when your command is executed. You may place your command logic in this method. 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: <?php namespace App\Console\Commands; use App\Models\User; use App\Support\DripEmailer; use Illuminate\Console\Command; class SendEmails extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'mail:send {user}'; /** * The console command description. * * @var string */ protected $description = 'Send a marketing email to a user'; /** * Execute the console command. */ public function handle(DripEmailer $drip): void { $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. <a name="exit-codes"></a> #### 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: $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`: $this->fail('Something went wrong.'); <a name="closure-commands"></a> ### 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. 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: 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. <a name="type-hinting-dependencies"></a> #### Type-Hinting Dependencies 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; Artisan::command('mail:send {user}', function (DripEmailer $drip, string $user) { $drip->send(User::find($user)); }); <a name="closure-command-descriptions"></a> #### 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: Artisan::command('mail:send {user}', function (string $user) { // ... })->purpose('Send a marketing email to a user'); <a name="isolatable-commands"></a> ### 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 namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Contracts\Console\Isolatable; class SendEmails extends Command implements Isolatable { // ... } When a command is marked as `Isolatable`, Laravel will automatically add an `--isolated` option to the command. When the command is invoked with that option, Laravel will ensure that no other instances of that command are already running. Laravel accomplishes this by attempting to acquire an atomic lock using your application's default cache driver. If other instances of the command are running, the command will not execute; however, the command will still exit with a successful exit status code: ```shell php artisan mail:send 1 --isolated ``` If you would like to specify the exit status code that the command should return if it is not able to execute, you may provide the desired status code via the `isolated` option: ```shell php artisan mail:send 1 --isolated=12 ``` <a name="lock-id"></a> #### 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'); } ``` <a name="lock-expiration-time"></a> #### 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); } ``` <a name="defining-input-expectations"></a>
243026
## Command I/O <a name="retrieving-input"></a> ### Retrieving Input 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. */ 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(); 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'); // Retrieve all options as an array... $options = $this->options(); <a name="prompting-for-input"></a> ### 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. */ 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: $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?'); <a name="asking-for-confirmation"></a> #### 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?')) { // ... } 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)) { // ... } <a name="auto-completion"></a> #### 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']); 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 (string $input) { // Return auto-completion options... }); <a name="multiple-choice-questions"></a> #### 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 ); 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 ); <a name="writing-output"></a> ### 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: /** * Execute the console command. */ public function handle(): void { // ... $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!'); You may use the `line` method to display plain, uncolored text: $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(); // Write three blank lines... $this->newLine(3); <a name="tables"></a> #### 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: use App\Models\User; $this->table( ['Name', 'Email'], User::all(['name', 'email'])->toArray() ); <a name="progress-bars"></a> #### 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; $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(); $bar = $this->output->createProgressBar(count($users)); $bar->start(); foreach ($users as $user) { $this->performTask($user); $bar->advance(); } $bar->finish(); > [!NOTE] > For more advanced options, check out the [Symfony Progress Bar component documentation](https://symfony.com/doc/7.0/components/console/helpers/progressbar.html). <a name="registering-commands"></a> ## Registering 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: ->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: use App\Domain\Orders\Commands\SendEmails; ->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. <a name="programmatically-executing-commands"></a>
243028
# Laravel Folio - [Introduction](#introduction) - [Installation](#installation) - [Page Paths / URIs](#page-paths-uris) - [Subdomain Routing](#subdomain-routing) - [Creating Routes](#creating-routes) - [Nested Routes](#nested-routes) - [Index Routes](#index-routes) - [Route Parameters](#route-parameters) - [Route Model Binding](#route-model-binding) - [Soft Deleted Models](#soft-deleted-models) - [Render Hooks](#render-hooks) - [Named Routes](#named-routes) - [Middleware](#middleware) - [Route Caching](#route-caching) <a name="introduction"></a> ## 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 <div> Hello World </div> ``` <a name="installation"></a> ## Installation To get started, install Folio into your project using the Composer package manager: ```bash 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: ```bash php artisan folio:install ``` <a name="page-paths-uris"></a> ### 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', // ... ], ]); ``` <a name="subdomain-routing"></a> ### 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')); ``` <a name="creating-routes"></a> ## 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: ```bash php artisan folio:list ``` <a name="nested-routes"></a> ### 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: ```bash php artisan folio:page user/profile # pages/user/profile.blade.php → /user/profile ``` <a name="index-routes"></a> ### 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: ```bash php artisan folio:page index # pages/index.blade.php → / php artisan folio:page users/index # pages/users/index.blade.php → /users ``` <a name="route-parameters"></a> ## 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: ```bash 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 <div> User {{ $id }} </div> ``` To capture multiple segments, you can prefix the encapsulated segment with three dots `...`: ```bash 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 <ul> @foreach ($ids as $id) <li>User {{ $id }}</li> @endforeach </ul> ``` <a name="route-model-binding"></a> ## 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: ```bash 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 <div> User {{ $user->id }} </div> ``` #### 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: ```bash php artisan folio:page "users/[.App.Models.User]" # pages/users/[.App.Models.User].blade.php → /users/1 ``` <a name="soft-deleted-models"></a> ### 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 <?php use function Laravel\Folio\{withTrashed}; withTrashed(); ?> <div> User {{ $user->id }} </div> ``` <a name="render-hooks"></a> ## Render Hook
243030
# Testing: Getting Started - [Introduction](#introduction) - [Environment](#environment) - [Creating Tests](#creating-tests) - [Running Tests](#running-tests) - [Running Tests in Parallel](#running-tests-in-parallel) - [Reporting Test Coverage](#reporting-test-coverage) - [Profiling Tests](#profiling-tests) <a name="introduction"></a> ## Introduction 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/pest`, `vendor/bin/phpunit`, or `php artisan test` commands to run your tests. <a name="environment"></a> ## 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 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! <a name="the-env-testing-environment-file"></a> #### 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 Pest and PHPUnit tests or executing Artisan commands with the `--env=testing` option. <a name="creating-tests"></a> ## Creating Tests To create a new test case, use the `make:test` Artisan command. By default, tests will be placed in the `tests/Feature` directory: ```shell php artisan make:test UserTest ``` If you would like to create a test within the `tests/Unit` directory, you may use the `--unit` option when executing the `make:test` command: ```shell php artisan make:test UserTest --unit ``` > [!NOTE] > Test stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization). 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: ```php tab=Pest <?php test('basic', function () { expect(true)->toBeTrue(); }); ``` ```php tab=PHPUnit <?php namespace Tests\Unit; use PHPUnit\Framework\TestCase; class ExampleTest extends TestCase { /** * A basic test example. */ public function test_basic_test(): void { $this->assertTrue(true); } } ``` > [!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. <a name="running-tests"></a>
243033
## Interacting With The Request <a name="accessing-the-request"></a> ### Accessing the Request To obtain an instance of the current HTTP request via dependency injection, you should type-hint the `Illuminate\Http\Request` class on your route closure or controller method. The incoming request instance will automatically be injected by the Laravel [service container](/docs/{{version}}/container): <?php namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class UserController extends Controller { /** * Store a new user. */ public function store(Request $request): RedirectResponse { $name = $request->input('name'); // Store the user... return redirect('/users'); } } As mentioned, you may also type-hint the `Illuminate\Http\Request` class on a route closure. The service container will automatically inject the incoming request into the closure when it is executed: use Illuminate\Http\Request; Route::get('/', function (Request $request) { // ... }); <a name="dependency-injection-route-parameters"></a> #### Dependency Injection and Route Parameters If your controller method is also expecting input from a route parameter you should list your route parameters after your other dependencies. For example, if your route is defined like so: use App\Http\Controllers\UserController; Route::put('/user/{id}', [UserController::class, 'update']); You may still type-hint the `Illuminate\Http\Request` and access your `id` route parameter by defining your controller method as follows: <?php namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class UserController extends Controller { /** * Update the specified user. */ public function update(Request $request, string $id): RedirectResponse { // Update the user... return redirect('/users'); } } <a name="request-path-and-method"></a> ### Request Path, Host, and Method The `Illuminate\Http\Request` instance provides a variety of methods for examining the incoming HTTP request and extends the `Symfony\Component\HttpFoundation\Request` class. We will discuss a few of the most important methods below. <a name="retrieving-the-request-path"></a> #### Retrieving the Request Path The `path` method returns the request's path information. So, if the incoming request is targeted at `http://example.com/foo/bar`, the `path` method will return `foo/bar`: $uri = $request->path(); <a name="inspecting-the-request-path"></a> #### Inspecting the Request Path / Route The `is` method allows you to verify that the incoming request path matches a given pattern. You may use the `*` character as a wildcard when utilizing this method: if ($request->is('admin/*')) { // ... } Using the `routeIs` method, you may determine if the incoming request has matched a [named route](/docs/{{version}}/routing#named-routes): if ($request->routeIs('admin.*')) { // ... } <a name="retrieving-the-request-url"></a> #### Retrieving the Request URL To retrieve the full URL for the incoming request you may use the `url` or `fullUrl` methods. The `url` method will return the URL without the query string, while the `fullUrl` method includes the query string: $url = $request->url(); $urlWithQueryString = $request->fullUrl(); If you would like to append query string data to the current URL, you may call the `fullUrlWithQuery` method. This method merges the given array of query string variables with the current query string: $request->fullUrlWithQuery(['type' => 'phone']); If you would like to get the current URL without a given query string parameter, you may utilize the `fullUrlWithoutQuery` method: ```php $request->fullUrlWithoutQuery(['type']); ``` <a name="retrieving-the-request-host"></a> #### Retrieving the Request Host You may retrieve the "host" of the incoming request via the `host`, `httpHost`, and `schemeAndHttpHost` methods: $request->host(); $request->httpHost(); $request->schemeAndHttpHost(); <a name="retrieving-the-request-method"></a> #### Retrieving the Request Method The `method` method will return the HTTP verb for the request. You may use the `isMethod` method to verify that the HTTP verb matches a given string: $method = $request->method(); if ($request->isMethod('post')) { // ... } <a name="request-headers"></a> ### Request Headers You may retrieve a request header from the `Illuminate\Http\Request` instance using the `header` method. If the header is not present on the request, `null` will be returned. However, the `header` method accepts an optional second argument that will be returned if the header is not present on the request: $value = $request->header('X-Header-Name'); $value = $request->header('X-Header-Name', 'default'); The `hasHeader` method may be used to determine if the request contains a given header: if ($request->hasHeader('X-Header-Name')) { // ... } For convenience, the `bearerToken` method may be used to retrieve a bearer token from the `Authorization` header. If no such header is present, an empty string will be returned: $token = $request->bearerToken(); <a name="request-ip-address"></a> ### Request IP Address The `ip` method may be used to retrieve the IP address of the client that made the request to your application: $ipAddress = $request->ip(); If you would like to retrieve an array of IP addresses, including all of the client IP addresses that were forwarded by proxies, you may use the `ips` method. The "original" client IP address will be at the end of the array: $ipAddresses = $request->ips(); In general, IP addresses should be considered untrusted, user-controlled input and be used for informational purposes only. <a name="content-negotiation"></a> ### Content Negotiation Laravel provides several methods for inspecting the incoming request's requested content types via the `Accept` header. First, the `getAcceptableContentTypes` method will return an array containing all of the content types accepted by the request: $contentTypes = $request->getAcceptableContentTypes(); The `accepts` method accepts an array of content types and returns `true` if any of the content types are accepted by the request. Otherwise, `false` will be returned: if ($request->accepts(['text/html', 'application/json'])) { // ... } You may use the `prefers` method to determine which content type out of a given array of content types is most preferred by the request. If none of the provided content types are accepted by the request, `null` will be returned: $preferred = $request->prefers(['text/html', 'application/json']); Since many applications only serve HTML or JSON, you may use the `expectsJson` method to quickly determine if the incoming request expects a JSON response: if ($request->expectsJson()) { // ... } <a name="psr7-requests"></a> ### PSR-7 Requests The [PSR-7 standard](https://www.php-fig.org/psr/psr-7/) specifies interfaces for HTTP messages, including requests and responses. If you would like to obtain an instance of a PSR-7 request instead of a Laravel request, you will first need to install a few libraries. Laravel uses the *Symfony HTTP Message Bridge* component to convert typical Laravel requests and responses into PSR-7 compatible implementations: ```shell composer require symfony/psr-http-message-bridge composer require nyholm/psr7 ``` Once you have installed these libraries, you may obtain a PSR-7 request by type-hinting the request interface on your route closure or controller method: use Psr\Http\Message\ServerRequestInterface; Route::get('/', function (ServerRequestInterface $request) { // ... }); > [!NOTE] > If you return a PSR-7 response instance from a route or controller, it will automatically be converted back to a Laravel response instance and be displayed by the framework. <a name="input"></a>
243034
## Input <a name="retrieving-input"></a> ### Retrieving Input <a name="retrieving-all-input-data"></a> #### Retrieving All Input Data You may retrieve all of the incoming request's input data as an `array` using the `all` method. This method may be used regardless of whether the incoming request is from an HTML form or is an XHR request: $input = $request->all(); Using the `collect` method, you may retrieve all of the incoming request's input data as a [collection](/docs/{{version}}/collections): $input = $request->collect(); The `collect` method also allows you to retrieve a subset of the incoming request's input as a collection: $request->collect('users')->each(function (string $user) { // ... }); <a name="retrieving-an-input-value"></a> #### Retrieving an Input Value Using a few simple methods, you may access all of the user input from your `Illuminate\Http\Request` instance without worrying about which HTTP verb was used for the request. Regardless of the HTTP verb, the `input` method may be used to retrieve user input: $name = $request->input('name'); You may pass a default value as the second argument to the `input` method. This value will be returned if the requested input value is not present on the request: $name = $request->input('name', 'Sally'); When working with forms that contain array inputs, use "dot" notation to access the arrays: $name = $request->input('products.0.name'); $names = $request->input('products.*.name'); You may call the `input` method without any arguments in order to retrieve all of the input values as an associative array: $input = $request->input(); <a name="retrieving-input-from-the-query-string"></a> #### Retrieving Input From the Query String While the `input` method retrieves values from the entire request payload (including the query string), the `query` method will only retrieve values from the query string: $name = $request->query('name'); If the requested query string value data is not present, the second argument to this method will be returned: $name = $request->query('name', 'Helen'); You may call the `query` method without any arguments in order to retrieve all of the query string values as an associative array: $query = $request->query(); <a name="retrieving-json-input-values"></a> #### Retrieving JSON Input Values When sending JSON requests to your application, you may access the JSON data via the `input` method as long as the `Content-Type` header of the request is properly set to `application/json`. You may even use "dot" syntax to retrieve values that are nested within JSON arrays / objects: $name = $request->input('user.name'); <a name="retrieving-stringable-input-values"></a> #### Retrieving Stringable Input Values Instead of retrieving the request's input data as a primitive `string`, you may use the `string` method to retrieve the request data as an instance of [`Illuminate\Support\Stringable`](/docs/{{version}}/strings): $name = $request->string('name')->trim(); <a name="retrieving-integer-input-values"></a> #### Retrieving Integer Input Values To retrieve input values as integers, you may use the `integer` method. This method will attempt to cast the input value to an integer. If the input is not present or the cast fails, it will return the default value you specify. This is particularly useful for pagination or other numeric inputs: $perPage = $request->integer('per_page'); <a name="retrieving-boolean-input-values"></a> #### Retrieving Boolean Input Values When dealing with HTML elements like checkboxes, your application may receive "truthy" values that are actually strings. For example, "true" or "on". For convenience, you may use the `boolean` method to retrieve these values as booleans. The `boolean` method returns `true` for 1, "1", true, "true", "on", and "yes". All other values will return `false`: $archived = $request->boolean('archived'); <a name="retrieving-date-input-values"></a> #### Retrieving Date Input Values For convenience, input values containing dates / times may be retrieved as Carbon instances using the `date` method. If the request does not contain an input value with the given name, `null` will be returned: $birthday = $request->date('birthday'); The second and third arguments accepted by the `date` method may be used to specify the date's format and timezone, respectively: $elapsed = $request->date('elapsed', '!H:i', 'Europe/Madrid'); If the input value is present but has an invalid format, an `InvalidArgumentException` will be thrown; therefore, it is recommended that you validate the input before invoking the `date` method. <a name="retrieving-enum-input-values"></a> #### Retrieving Enum Input Values Input values that correspond to [PHP enums](https://www.php.net/manual/en/language.types.enumerations.php) may also be retrieved from the request. If the request does not contain an input value with the given name or the enum does not have a backing value that matches the input value, `null` will be returned. The `enum` method accepts the name of the input value and the enum class as its first and second arguments: use App\Enums\Status; $status = $request->enum('status', Status::class); <a name="retrieving-input-via-dynamic-properties"></a> #### Retrieving Input via Dynamic Properties You may also access user input using dynamic properties on the `Illuminate\Http\Request` instance. For example, if one of your application's forms contains a `name` field, you may access the value of the field like so: $name = $request->name; When using dynamic properties, Laravel will first look for the parameter's value in the request payload. If it is not present, Laravel will search for the field in the matched route's parameters. <a name="retrieving-a-portion-of-the-input-data"></a> #### Retrieving a Portion of the Input Data If you need to retrieve a subset of the input data, you may use the `only` and `except` methods. Both of these methods accept a single `array` or a dynamic list of arguments: $input = $request->only(['username', 'password']); $input = $request->only('username', 'password'); $input = $request->except(['credit_card']); $input = $request->except('credit_card'); > [!WARNING] > The `only` method returns all of the key / value pairs that you request; however, it will not return key / value pairs that are not present on the request. <a name="input-presence"></a>
243035
### Input Presence You may use the `has` method to determine if a value is present on the request. The `has` method returns `true` if the value is present on the request: if ($request->has('name')) { // ... } When given an array, the `has` method will determine if all of the specified values are present: if ($request->has(['name', 'email'])) { // ... } The `hasAny` method returns `true` if any of the specified values are present: if ($request->hasAny(['name', 'email'])) { // ... } The `whenHas` method will execute the given closure if a value is present on the request: $request->whenHas('name', function (string $input) { // ... }); A second closure may be passed to the `whenHas` method that will be executed if the specified value is not present on the request: $request->whenHas('name', function (string $input) { // The "name" value is present... }, function () { // The "name" value is not present... }); If you would like to determine if a value is present on the request and is not an empty string, you may use the `filled` method: if ($request->filled('name')) { // ... } If you would like to determine if a value is missing from the request or is an empty string, you may use the `isNotFilled` method: if ($request->isNotFilled('name')) { // ... } When given an array, the `isNotFilled` method will determine if all of the specified values are missing or empty: if ($request->isNotFilled(['name', 'email'])) { // ... } The `anyFilled` method returns `true` if any of the specified values is not an empty string: if ($request->anyFilled(['name', 'email'])) { // ... } The `whenFilled` method will execute the given closure if a value is present on the request and is not an empty string: $request->whenFilled('name', function (string $input) { // ... }); A second closure may be passed to the `whenFilled` method that will be executed if the specified value is not "filled": $request->whenFilled('name', function (string $input) { // The "name" value is filled... }, function () { // The "name" value is not filled... }); To determine if a given key is absent from the request, you may use the `missing` and `whenMissing` methods: if ($request->missing('name')) { // ... } $request->whenMissing('name', function () { // The "name" value is missing... }, function () { // The "name" value is present... }); <a name="merging-additional-input"></a> ### Merging Additional Input Sometimes you may need to manually merge additional input into the request's existing input data. To accomplish this, you may use the `merge` method. If a given input key already exists on the request, it will be overwritten by the data provided to the `merge` method: $request->merge(['votes' => 0]); The `mergeIfMissing` method may be used to merge input into the request if the corresponding keys do not already exist within the request's input data: $request->mergeIfMissing(['votes' => 0]); <a name="old-input"></a> ### Old Input Laravel allows you to keep input from one request during the next request. This feature is particularly useful for re-populating forms after detecting validation errors. However, if you are using Laravel's included [validation features](/docs/{{version}}/validation), it is possible that you will not need to manually use these session input flashing methods directly, as some of Laravel's built-in validation facilities will call them automatically. <a name="flashing-input-to-the-session"></a> #### Flashing Input to the Session The `flash` method on the `Illuminate\Http\Request` class will flash the current input to the [session](/docs/{{version}}/session) so that it is available during the user's next request to the application: $request->flash(); You may also use the `flashOnly` and `flashExcept` methods to flash a subset of the request data to the session. These methods are useful for keeping sensitive information such as passwords out of the session: $request->flashOnly(['username', 'email']); $request->flashExcept('password'); <a name="flashing-input-then-redirecting"></a> #### Flashing Input Then Redirecting Since you often will want to flash input to the session and then redirect to the previous page, you may easily chain input flashing onto a redirect using the `withInput` method: return redirect('/form')->withInput(); return redirect()->route('user.create')->withInput(); return redirect('/form')->withInput( $request->except('password') ); <a name="retrieving-old-input"></a> #### Retrieving Old Input 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): $username = $request->old('username'); 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: <input type="text" name="username" value="{{ old('username') }}"> <a name="cookies"></a> ### Cookies <a name="retrieving-cookies-from-requests"></a> #### Retrieving Cookies From Requests All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client. To retrieve a cookie value from the request, use the `cookie` method on an `Illuminate\Http\Request` instance: $value = $request->cookie('name'); <a name="input-trimming-and-normalization"></a> ## Input Trimming and Normalization By default, Laravel includes the `Illuminate\Foundation\Http\Middleware\TrimStrings` and `Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull` middleware in your application's global middleware stack. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to `null`. This allows you to not have to worry about these normalization concerns in your routes and controllers. #### Disabling Input Normalization If you would like to disable this behavior for all requests, you may remove the two middleware from your application's middleware stack by invoking the `$middleware->remove` method in your application's `bootstrap/app.php` file: use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull; use Illuminate\Foundation\Http\Middleware\TrimStrings; ->withMiddleware(function (Middleware $middleware) { $middleware->remove([ ConvertEmptyStringsToNull::class, TrimStrings::class, ]); }) If you would like to disable string trimming and empty string conversion for a subset of requests to your application, you may use the `trimStrings` and `convertEmptyStringsToNull` middleware methods within your application's `bootstrap/app.php` file. Both methods accept an array of closures, which should return `true` or `false` to indicate whether input normalization should be skipped: ->withMiddleware(function (Middleware $middleware) { $middleware->convertEmptyStringsToNull(except: [ fn (Request $request) => $request->is('admin/*'), ]); $middleware->trimStrings(except: [ fn (Request $request) => $request->is('admin/*'), ]); }) <a name="files"></a>
243037
# Laravel Reverb - [Introduction](#introduction) - [Installation](#installation) - [Configuration](#configuration) - [Application Credentials](#application-credentials) - [Allowed Origins](#allowed-origins) - [Additional Applications](#additional-applications) - [SSL](#ssl) - [Running the Server](#running-server) - [Debugging](#debugging) - [Restarting](#restarting) - [Monitoring](#monitoring) - [Running Reverb in Production](#production) - [Open Files](#open-files) - [Event Loop](#event-loop) - [Web Server](#web-server) - [Ports](#ports) - [Process Management](#process-management) - [Scaling](#scaling) <a name="introduction"></a> ## Introduction [Laravel Reverb](https://github.com/laravel/reverb) brings blazing-fast and scalable real-time WebSocket communication directly to your Laravel application, and provides seamless integration with Laravel’s existing suite of [event broadcasting tools](/docs/{{version}}/broadcasting). <a name="installation"></a> ## Installation You may install Reverb using the `install:broadcasting` Artisan command: ``` php artisan install:broadcasting ``` <a name="configuration"></a> ## Configuration Behind the scenes, the `install:broadcasting` Artisan command will run the `reverb:install` command, which will install Reverb with a sensible set of default configuration options. If you would like to make any configuration changes, you may do so by updating Reverb's environment variables or by updating the `config/reverb.php` configuration file. <a name="application-credentials"></a> ### Application Credentials In order to establish a connection to Reverb, a set of Reverb "application" credentials must be exchanged between the client and server. These credentials are configured on the server and are used to verify the request from the client. You may define these credentials using the following environment variables: ```ini REVERB_APP_ID=my-app-id REVERB_APP_KEY=my-app-key REVERB_APP_SECRET=my-app-secret ``` <a name="allowed-origins"></a> ### Allowed Origins You may also define the origins from which client requests may originate by updating the value of the `allowed_origins` configuration value within the `apps` section of the `config/reverb.php` configuration file. Any requests from an origin not listed in your allowed origins will be rejected. You may allow all origins using `*`: ```php 'apps' => [ [ 'id' => 'my-app-id', 'allowed_origins' => ['laravel.com'], // ... ] ] ``` <a name="additional-applications"></a> ### Additional Applications Typically, Reverb provides a WebSocket server for the application in which it is installed. However, it is possible to serve more than one application using a single Reverb installation. For example, you may wish to maintain a single Laravel application which, via Reverb, provides WebSocket connectivity for multiple applications. This can be achieved by defining multiple `apps` in your application's `config/reverb.php` configuration file: ```php 'apps' => [ [ 'app_id' => 'my-app-one', // ... ], [ 'app_id' => 'my-app-two', // ... ], ], ``` <a name="ssl"></a> ### SSL In most cases, secure WebSocket connections are handled by the upstream web server (Nginx, etc.) before the request is proxied to your Reverb server. However, it can sometimes be useful, such as during local development, for the Reverb server to handle secure connections directly. If you are using [Laravel Herd's](https://herd.laravel.com) secure site feature or you are using [Laravel Valet](/docs/{{version}}/valet) and have run the [secure command](/docs/{{version}}/valet#securing-sites) against your application, you may use the Herd / Valet certificate generated for your site to secure your Reverb connections. To do so, set the `REVERB_HOST` environment variable to your site's hostname or explicitly pass the hostname option when starting the Reverb server: ```sh php artisan reverb:start --host="0.0.0.0" --port=8080 --hostname="laravel.test" ``` Since Herd and Valet domains resolve to `localhost`, running the command above will result in your Reverb server being accessible via the secure WebSocket protocol (`wss`) at `wss://laravel.test:8080`. You may also manually choose a certificate by defining `tls` options in your application's `config/reverb.php` configuration file. Within the array of `tls` options, you may provide any of the options supported by [PHP's SSL context options](https://www.php.net/manual/en/context.ssl.php): ```php 'options' => [ 'tls' => [ 'local_cert' => '/path/to/cert.pem' ], ], ``` <a name="running-server"></a> ## Running the Server The Reverb server can be started using the `reverb:start` Artisan command: ```sh php artisan reverb:start ``` By default, the Reverb server will be started at `0.0.0.0:8080`, making it accessible from all network interfaces. If you need to specify a custom host or port, you may do so via the `--host` and `--port` options when starting the server: ```sh php artisan reverb:start --host=127.0.0.1 --port=9000 ``` Alternatively, you may define `REVERB_SERVER_HOST` and `REVERB_SERVER_PORT` environment variables in your application's `.env` configuration file. The `REVERB_SERVER_HOST` and `REVERB_SERVER_PORT` environment variables should not be confused with `REVERB_HOST` and `REVERB_PORT`. The former specify the host and port on which to run the Reverb server itself, while the latter pair instruct Laravel where to send broadcast messages. For example, in a production environment, you may route requests from your public Reverb hostname on port `443` to a Reverb server operating on `0.0.0.0:8080`. In this scenario, your environment variables would be defined as follows: ```ini REVERB_SERVER_HOST=0.0.0.0 REVERB_SERVER_PORT=8080 REVERB_HOST=ws.laravel.com REVERB_PORT=443 ``` <a name="debugging"></a> ### Debugging To improve performance, Reverb does not output any debug information by default. If you would like to see the stream of data passing through your Reverb server, you may provide the `--debug` option to the `reverb:start` command: ```sh php artisan reverb:start --debug ``` <a name="restarting"></a> ### Restarting Since Reverb is a long-running process, changes to your code will not be reflected without restarting the server via the `reverb:restart` Artisan command. The `reverb:restart` command ensures all connections are gracefully terminated before stopping the server. If you are running Reverb with a process manager such as Supervisor, the server will be automatically restarted by the process manager after all connections have been terminated: ```sh php artisan reverb:restart ``` <a name="monitoring"></a> ## Monitoring Reverb may be monitored via an integration with [Laravel Pulse](/docs/{{version}}/pulse). By enabling Reverb's Pulse integration, you may track the number of connections and messages being handled by your server. To enable the integration, you should first ensure you have [installed Pulse](/docs/{{version}}/pulse#installation). Then, add any of Reverb's recorders to your application's `config/pulse.php` configuration file: ```php use Laravel\Reverb\Pulse\Recorders\ReverbConnections; use Laravel\Reverb\Pulse\Recorders\ReverbMessages; 'recorders' => [ ReverbConnections::class => [ 'sample_rate' => 1, ], ReverbMessages::class => [ 'sample_rate' => 1, ], ... ], ``` Next, add the Pulse cards for each recorder to your [Pulse dashboard](/docs/{{version}}/pulse#dashboard-customization): ```blade <x-pulse> <livewire:reverb.connections cols="full" /> <livewire:reverb.messages cols="full" /> ... </x-pulse> ``` <a name="production"></a> ##
243042
### 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: 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()) <p>You are subscribed.</p> @endif ``` We can even easily determine if a user is subscribed to specific product or price: ```blade @if ($user->subscribedToProduct('pro_basic')) <p>You are subscribed to our Basic product.</p> @endif @if ($user->subscribedToPrice('price_basic_monthly')) <p>You are subscribed to our monthly Basic plan.</p> @endif ``` <a name="quickstart-building-a-subscribed-middleware"></a> #### 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 namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class Subscribed { /** * Handle an incoming request. */ public function handle(Request $request, Closure $next): Response { if (! $request->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: use App\Http\Middleware\Subscribed; Route::get('/dashboard', function () { // ... })->middleware([Subscribed::class]); <a name="quickstart-allowing-customers-to-manage-their-billing-plan"></a> #### 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 <a href="{{ route('billing') }}"> Billing </a> ``` 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: 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. <a name="customers"></a>
243052
## Invoices <a name="retrieving-invoices"></a> ### Retrieving Invoices 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(); If you would like to include pending invoices in the results, you may use the `invoicesIncludingPending` method: $invoices = $user->invoicesIncludingPending(); You may use the `findInvoice` method to retrieve a specific invoice by its ID: $invoice = $user->findInvoice($invoiceId); <a name="displaying-invoice-information"></a> #### 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: <table> @foreach ($invoices as $invoice) <tr> <td>{{ $invoice->date()->toFormattedDateString() }}</td> <td>{{ $invoice->total() }}</td> <td><a href="/user/invoice/{{ $invoice->id }}">Download</a></td> </tr> @endforeach </table> <a name="upcoming-invoices"></a> ### Upcoming Invoices To retrieve the upcoming invoice for a customer, you may use the `upcomingInvoice` method: $invoice = $user->upcomingInvoice(); Similarly, if the customer has multiple subscriptions, you can also retrieve the upcoming invoice for a specific subscription: $invoice = $user->subscription('default')->upcomingInvoice(); <a name="previewing-subscription-invoices"></a> ### 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'); 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']); <a name="generating-invoice-pdfs"></a> ### Generating Invoice PDFs Before generating invoice PDFs, you should use Composer to install the Dompdf library, which is the default invoice renderer for Cashier: ```php composer require dompdf/dompdf ``` 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: use Illuminate\Http\Request; Route::get('/user/invoice/{invoice}', function (Request $request, string $invoiceId) { return $request->user()->downloadInvoice($invoiceId); }); 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: 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'); <a name="custom-invoice-render"></a> #### 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; class ApiInvoiceRenderer implements InvoiceRenderer { /** * Render the given invoice and return the raw PDF bytes. */ 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(); } } 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. <a name="checkout"></a>
243064
### Job Chaining Job chaining allows you to specify a list of queued jobs that should be run in sequence after the primary job has executed successfully. If one job in the sequence fails, the rest of the jobs will not be run. To execute a queued job chain, you may use the `chain` method provided by the `Bus` facade. Laravel's command bus is a lower level component that queued job dispatching is built on top of: use App\Jobs\OptimizePodcast; use App\Jobs\ProcessPodcast; use App\Jobs\ReleasePodcast; use Illuminate\Support\Facades\Bus; Bus::chain([ new ProcessPodcast, new OptimizePodcast, new ReleasePodcast, ])->dispatch(); In addition to chaining job class instances, you may also chain closures: Bus::chain([ new ProcessPodcast, new OptimizePodcast, function () { Podcast::update(/* ... */); }, ])->dispatch(); > [!WARNING] > Deleting jobs using the `$this->delete()` method within the job will not prevent chained jobs from being processed. The chain will only stop executing if a job in the chain fails. <a name="chain-connection-queue"></a> #### Chain Connection and Queue If you would like to specify the connection and queue that should be used for the chained jobs, you may use the `onConnection` and `onQueue` methods. These methods specify the queue connection and queue name that should be used unless the queued job is explicitly assigned a different connection / queue: Bus::chain([ new ProcessPodcast, new OptimizePodcast, new ReleasePodcast, ])->onConnection('redis')->onQueue('podcasts')->dispatch(); <a name="adding-jobs-to-the-chain"></a> #### Adding Jobs to the Chain Occasionally, you may need to prepend or append a job to an existing job chain from within another job in that chain. You may accomplish this using the `prependToChain` and `appendToChain` methods: ```php /** * Execute the job. */ public function handle(): void { // ... // Prepend to the current chain, run job immediately after current job... $this->prependToChain(new TranscribePodcast); // Append to the current chain, run job at end of chain... $this->appendToChain(new TranscribePodcast); } ``` <a name="chain-failures"></a> #### Chain Failures When chaining jobs, you may use the `catch` method to specify a closure that should be invoked if a job within the chain fails. The given callback will receive the `Throwable` instance that caused the job failure: use Illuminate\Support\Facades\Bus; use Throwable; Bus::chain([ new ProcessPodcast, new OptimizePodcast, new ReleasePodcast, ])->catch(function (Throwable $e) { // A job within the chain has failed... })->dispatch(); > [!WARNING] > Since chain callbacks are serialized and executed at a later time by the Laravel queue, you should not use the `$this` variable within chain callbacks. <a name="customizing-the-queue-and-connection"></a> ### Customizing the Queue and Connection <a name="dispatching-to-a-particular-queue"></a> #### Dispatching to a Particular Queue By pushing jobs to different queues, you may "categorize" your queued jobs and even prioritize how many workers you assign to various queues. Keep in mind, this does not push jobs to different queue "connections" as defined by your queue configuration file, but only to specific queues within a single connection. To specify the queue, use the `onQueue` method when dispatching the job: <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Jobs\ProcessPodcast; use App\Models\Podcast; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class PodcastController extends Controller { /** * Store a new podcast. */ public function store(Request $request): RedirectResponse { $podcast = Podcast::create(/* ... */); // Create podcast... ProcessPodcast::dispatch($podcast)->onQueue('processing'); return redirect('/podcasts'); } } Alternatively, you may specify the job's queue by calling the `onQueue` method within the job's constructor: <?php namespace App\Jobs; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; class ProcessPodcast implements ShouldQueue { use Queueable; /** * Create a new job instance. */ public function __construct() { $this->onQueue('processing'); } } <a name="dispatching-to-a-particular-connection"></a> #### Dispatching to a Particular Connection If your application interacts with multiple queue connections, you may specify which connection to push a job to using the `onConnection` method: <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Jobs\ProcessPodcast; use App\Models\Podcast; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class PodcastController extends Controller { /** * Store a new podcast. */ public function store(Request $request): RedirectResponse { $podcast = Podcast::create(/* ... */); // Create podcast... ProcessPodcast::dispatch($podcast)->onConnection('sqs'); return redirect('/podcasts'); } } You may chain the `onConnection` and `onQueue` methods together to specify the connection and the queue for a job: ProcessPodcast::dispatch($podcast) ->onConnection('sqs') ->onQueue('processing'); Alternatively, you may specify the job's connection by calling the `onConnection` method within the job's constructor: <?php namespace App\Jobs; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; class ProcessPodcast implements ShouldQueue { use Queueable; /** * Create a new job instance. */ public function __construct() { $this->onConnection('sqs'); } } <a name="max-job-attempts-and-timeout"></a>
243065
### Specifying Max Job Attempts / Timeout Values <a name="max-attempts"></a> #### Max Attempts If one of your queued jobs 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 job may be attempted. One approach to specifying the maximum number of times a job may be attempted is via the `--tries` switch on the Artisan command line. This will apply to all jobs processed by the worker unless the job being processed specifies the number of times it may be attempted: ```shell php artisan queue:work --tries=3 ``` If a job exceeds its maximum number of attempts, it will be considered a "failed" job. For more information on handling failed jobs, consult the [failed job documentation](#dealing-with-failed-jobs). If `--tries=0` is provided to the `queue:work` command, the job will be retried indefinitely. You may take a more granular approach by defining the maximum number of times a job may be attempted on the job class itself. If the maximum number of attempts is specified on the job, it will take precedence over the `--tries` value provided on the command line: <?php namespace App\Jobs; class ProcessPodcast implements ShouldQueue { /** * The number of times the job may be attempted. * * @var int */ public $tries = 5; } If you need dynamic control over a particular job's maximum attempts, you may define a `tries` method on the job: /** * Determine number of times the job may be attempted. */ public function tries(): int { return 5; } <a name="time-based-attempts"></a> #### Time Based Attempts As an alternative to defining how many times a job may be attempted before it fails, you may define a time at which the job should no longer be attempted. This allows a job to be attempted any number of times within a given time frame. To define the time at which a job should no longer be attempted, add a `retryUntil` method to your job class. This method should return a `DateTime` instance: use DateTime; /** * Determine the time at which the job should timeout. */ public function retryUntil(): DateTime { return now()->addMinutes(10); } > [!NOTE] > You may also define a `tries` property or `retryUntil` method on your [queued event listeners](/docs/{{version}}/events#queued-event-listeners). <a name="max-exceptions"></a> #### Max Exceptions Sometimes you may wish to specify that a job 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 job class: <?php namespace App\Jobs; use Illuminate\Support\Facades\Redis; class ProcessPodcast implements ShouldQueue { /** * The number of times the job may be attempted. * * @var int */ public $tries = 25; /** * The maximum number of unhandled exceptions to allow before failing. * * @var int */ public $maxExceptions = 3; /** * Execute the job. */ public function handle(): void { Redis::throttle('key')->allow(10)->every(60)->then(function () { // Lock obtained, process the podcast... }, function () { // Unable to obtain lock... return $this->release(10); }); } } In this example, the job is released for ten seconds if the application is unable to obtain a Redis lock and will continue to be retried up to 25 times. However, the job will fail if three unhandled exceptions are thrown by the job. <a name="timeout"></a> #### Timeout Often, you know roughly how long you expect your queued jobs to take. For this reason, Laravel allows you to specify a "timeout" value. By default, the timeout value is 60 seconds. If a job is processing for longer than the number of seconds specified by the timeout value, the worker processing the job will exit with an error. Typically, the worker will be restarted automatically by a [process manager configured on your server](#supervisor-configuration). The maximum number of seconds that jobs can run may be specified using the `--timeout` switch on the Artisan command line: ```shell php artisan queue:work --timeout=30 ``` If the job exceeds its maximum attempts by continually timing out, it will be marked as failed. You may also define the maximum number of seconds a job should be allowed to run on the job class itself. If the timeout is specified on the job, it will take precedence over any timeout specified on the command line: <?php namespace App\Jobs; class ProcessPodcast implements ShouldQueue { /** * The number of seconds the job can run before timing out. * * @var int */ public $timeout = 120; } Sometimes, IO blocking processes such as sockets or outgoing HTTP connections may not respect your specified timeout. Therefore, when using these features, you should always attempt to specify a timeout using their APIs as well. For example, when using Guzzle, you should always specify a connection and request timeout value. > [!WARNING] > The `pcntl` PHP extension must be installed in order to specify job timeouts. In addition, a job's "timeout" value should always be less than its ["retry after"](#job-expiration) value. Otherwise, the job may be re-attempted before it has actually finished executing or timed out. <a name="failing-on-timeout"></a> #### Failing on Timeout If you would like to indicate that a job should be marked as [failed](#dealing-with-failed-jobs) on timeout, you may define the `$failOnTimeout` property on the job class: ```php /** * Indicate if the job should be marked as failed on timeout. * * @var bool */ public $failOnTimeout = true; ``` <a name="error-handling"></a> ### Error Handling If an exception is thrown while the job is being processed, the job will automatically be released back onto the queue so it may be attempted again. The job will continue to be released until it has been attempted the maximum number of times allowed by your application. The maximum number of attempts is defined by the `--tries` switch used on the `queue:work` Artisan command. Alternatively, the maximum number of attempts may be defined on the job class itself. More information on running the queue worker [can be found below](#running-the-queue-worker). <a name="manually-releasing-a-job"></a> #### Manually Releasing a Job Sometimes you may wish to manually release a job back onto the queue so that it can be attempted again at a later time. You may accomplish this by calling the `release` method: /** * Execute the job. */ public function handle(): void { // ... $this->release(); } By default, the `release` method will release the job back onto the queue for immediate processing. However, you may instruct the queue to not make the job available for processing until a given number of seconds has elapsed by passing an integer or date instance to the `release` method: $this->release(10); $this->release(now()->addSeconds(10)); <a name="manually-failing-a-job"></a> #### Manually Failing a Job Occasionally you may need to manually mark a job as "failed". To do so, you may call the `fail` method: /** * Execute the job. */ public function handle(): void { // ... $this->fail(); } If you would like to mark your job as failed because of an exception that you have caught, you may pass the exception to the `fail` method. Or, for convenience, you may pass a string error message which will be converted to an exception for you: $this->fail($exception); $this->fail('Something went wrong.'); > [!NOTE] > For more information on failed jobs, check out the [documentation on dealing with job failures](#dealing-with-failed-jobs). <a name="job-batching"></a>
243068
## Running the Queue Worker <a name="the-queue-work-command"></a> ### The `queue:work` Command Laravel includes an Artisan command that will start a queue worker and process new jobs as they are pushed onto the queue. You may run the worker using the `queue:work` Artisan command. Note that once the `queue:work` command has started, it will continue to run until it is manually stopped or you close your terminal: ```shell php artisan queue:work ``` > [!NOTE] > To keep the `queue:work` process running permanently in the background, you should use a process monitor such as [Supervisor](#supervisor-configuration) to ensure that the queue worker does not stop running. You may include the `-v` flag when invoking the `queue:work` command if you would like the processed job IDs to be included in the command's output: ```shell php artisan queue:work -v ``` Remember, queue workers are long-lived processes and store the booted application state in memory. As a result, they will not notice changes in your code base after they have been started. So, during your deployment process, be sure to [restart your queue workers](#queue-workers-and-deployment). In addition, remember that any static state created or modified by your application will not be automatically reset between jobs. Alternatively, you may run the `queue:listen` command. When using the `queue:listen` command, you don't have to manually restart the worker when you want to reload your updated code or reset the application state; however, this command is significantly less efficient than the `queue:work` command: ```shell php artisan queue:listen ``` <a name="running-multiple-queue-workers"></a> #### Running Multiple Queue Workers To assign multiple workers to a queue and process jobs concurrently, you should simply start multiple `queue:work` processes. This can either be done locally via multiple tabs in your terminal or in production using your process manager's configuration settings. [When using Supervisor](#supervisor-configuration), you may use the `numprocs` configuration value. <a name="specifying-the-connection-queue"></a> #### Specifying the Connection and Queue You may also specify which queue connection the worker should utilize. The connection name passed to the `work` command should correspond to one of the connections defined in your `config/queue.php` configuration file: ```shell php artisan queue:work redis ``` By default, the `queue:work` command only processes jobs for the default queue on a given connection. However, you may customize your queue worker even further by only processing particular queues for a given connection. For example, if all of your emails are processed in an `emails` queue on your `redis` queue connection, you may issue the following command to start a worker that only processes that queue: ```shell php artisan queue:work redis --queue=emails ``` <a name="processing-a-specified-number-of-jobs"></a> #### Processing a Specified Number of Jobs The `--once` option may be used to instruct the worker to only process a single job from the queue: ```shell php artisan queue:work --once ``` The `--max-jobs` option may be used to instruct the worker to process the given number of jobs and then exit. This option may be useful when combined with [Supervisor](#supervisor-configuration) so that your workers are automatically restarted after processing a given number of jobs, releasing any memory they may have accumulated: ```shell php artisan queue:work --max-jobs=1000 ``` <a name="processing-all-queued-jobs-then-exiting"></a> #### Processing All Queued Jobs and Then Exiting The `--stop-when-empty` option may be used to instruct the worker to process all jobs and then exit gracefully. This option can be useful when processing Laravel queues within a Docker container if you wish to shutdown the container after the queue is empty: ```shell php artisan queue:work --stop-when-empty ``` <a name="processing-jobs-for-a-given-number-of-seconds"></a> #### Processing Jobs for a Given Number of Seconds The `--max-time` option may be used to instruct the worker to process jobs for the given number of seconds and then exit. This option may be useful when combined with [Supervisor](#supervisor-configuration) so that your workers are automatically restarted after processing jobs for a given amount of time, releasing any memory they may have accumulated: ```shell # Process jobs for one hour and then exit... php artisan queue:work --max-time=3600 ``` <a name="worker-sleep-duration"></a> #### Worker Sleep Duration When jobs are available on the queue, the worker will keep processing jobs with no delay in between jobs. However, the `sleep` option determines how many seconds the worker will "sleep" if there are no jobs available. Of course, while sleeping, the worker will not process any new jobs: ```shell php artisan queue:work --sleep=3 ``` <a name="maintenance-mode-queues"></a> #### Maintenance Mode and Queues While your application is in [maintenance mode](/docs/{{version}}/configuration#maintenance-mode), no queued jobs will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode. To force your queue workers to process jobs even if maintenance mode is enabled, you may use `--force` option: ```shell php artisan queue:work --force ``` <a name="resource-considerations"></a> #### Resource Considerations Daemon queue workers do not "reboot" the framework before processing each job. Therefore, you should release any heavy resources after each job completes. For example, if you are doing image manipulation with the GD library, you should free the memory with `imagedestroy` when you are done processing the image. <a name="queue-priorities"></a> ### Queue Priorities Sometimes you may wish to prioritize how your queues are processed. For example, in your `config/queue.php` configuration file, you may set the default `queue` for your `redis` connection to `low`. However, occasionally you may wish to push a job to a `high` priority queue like so: dispatch((new Job)->onQueue('high')); To start a worker that verifies that all of the `high` queue jobs are processed before continuing to any jobs on the `low` queue, pass a comma-delimited list of queue names to the `work` command: ```shell php artisan queue:work --queue=high,low ``` <a name="queue-workers-and-deployment"></a> ### Queue Workers and Deployment Since queue workers are long-lived processes, they will not notice changes to your code without being restarted. So, the simplest way to deploy an application using queue workers is to restart the workers during your deployment process. You may gracefully restart all of the workers by issuing the `queue:restart` command: ```shell php artisan queue:restart ``` This command will instruct all queue workers to gracefully exit after they finish processing their current job so that no existing jobs are lost. Since the queue workers will exit when the `queue:restart` command is executed, you should be running a process manager such as [Supervisor](#supervisor-configuration) to automatically restart the queue workers. > [!NOTE] > The queue 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. <a name="job-expirations-and-timeouts"></a>
243069
### Job Expirations and Timeouts <a name="job-expiration"></a> #### Job Expiration In your `config/queue.php` configuration file, each queue connection defines a `retry_after` option. This option specifies how many seconds the queue connection should wait before retrying a job that is being processed. For example, if the value of `retry_after` is set to `90`, the job will be released back onto the queue if it has been processing for 90 seconds without being released or deleted. Typically, you should set the `retry_after` value to the maximum number of seconds your jobs should reasonably take to complete processing. > [!WARNING] > The only queue connection which does not contain a `retry_after` value is Amazon SQS. SQS will retry the job based on the [Default Visibility Timeout](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html) which is managed within the AWS console. <a name="worker-timeouts"></a> #### Worker Timeouts The `queue:work` Artisan command exposes a `--timeout` option. By default, the `--timeout` value is 60 seconds. If a job is processing for longer than the number of seconds specified by the timeout value, the worker processing the job will exit with an error. Typically, the worker will be restarted automatically by a [process manager configured on your server](#supervisor-configuration): ```shell php artisan queue:work --timeout=60 ``` The `retry_after` configuration option and the `--timeout` CLI option are different, but work together to ensure that jobs are not lost and that jobs are only successfully processed once. > [!WARNING] > The `--timeout` value should always be at least several seconds shorter than your `retry_after` configuration value. This will ensure that a worker processing a frozen job is always terminated before the job is retried. If your `--timeout` option is longer than your `retry_after` configuration value, your jobs may be processed twice. <a name="supervisor-configuration"></a> ## Supervisor Configuration In production, you need a way to keep your `queue:work` processes running. A `queue:work` process may stop running for a variety of reasons, such as an exceeded worker timeout or the execution of the `queue:restart` command. For this reason, you need to configure a process monitor that can detect when your `queue:work` processes exit and automatically restart them. In addition, process monitors can allow you to specify how many `queue:work` processes you would like to run concurrently. Supervisor is a process monitor commonly used in Linux environments and we will discuss how to configure it in the following documentation. <a name="installing-supervisor"></a> #### Installing Supervisor Supervisor is a process monitor for the Linux operating system, and will automatically restart your `queue:work` processes if they fail. To install Supervisor on Ubuntu, you may use the following command: ```shell sudo apt-get install supervisor ``` > [!NOTE] > If configuring and managing Supervisor yourself sounds overwhelming, consider using [Laravel Forge](https://forge.laravel.com), which will automatically install and configure Supervisor for your production Laravel projects. <a name="configuring-supervisor"></a> #### Configuring Supervisor Supervisor configuration files are typically stored in the `/etc/supervisor/conf.d` directory. Within this directory, you may create any number of configuration files that instruct supervisor how your processes should be monitored. For example, let's create a `laravel-worker.conf` file that starts and monitors `queue:work` processes: ```ini [program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /home/forge/app.com/artisan queue:work sqs --sleep=3 --tries=3 --max-time=3600 autostart=true autorestart=true stopasgroup=true killasgroup=true user=forge numprocs=8 redirect_stderr=true stdout_logfile=/home/forge/app.com/worker.log stopwaitsecs=3600 ``` In this example, the `numprocs` directive will instruct Supervisor to run eight `queue:work` processes and monitor all of them, automatically restarting them if they fail. You should change the `command` directive of the configuration to reflect your desired queue connection and worker options. > [!WARNING] > 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. <a name="starting-supervisor"></a> #### Starting Supervisor Once the configuration file has been created, you may update the Supervisor configuration and start the processes using the following commands: ```shell sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl start "laravel-worker:*" ``` For more information on Supervisor, consult the [Supervisor documentation](http://supervisord.org/index.html). <a name="dealing-with-failed-jobs"></a>
243076
# Laravel Passport - [Introduction](#introduction) - [Passport or Sanctum?](#passport-or-sanctum) - [Installation](#installation) - [Deploying Passport](#deploying-passport) - [Upgrading Passport](#upgrading-passport) - [Configuration](#configuration) - [Client Secret Hashing](#client-secret-hashing) - [Token Lifetimes](#token-lifetimes) - [Overriding Default Models](#overriding-default-models) - [Overriding Routes](#overriding-routes) - [Issuing Access Tokens](#issuing-access-tokens) - [Managing Clients](#managing-clients) - [Requesting Tokens](#requesting-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) - [Requesting Tokens](#requesting-auth-pkce-grant-tokens) - [Password Grant Tokens](#password-grant-tokens) - [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) - [Personal Access Tokens](#personal-access-tokens) - [Creating a Personal Access Client](#creating-a-personal-access-client) - [Managing Personal Access Tokens](#managing-personal-access-tokens) - [Protecting Routes](#protecting-routes) - [Via Middleware](#via-middleware) - [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) - [Checking Scopes](#checking-scopes) - [Consuming Your API With JavaScript](#consuming-your-api-with-javascript) - [Events](#events) - [Testing](#testing) <a name="introduction"></a> ## Introduction [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. > [!WARNING] > 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. <a name="passport-or-sanctum"></a> ### 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. However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use [Laravel Sanctum](/docs/{{version}}/sanctum). Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience. <a name="installation"></a> ## Installation You may install Laravel Passport via the `install:api` Artisan command: ```shell php artisan install:api --passport ``` 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. Additionally, this command will ask if you would like to use UUIDs as the primary key value of the Passport `Client` model instead of auto-incrementing integers. After running the `install:api` command, add the `Laravel\Passport\HasApiTokens` trait 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: <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; } 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: 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], <a name="deploying-passport"></a> ### Deploying Passport When deploying Passport to your application's servers for the first time, you will likely need to run the `passport:keys` command. This command generates the encryption keys Passport needs in order to generate access tokens. The generated keys are not typically kept in source control: ```shell 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\AppServiceProvider` class: /** * Bootstrap any application services. */ public function boot(): void { Passport::loadKeysFrom(__DIR__.'/../secrets/oauth'); } <a name="loading-keys-from-the-environment"></a> #### Loading Keys From the Environment Alternatively, you may publish Passport's configuration file using the `vendor:publish` Artisan command: ```shell php artisan vendor:publish --tag=passport-config ``` After the configuration file has been published, you may load your application's encryption keys by defining them as environment variables: ```ini PASSPORT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- <private key here> -----END RSA PRIVATE KEY-----" PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY----- <public key here> -----END PUBLIC KEY-----" ``` <a name="upgrading-passport"></a> ### Upgrading Passport When upgrading to a new major version of Passport, it's important that you carefully review [the upgrade guide](https://github.com/laravel/passport/blob/master/UPGRADE.md). <a name="configuration"></a>
243078
### Requesting Tokens <a name="requesting-tokens-redirecting-for-authorization"></a> #### 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; 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, // 'prompt' => '', // "none", "consent", or "login" ]); return redirect('http://passport-app.test/oauth/authorize?'.$query); }); The `prompt` parameter may be used to specify the authentication behavior of the Passport application. 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. 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. > [!NOTE] > Remember, the `/oauth/authorize` route is already defined by Passport. You do not need to manually define this route. <a name="approving-the-request"></a> #### Approving the Request 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. 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: ```shell php artisan vendor:publish --tag=passport-views ``` 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, unless the consuming application has explicitly set the `prompt` parameter when redirecting for authorization: <?php namespace App\Models\Passport; use Laravel\Passport\Client as BaseClient; class Client extends BaseClient { /** * Determine if the client should skip the authorization prompt. */ public function skipsAuthorization(): bool { return $this->firstParty(); } } <a name="requesting-tokens-converting-authorization-codes-to-access-tokens"></a> #### 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, 'Invalid state value.' ); $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. > [!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. <a name="tokens-json-api"></a> #### 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/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. <a name="get-oauthtokens"></a> #### `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: ```js axios.get('/oauth/tokens') .then(response => { console.log(response.data); }); ``` <a name="delete-oauthtokenstoken-id"></a> #### `DELETE /oauth/tokens/{token-id}` This route may be used to revoke authorized access tokens and their related refresh tokens: ```js axios.delete('/oauth/tokens/' + tokenId); ``` <a name="refreshing-tokens"></a> ### Refreshing Tokens 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; $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' => '', ]); 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. <a name="revoking-tokens"></a> ### 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): use Laravel\Passport\TokenRepository; use Laravel\Passport\RefreshTokenRepository; $tokenRepository = app(TokenRepository::class); $refreshTokenRepository = app(RefreshTokenRepository::class); // Revoke an access token... $tokenRepository->revokeAccessToken($tokenId); // Revoke all of the token's refresh tokens... $refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId); <a name="purging-tokens"></a> ### Purging Tokens 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... php artisan passport:purge # Only purge tokens expired for more than 6 hours... php artisan passport:purge --hours=6 # Only purge revoked tokens and auth codes... php artisan passport:purge --revoked # Only purge expired tokens and auth codes... php artisan passport:purge --expired ``` 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: use Illuminate\Support\Facades\Schedule; Schedule::command('passport:purge')->hourly(); <a name="code-grant-pkce"></a>
243081
## Client Credentials Grant Tokens 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. Before your application can issue tokens via the client credentials grant, you will need to create a client credentials grant client. You may do this using the `--client` option of the `passport:client` Artisan command: ```shell php artisan passport:client --client ``` Next, to use this grant type, register a middleware alias for the `CheckClientCredentials` middleware. You may define middleware aliases in your application's `bootstrap/app.php` file: use Laravel\Passport\Http\Middleware\CheckClientCredentials; ->withMiddleware(function (Middleware $middleware) { $middleware->alias([ 'client' => CheckClientCredentials::class ]); }) Then, attach the middleware to a route: Route::get('/orders', function (Request $request) { ... })->middleware('client'); 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: Route::get('/orders', function (Request $request) { ... })->middleware('client:check-status,your-scope'); <a name="retrieving-tokens"></a> ### Retrieving Tokens To retrieve a token using this grant type, make a request to the `oauth/token` endpoint: 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', ]); return $response->json()['access_token']; <a name="personal-access-tokens"></a> ## 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. > [!NOTE] > 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. <a name="creating-a-personal-access-client"></a> ### 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: ```shell 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: ```ini PASSPORT_PERSONAL_ACCESS_CLIENT_ID="client-id-value" PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET="unhashed-client-secret-value" ``` <a name="managing-personal-access-tokens"></a> ### 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; <a name="personal-access-tokens-json-api"></a> #### 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/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. <a name="get-oauthscopes"></a> #### `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); }); ``` <a name="get-oauthpersonal-access-tokens"></a> #### `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); }); ``` <a name="post-oauthpersonal-access-tokens"></a> #### `POST /oauth/personal-access-tokens` 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: ```js const data = { name: 'Token Name', scopes: [] }; axios.post('/oauth/personal-access-tokens', data) .then(response => { console.log(response.data.accessToken); }) .catch (response => { // List errors on response... }); ``` <a name="delete-oauthpersonal-access-tokenstoken-id"></a> #### `DELETE /oauth/personal-access-tokens/{token-id}` This route may be used to revoke personal access tokens: ```js axios.delete('/oauth/personal-access-tokens/' + tokenId); ``` <a name="protecting-routes"></a> ## Protecting Routes <a name="via-middleware"></a> ### Via Middleware 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'); > [!WARNING] > 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. <a name="multiple-authentication-guards"></a> #### 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: 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], 'api-customers' => [ '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'); > [!NOTE] > For more information on using multiple user providers with Passport, please consult the [password grant documentation](#customizing-the-user-provider). <a name="passing-the-access-token"></a> ### 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: use Illuminate\Support\Facades\Http; $response = Http::withHeaders([ 'Accept' => 'application/json', 'Authorization' => 'Bearer '.$accessToken, ])->get('https://passport-app.test/api/user'); return $response->json(); <a name="token-scopes"></a>
243082
## Token Scopes Scopes allow your API clients to request a specific set of permissions when requesting authorization to access an account. For example, if you are building an e-commerce application, not all API consumers will need the ability to place orders. Instead, you may allow the consumers to only request authorization to access order shipment statuses. In other words, scopes allow your application's users to limit the actions a third-party application can perform on their behalf. <a name="defining-scopes"></a> ### Defining Scopes 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: /** * Bootstrap any application services. */ public function boot(): void { Passport::tokensCan([ 'place-orders' => 'Place orders', 'check-status' => 'Check order status', ]); } <a name="default-scope"></a> ### 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\AppServiceProvider` class: use Laravel\Passport\Passport; Passport::tokensCan([ 'place-orders' => 'Place orders', 'check-status' => 'Check order status', ]); Passport::setDefaultScope([ 'check-status', 'place-orders', ]); > [!NOTE] > Passport's default scopes do not apply to personal access tokens that are generated by the user. <a name="assigning-scopes-to-tokens"></a> ### Assigning Scopes to Tokens <a name="when-requesting-authorization-codes"></a> #### 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', ]); return redirect('http://passport-app.test/oauth/authorize?'.$query); }); <a name="when-issuing-personal-access-tokens"></a> #### 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; <a name="checking-scopes"></a> ### 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, define the following middleware aliases in your application's `bootstrap/app.php` file: use Laravel\Passport\Http\Middleware\CheckForAnyScope; use Laravel\Passport\Http\Middleware\CheckScopes; ->withMiddleware(function (Middleware $middleware) { $middleware->alias([ 'scopes' => CheckScopes::class, 'scope' => CheckForAnyScope::class, ]); }) <a name="check-for-all-scopes"></a> #### 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: Route::get('/orders', function () { // Access token has both "check-status" and "place-orders" scopes... })->middleware(['auth:api', 'scopes:check-status,place-orders']); <a name="check-for-any-scopes"></a> #### 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: Route::get('/orders', function () { // Access token has either "check-status" or "place-orders" scope... })->middleware(['auth:api', 'scope:check-status,place-orders']); <a name="checking-scopes-on-a-token-instance"></a> #### 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; Route::get('/orders', function (Request $request) { if ($request->user()->tokenCan('place-orders')) { // ... } }); <a name="additional-scope-methods"></a> #### Additional Scope Methods The `scopeIds` method will return an array of all defined IDs / names: use Laravel\Passport\Passport; Passport::scopeIds(); The `scopes` method will return an array of all defined scopes as instances of `Laravel\Passport\Scope`: 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']); You may determine if a given scope has been defined using the `hasScope` method: Passport::hasScope('place-orders'); <a name="consuming-your-api-with-javascript"></a> ## Consuming Your API With JavaScript 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 append the `CreateFreshApiToken` middleware to the `web` middleware group in your application's `bootstrap/app.php` file: use Laravel\Passport\Http\Middleware\CreateFreshApiToken; ->withMiddleware(function (Middleware $middleware) { $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); }); <a name="customizing-the-cookie-name"></a> #### 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: /** * Bootstrap any application services. */ public function boot(): void { Passport::cookie('custom_name'); } <a name="csrf-protection"></a> #### 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. > [!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()`. <a name="events"></a> ## Events 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: <div class="overflow-auto"> | Event Name | | --- | | `Laravel\Passport\Events\AccessTokenCreated` | | `Laravel\Passport\Events\RefreshTokenCreated` | </div> <a name="testing"></a>
243087
# Deployment - [Introduction](#introduction) - [Server Requirements](#server-requirements) - [Server Configuration](#server-configuration) - [Nginx](#nginx) - [FrankenPHP](#frankenphp) - [Directory Permissions](#directory-permissions) - [Optimization](#optimization) - [Caching Configuration](#optimizing-configuration-loading) - [Caching Events](#caching-events) - [Caching Routes](#optimizing-route-loading) - [Caching Views](#optimizing-view-loading) - [Debug Mode](#debug-mode) - [The Health Route](#the-health-route) - [Easy Deployment With Forge / Vapor](#deploying-with-forge-or-vapor) <a name="introduction"></a> ## Introduction When you're ready to deploy your Laravel application to production, there are some important things you can do to make sure your application is running as efficiently as possible. In this document, we'll cover some great starting points for making sure your Laravel application is deployed properly. <a name="server-requirements"></a> ## Server Requirements The Laravel framework has a few system requirements. You should ensure that your web server has the following minimum PHP version and extensions: <div class="content-list" markdown="1"> - PHP >= 8.2 - Ctype PHP Extension - cURL PHP Extension - DOM PHP Extension - Fileinfo 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 </div> <a name="server-configuration"></a> ## Server Configuration <a name="nginx"></a> ### 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).** 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: ```nginx server { listen 80; listen [::]:80; server_name example.com; root /srv/example.com/public; add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; index index.php; charset utf-8; location / { try_files $uri $uri/ /index.php?$query_string; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } error_page 404 /index.php; location ~ \.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).* { deny all; } } ``` <a name="frankenphp"></a> ### 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/). <a name="directory-permissions"></a> ### 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. <a name="optimization"></a> ## 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 ``` 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 php artisan optimize:clear ``` In the following documentation, we will discuss each of the granular optimization commands that are executed by the `optimize` command. <a name="optimizing-configuration-loading"></a> ### Caching Configuration When deploying your application to production, you should make sure that you run the `config:cache` Artisan command during your deployment process: ```shell 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. > [!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`. <a name="caching-events"></a> ### 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 ``` <a name="optimizing-route-loading"></a> ### 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: ```shell 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. <a name="optimizing-view-loading"></a> ### Caching Views When deploying your application to production, you should make sure that you run the `view:cache` Artisan command during your deployment process: ```shell php artisan view:cache ``` This command precompiles all your Blade views so they are not compiled on demand, improving the performance of each request that returns a view. <a name="debug-mode"></a> ## 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 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.** <a name="the-health-route"></a> ## The Health Route 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: ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', // [tl! remove] health: '/status', // [tl! add] ) 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. <a name="deploying-with-forge-or-vapor"></a>
243089
# CSRF Protection - [Introduction](#csrf-introduction) - [Preventing CSRF Requests](#preventing-csrf-requests) - [Excluding URIs](#csrf-excluding-uris) - [X-CSRF-Token](#csrf-x-csrf-token) - [X-XSRF-Token](#csrf-x-xsrf-token) <a name="csrf-introduction"></a> ## Introduction Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user. Thankfully, Laravel makes it easy to protect your application from [cross-site request forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) (CSRF) attacks. <a name="csrf-explanation"></a> #### 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. Without CSRF protection, a malicious website could create an HTML form that points to your application's `/user/email` route and submits the malicious user's own email address: ```blade <form action="https://your-application.com/user/email" method="POST"> <input type="email" value="malicious-email@example.com"> </form> <script> document.forms[0].submit(); </script> ``` 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. <a name="preventing-csrf-requests"></a> ## Preventing CSRF Requests Laravel automatically generates a CSRF "token" for each active [user session](/docs/{{version}}/session) managed by the application. This token is used to verify that the authenticated user is the person actually making the requests to the application. Since this token is stored in the user's session and changes each time the session is regenerated, a malicious application is unable to access it. 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; Route::get('/token', function (Request $request) { $token = $request->session()->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: ```blade <form method="POST" action="/profile"> @csrf <!-- Equivalent to... --> <input type="hidden" name="_token" value="{{ csrf_token() }}" /> </form> ``` 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. <a name="csrf-tokens-and-spas"></a> ### CSRF Tokens & SPAs If you are building an SPA that is utilizing Laravel as an API backend, you should consult the [Laravel Sanctum documentation](/docs/{{version}}/sanctum) for information on authenticating with your API and protecting against CSRF vulnerabilities. <a name="csrf-excluding-uris"></a> ### Excluding URIs From CSRF Protection 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 Laravel applies to all routes in the `routes/web.php` file. However, you may also exclude specific routes by providing their URIs to the `validateCsrfTokens` method in your application's `bootstrap/app.php` file: ->withMiddleware(function (Middleware $middleware) { $middleware->validateCsrfTokens(except: [ 'stripe/*', 'http://example.com/foo/bar', 'http://example.com/foo/*', ]); }) > [!NOTE] > For convenience, the CSRF middleware is automatically disabled for all routes when [running tests](/docs/{{version}}/testing). <a name="csrf-x-csrf-token"></a> ## X-CSRF-TOKEN 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 <meta name="csrf-token" content="{{ csrf_token() }}"> ``` Then, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications using legacy JavaScript technology: ```js $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); ``` <a name="csrf-x-xsrf-token"></a> ## X-XSRF-TOKEN Laravel stores the current CSRF token in an encrypted `XSRF-TOKEN` cookie that is included with each response generated by the framework. You can use the cookie value to set the `X-XSRF-TOKEN` request header. 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. > [!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.
243091
## Environment Configuration It is often helpful to have different configuration values based on the environment where the application is running. For example, you may wish to use a different cache driver locally than you do on your production server. 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 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 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. > [!NOTE] > Any variable in your `.env` file can be overridden by external environment variables such as server-level or system-level environment variables. <a name="environment-file-security"></a> #### 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. <a name="additional-environment-files"></a> #### Additional Environment Files 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. <a name="environment-variable-types"></a> ### 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: <div class="overflow-auto"> | `.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 | </div> 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: ```ini APP_NAME="My Application" ``` <a name="retrieving-environment-configuration"></a> ### Retrieving Environment Configuration 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), 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. <a name="determining-the-current-environment"></a> ### 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; $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 } 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. <a name="encrypting-environment-files"></a> ### 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. <a name="encryption"></a> #### 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 ``` <a name="decryption"></a> #### 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 ``` In order to overwrite an existing environment file, you may provide the `--force` option to the `env:decrypt` command: ```shell php artisan env:decrypt --force ``` <a name="accessing-configuration-values"></a> ## Accessing Configuration Values 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: use Illuminate\Support\Facades\Config; $value = Config::get('app.timezone'); $value = config('app.timezone'); // 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::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: Config::string('config-key'); Config::integer('config-key'); Config::float('config-key'); Config::boolean('config-key'); Config::array('config-key'); <a name="configuration-caching"></a>
243092
## Configuration Caching To give your application a speed boost, you should cache all of your configuration files into a single file using the `config:cache` Artisan command. This will combine all of the configuration options for your application into a single file which can be quickly loaded by the framework. 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. 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. <a name="configuration-publishing"></a> ## 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 ``` <a name="debug-mode"></a> ## 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. > [!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.** <a name="maintenance-mode"></a> ## Maintenance Mode When your application is in maintenance mode, a custom view will be displayed for all requests into your application. This makes it easy to "disable" your application while it is updating or when you are performing maintenance. A maintenance mode check is included in the default middleware stack for your application. If the application is in maintenance mode, a `Symfony\Component\HttpKernel\Exception\HttpException` instance will be thrown with a status code of 503. To enable maintenance mode, execute the `down` Artisan command: ```shell php artisan down ``` If you would like the `Refresh` HTTP header to be sent with all maintenance mode responses, you may provide the `refresh` option when invoking the `down` command. The `Refresh` header will instruct the browser to automatically refresh the page after the specified number of seconds: ```shell php artisan down --refresh=15 ``` You may also provide a `retry` option to the `down` command, which will be set as the `Retry-After` HTTP header's value, although browsers generally ignore this header: ```shell php artisan down --retry=60 ``` <a name="bypassing-maintenance-mode"></a> #### Bypassing Maintenance Mode 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" ``` After placing the application in maintenance mode, you may navigate to the application URL matching this token and Laravel will issue a maintenance mode bypass cookie to your browser: ```shell 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. > [!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 `&`. <a name="maintenance-mode-on-multiple-servers"></a> #### 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 "driver" setting in the `config/app.php` file of your application to `cache`. Then, select a cache `store` that is accessible by all your servers. This ensures the maintenance mode status is consistently maintained across every server: ```php 'maintenance' => [ 'driver' => 'cache', 'store' => 'database', ], ``` <a name="pre-rendering-the-maintenance-mode-view"></a> #### 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. For this reason, Laravel allows you to pre-render a maintenance mode view that will be returned at the very beginning of the request cycle. This view is rendered before any of your application's dependencies have loaded. You may pre-render a template of your choice using the `down` command's `render` option: ```shell php artisan down --render="errors::503" ``` <a name="redirecting-maintenance-mode-requests"></a> #### Redirecting Maintenance Mode Requests While in maintenance mode, Laravel will display the maintenance mode view for all application URLs the user attempts to access. If you wish, you may instruct Laravel to redirect all requests to a specific URL. This may be accomplished using the `redirect` option. For example, you may wish to redirect all requests to the `/` URI: ```shell php artisan down --redirect=/ ``` <a name="disabling-maintenance-mode"></a> #### Disabling Maintenance Mode To disable maintenance mode, use the `up` command: ```shell php artisan up ``` > [!NOTE] > You may customize the default maintenance mode template by defining your own template at `resources/views/errors/503.blade.php`. <a name="maintenance-mode-queues"></a> #### 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. <a name="alternatives-to-maintenance-mode"></a> #### 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.
243093
# Logging - [Introduction](#introduction) - [Configuration](#configuration) - [Available Channel Drivers](#available-channel-drivers) - [Channel Prerequisites](#channel-prerequisites) - [Logging Deprecation Warnings](#logging-deprecation-warnings) - [Building Log Stacks](#building-log-stacks) - [Writing Log Messages](#writing-log-messages) - [Contextual Information](#contextual-information) - [Writing to Specific Channels](#writing-to-specific-channels) - [Monolog Channel Customization](#monolog-channel-customization) - [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) - [Tailing Log Messages Using Pail](#tailing-log-messages-using-pail) - [Installation](#pail-installation) - [Usage](#pail-usage) - [Filtering Logs](#pail-filtering-logs) <a name="introduction"></a> ## Introduction To help you learn more about what's happening within your application, Laravel provides robust logging services that allow you to log messages to files, the system error log, and even to Slack to notify your entire team. Laravel logging is based on "channels". Each channel represents a specific way of writing log information. For example, the `single` channel writes log files to a single log file, while the `slack` channel sends log messages to Slack. Log messages may be written to multiple channels based on their severity. Under the hood, Laravel utilizes the [Monolog](https://github.com/Seldaek/monolog) library, which provides support for a variety of powerful log handlers. Laravel makes it a cinch to configure these handlers, allowing you to mix and match them to customize your application's log handling. <a name="configuration"></a> ## Configuration 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). <a name="available-channel-drivers"></a> ### 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: <div class="overflow-auto"> | 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. | </div> > [!NOTE] > Check out the documentation on [advanced channel customization](#monolog-channel-customization) to learn more about the `monolog` and `custom` drivers. <a name="configuring-the-channel-name"></a> #### 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: 'stack' => [ 'driver' => 'stack', 'name' => 'channel-name', 'channels' => ['single', 'slack'], ], <a name="channel-prerequisites"></a> ### Channel Prerequisites <a name="configuring-the-single-and-daily-channels"></a> #### Configuring the Single and Daily Channels The `single` and `daily` channels have three optional configuration options: `bubble`, `permission`, and `locking`. <div class="overflow-auto"> | 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` | </div> 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. <div class="overflow-auto"> | Name | Description | Default | | ------ | ----------------------------------------------------------- | ------- | | `days` | The number of days that daily log files should be retained. | `7` | </div> <a name="configuring-the-papertrail-channel"></a> #### Configuring the Papertrail Channel 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). <a name="configuring-the-slack-channel"></a> #### Configuring the Slack Channel 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 using the `LOG_LEVEL` environment variable or by modifying the `level` configuration option within your Slack log channel's configuration array. <a name="logging-deprecation-warnings"></a> ### 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 using the `LOG_DEPRECATIONS_CHANNEL` environment variable, or within your application's `config/logging.php` configuration file: 'deprecations' => [ 'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), 'trace' => env('LOG_DEPRECATIONS_TRACE', false), ], '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'), ], ], <a name="building-log-stacks"></a>
243094
## 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: ```php 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['syslog', 'slack'], // [tl! add] 'ignore_exceptions' => false, ], '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' => 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". <a name="log-levels"></a> #### 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). 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.'); 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!'); <a name="writing-log-messages"></a> ## 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; 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: <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Models\User; use Illuminate\Support\Facades\Log; use Illuminate\View\View; class UserController extends Controller { /** * Show the profile for the given user. */ public function show(string $id): View { Log::info('Showing the user profile for user: {id}', ['id' => $id]); return view('user.profile', [ 'user' => User::findOrFail($id) ]); } } <a name="contextual-information"></a> ### 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; 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 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: <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\Response; class AssignRequestId { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { $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 namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\Response; class AssignRequestId { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { $requestId = (string) Str::uuid(); Log::shareContext([ 'request-id' => $requestId ]); // ... } } > [!NOTE] > If you need to share log context while processing queued jobs, you may utilize [job middleware](/docs/{{version}}/queues#job-middleware). <a name="writing-to-specific-channels"></a> ### 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; 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!'); <a name="on-demand-channels"></a> #### 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; 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; $channel = Log::build([ 'driver' => 'single', 'path' => storage_path('logs/custom.log'), ]); Log::stack(['slack', $channel])->info('Something happened!'); <a name="monolog-channel-customization"></a>
243095
## Monolog Channel Customization <a name="customizing-monolog-for-channels"></a> ### 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' => 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: <?php namespace App\Logging; use Illuminate\Log\Logger; use Monolog\Formatter\LineFormatter; class CustomizeFormatter { /** * Customize the given logger instance. */ public function __invoke(Logger $logger): void { foreach ($logger->getHandlers() as $handler) { $handler->setFormatter(new LineFormatter( '[%datetime%] %channel%.%level_name%: %message% %context% %extra%' )); } } } > [!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. <a name="creating-monolog-handler-channels"></a> ### 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. 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: 'logentries' => [ 'driver' => 'monolog', 'handler' => Monolog\Handler\SyslogUdpHandler::class, 'with' => [ 'host' => 'my.logentries.internal.datahubhost.company.com', 'port' => '10000', ], ], <a name="monolog-formatters"></a> #### 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', ], ], 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', ], <a name="monolog-processors"></a> #### 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: 'memory' => [ 'driver' => 'monolog', 'handler' => Monolog\Handler\StreamHandler::class, 'with' => [ 'stream' => 'php://stderr', ], 'processors' => [ // Simple syntax... Monolog\Processor\MemoryUsageProcessor::class, // With options... [ 'processor' => Monolog\Processor\PsrLogMessageProcessor::class, 'with' => ['removeUsedContextFields' => true], ], ], ], <a name="creating-custom-channels-via-factories"></a> ### 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, ], ], 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: <?php namespace App\Logging; use Monolog\Logger; class CreateCustomLogger { /** * Create a custom Monolog instance. */ public function __invoke(array $config): Logger { return new Logger(/* ... */); } } <a name="tailing-log-messages-using-pail"></a> ## 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. <img src="https://laravel.com/img/docs/pail-example.png"> <a name="pail-installation"></a> ### Installation > [!WARNING] > Laravel Pail requires [PHP 8.2+](https://php.net/releases/) and the [PCNTL](https://www.php.net/manual/en/book.pcntl.php) extension. To get started, install Pail into your project using the Composer package manager: ```bash composer require laravel/pail ``` <a name="pail-usage"></a> ### Usage To start tailing logs, run the `pail` command: ```bash php artisan pail ``` To increase the verbosity of the output and avoid truncation (…), use the `-v` option: ```bash php artisan pail -v ``` For maximum verbosity and to display exception stack traces, use the `-vv` option: ```bash php artisan pail -vv ``` To stop tailing logs, press `Ctrl+C` at any time. <a name="pail-filtering-logs"></a> ### Filtering Logs <a name="pail-filtering-logs-filter-option"></a> #### `--filter` You may use the `--filter` option to filter logs by their type, file, message, and stack trace content: ```bash php artisan pail --filter="QueryException" ``` <a name="pail-filtering-logs-message-option"></a> #### `--message` To filter logs by only their message, you may use the `--message` option: ```bash php artisan pail --message="User created" ``` <a name="pail-filtering-logs-level-option"></a> #### `--level` The `--level` option may be used to filter logs by their [log level](#log-levels): ```bash php artisan pail --level=error ``` <a name="pail-filtering-logs-user-option"></a> #### `--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: ```bash php artisan pail --user=1 ```
243096
# Database: Seeding - [Introduction](#introduction) - [Writing Seeders](#writing-seeders) - [Using Model Factories](#using-model-factories) - [Calling Additional Seeders](#calling-additional-seeders) - [Muting Model Events](#muting-model-events) - [Running Seeders](#running-seeders) <a name="introduction"></a> ## Introduction Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the `database/seeders` directory. By default, a `DatabaseSeeder` class is defined for you. From this class, you may use the `call` method to run other seed classes, allowing you to control the seeding order. > [!NOTE] > [Mass assignment protection](/docs/{{version}}/eloquent#mass-assignment) is automatically disabled during database seeding. <a name="writing-seeders"></a> ## Writing Seeders To generate a seeder, execute the `make:seeder` [Artisan command](/docs/{{version}}/artisan). All seeders generated by the framework will be placed in the `database/seeders` directory: ```shell php artisan make:seeder UserSeeder ``` A seeder class only contains one method by default: `run`. This method is called when the `db:seed` [Artisan command](/docs/{{version}}/artisan) is executed. Within the `run` method, you may insert data into your database however you wish. You may use the [query builder](/docs/{{version}}/queries) to manually insert data or you may use [Eloquent model factories](/docs/{{version}}/eloquent-factories). As an example, let's modify the default `DatabaseSeeder` class and add a database insert statement to the `run` method: <?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; class DatabaseSeeder extends Seeder { /** * Run the database seeders. */ public function run(): void { DB::table('users')->insert([ 'name' => Str::random(10), 'email' => Str::random(10).'@example.com', 'password' => Hash::make('password'), ]); } } > [!NOTE] > You may type-hint any dependencies you need within the `run` method's signature. They will automatically be resolved via the Laravel [service container](/docs/{{version}}/container). <a name="using-model-factories"></a> ### Using Model Factories Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use [model factories](/docs/{{version}}/eloquent-factories) to conveniently generate large amounts of database records. First, review the [model factory documentation](/docs/{{version}}/eloquent-factories) to learn how to define your factories. For example, let's create 50 users that each has one related post: use App\Models\User; /** * Run the database seeders. */ public function run(): void { User::factory() ->count(50) ->hasPosts(1) ->create(); } <a name="calling-additional-seeders"></a> ### Calling Additional Seeders Within the `DatabaseSeeder` class, you may use the `call` method to execute additional seed classes. Using the `call` method allows you to break up your database seeding into multiple files so that no single seeder class becomes too large. The `call` method accepts an array of seeder classes that should be executed: /** * Run the database seeders. */ public function run(): void { $this->call([ UserSeeder::class, PostSeeder::class, CommentSeeder::class, ]); } <a name="muting-model-events"></a> ### Muting Model Events While running seeds, you may want to prevent models from dispatching events. You may achieve this using the `WithoutModelEvents` trait. When used, the `WithoutModelEvents` trait ensures no model events are dispatched, even if additional seed classes are executed via the `call` method: <?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Database\Console\Seeds\WithoutModelEvents; class DatabaseSeeder extends Seeder { use WithoutModelEvents; /** * Run the database seeders. */ public function run(): void { $this->call([ UserSeeder::class, ]); } } <a name="running-seeders"></a> ## Running Seeders You may execute the `db:seed` Artisan command to seed your database. By default, the `db:seed` command runs the `Database\Seeders\DatabaseSeeder` class, which may in turn invoke other seed classes. However, you may use the `--class` option to specify a specific seeder class to run individually: ```shell php artisan db:seed php artisan db:seed --class=UserSeeder ``` You may also seed your database using the `migrate:fresh` command in combination with the `--seed` option, which will drop all tables and re-run all of your migrations. This command is useful for completely re-building your database. The `--seeder` option may be used to specify a specific seeder to run: ```shell php artisan migrate:fresh --seed php artisan migrate:fresh --seed --seeder=UserSeeder ``` <a name="forcing-seeding-production"></a> #### Forcing Seeders to Run in Production Some seeding operations may cause you to alter or lose data. In order to protect you from running seeding commands against your production database, you will be prompted for confirmation before the seeders are executed in the `production` environment. To force the seeders to run without a prompt, use the `--force` flag: ```shell php artisan db:seed --force ```
243101
## 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. <a name="custom-card-components"></a> ### 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 <x-pulse::card :cols="$cols" :rows="$rows" :class="$class" wire:poll.5s=""> <x-pulse::card-header name="Top Sellers"> <x-slot:icon> ... </x-slot:icon> </x-pulse::card-header> <x-pulse::scroll :expand="$expand"> ... </x-pulse::scroll> </x-pulse::card> ``` 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 <x-pulse> ... <livewire:pulse.top-sellers cols="4" /> </x-pulse> ``` > [!NOTE] > If your card is included in a package, you will need to register the component with Livewire using the `Livewire::component` method. <a name="custom-card-styling"></a> ### 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. <a name="custom-card-styling-vite"></a> #### 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 <x-pulse> @vite('resources/css/pulse/top-sellers.css') ... </x-pulse> ``` <a name="custom-card-styling-css"></a> #### 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 `<style>` tag so it does not need to be published to the `public` directory. <a name="custom-card-styling-tailwind"></a> #### Tailwind CSS When using Tailwind CSS, you should create a dedicated Tailwind configuration file to avoid loading unnecessary CSS or conflicting with Pulse's Tailwind classes: ```js export default { darkMode: 'class', important: '#top-sellers', content: [ './resources/views/livewire/pulse/top-sellers.blade.php', ], corePlugins: { preflight: false, }, }; ``` You may then specify the configuration file in your CSS entrypoint: ```css @config "../../tailwind.top-sellers.config.js"; @tailwind base; @tailwind components; @tailwind utilities; ``` You will also need to include an `id` or `class` attribute in your card's view that matches the selector passed to Tailwind's [`important` selector strategy](https://tailwindcss.com/docs/configuration#selector-strategy): ```blade <x-pulse::card id="top-sellers" :cols="$cols" :rows="$rows" class="$class"> ... </x-pulse::card> ``` <a name="custom-card-data"></a>
243103
# Starter Kits - [Introduction](#introduction) - [Laravel Breeze](#laravel-breeze) - [Installation](#laravel-breeze-installation) - [Breeze and Blade](#breeze-and-blade) - [Breeze and Livewire](#breeze-and-livewire) - [Breeze and React / Vue](#breeze-and-inertia) - [Breeze and Next.js / API](#breeze-and-next) - [Laravel Jetstream](#laravel-jetstream) <a name="introduction"></a> ## Introduction To give you a head start building your new Laravel application, we are happy to offer authentication and application starter kits. These kits automatically scaffold your application with the routes, controllers, and views you need to register and authenticate your application's users. While you are welcome to use these starter kits, they are not required. You are free to build your own application from the ground up by simply installing a fresh copy of Laravel. Either way, we know you will build something great! <a name="laravel-breeze"></a> ## Laravel Breeze [Laravel Breeze](https://github.com/laravel/breeze) is a minimal, simple implementation of all of Laravel's [authentication features](/docs/{{version}}/authentication), including login, registration, password reset, email verification, and password confirmation. In addition, Breeze includes a simple "profile" page where the user may update their name, email address, and password. Laravel Breeze's default view layer is made up of simple [Blade templates](/docs/{{version}}/blade) styled with [Tailwind CSS](https://tailwindcss.com). Additionally, Breeze provides scaffolding options based on [Livewire](https://livewire.laravel.com) or [Inertia](https://inertiajs.com), with the choice of using Vue or React for the Inertia-based scaffolding. <img src="https://laravel.com/img/docs/breeze-register.png"> #### Laravel Bootcamp If you're new to Laravel, feel free to jump into the [Laravel Bootcamp](https://bootcamp.laravel.com). The Laravel Bootcamp will walk you through building your first Laravel application using Breeze. It's a great way to get a tour of everything that Laravel and Breeze have to offer. <a name="laravel-breeze-installation"></a> ### Installation First, you should [create a new Laravel application](/docs/{{version}}/installation). If you create your application using the [Laravel installer](/docs/{{version}}/installation#creating-a-laravel-project), you will be prompted to install Laravel Breeze during the installation process. Otherwise, you will need to follow the manual installation instructions below. If you have already created a new Laravel application without a starter kit, you may manually install Laravel Breeze using Composer: ```shell composer require laravel/breeze --dev ``` After Composer has installed the Laravel Breeze package, you should run the `breeze:install` Artisan command. This command publishes the authentication views, routes, controllers, and other resources to your application. Laravel Breeze publishes all of its code to your application so that you have full control and visibility over its features and implementation. The `breeze:install` command will prompt you for your preferred frontend stack and testing framework: ```shell php artisan breeze:install php artisan migrate npm install npm run dev ``` <a name="breeze-and-blade"></a> ### Breeze and Blade The default Breeze "stack" is the Blade stack, which utilizes simple [Blade templates](/docs/{{version}}/blade) to render your application's frontend. The Blade stack may be installed by invoking the `breeze:install` command with no other additional arguments and selecting the Blade frontend stack. After Breeze's scaffolding is installed, you should also compile your application's frontend assets: ```shell php artisan breeze:install php artisan migrate npm install npm run dev ``` Next, you may navigate to your application's `/login` or `/register` URLs in your web browser. All of Breeze's routes are defined within the `routes/auth.php` file. > [!NOTE] > To learn more about compiling your application's CSS and JavaScript, check out Laravel's [Vite documentation](/docs/{{version}}/vite#running-vite). <a name="breeze-and-livewire"></a> ### Breeze and Livewire Laravel Breeze also offers [Livewire](https://livewire.laravel.com) scaffolding. Livewire is a powerful way of building dynamic, reactive, front-end UIs using just PHP. Livewire is a great fit for teams that primarily use Blade templates and are looking for a simpler alternative to JavaScript-driven SPA frameworks like Vue and React. To use the Livewire stack, you may select the Livewire frontend stack when executing the `breeze:install` Artisan command. After Breeze's scaffolding is installed, you should run your database migrations: ```shell php artisan breeze:install php artisan migrate ``` <a name="breeze-and-inertia"></a> ### Breeze and React / Vue Laravel Breeze also offers React and Vue scaffolding via an [Inertia](https://inertiajs.com) frontend implementation. Inertia allows you to build modern, single-page React and Vue applications using classic server-side routing and controllers. Inertia lets you enjoy the frontend power of React and Vue combined with the incredible backend productivity of Laravel and lightning-fast [Vite](https://vitejs.dev) compilation. To use an Inertia stack, you may select the Vue or React frontend stacks when executing the `breeze:install` Artisan command. When selecting the Vue or React frontend stack, the Breeze installer will also prompt you to determine if you would like [Inertia SSR](https://inertiajs.com/server-side-rendering) or TypeScript support. After Breeze's scaffolding is installed, you should also compile your application's frontend assets: ```shell php artisan breeze:install php artisan migrate npm install npm run dev ``` Next, you may navigate to your application's `/login` or `/register` URLs in your web browser. All of Breeze's routes are defined within the `routes/auth.php` file. <a name="breeze-and-next"></a> ### Breeze and Next.js / API Laravel Breeze can also scaffold an authentication API that is ready to authenticate modern JavaScript applications such as those powered by [Next](https://nextjs.org), [Nuxt](https://nuxt.com), and others. To get started, select the API stack as your desired stack when executing the `breeze:install` Artisan command: ```shell php artisan breeze:install php artisan migrate ``` During installation, Breeze will add a `FRONTEND_URL` environment variable to your application's `.env` file. This URL should be the URL of your JavaScript application. This will typically be `http://localhost:3000` during local development. In addition, you should ensure that your `APP_URL` is set to `http://localhost:8000`, which is the default URL used by the `serve` Artisan command. <a name="next-reference-implementation"></a> #### Next.js Reference Implementation Finally, you are ready to pair this backend with the frontend of your choice. A Next reference implementation of the Breeze frontend is [available on GitHub](https://github.com/laravel/breeze-next). This frontend is maintained by Laravel and contains the same user interface as the traditional Blade and Inertia stacks provided by Breeze. <a name="laravel-jetstream"></a> ## Laravel Jetstream While Laravel Breeze provides a simple and minimal starting point for building a Laravel application, Jetstream augments that functionality with more robust features and additional frontend technology stacks. **For those brand new to Laravel, we recommend learning the ropes with Laravel Breeze before graduating to Laravel Jetstream.** Jetstream provides a beautifully designed application scaffolding for Laravel and includes login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management. Jetstream is designed using [Tailwind CSS](https://tailwindcss.com) and offers your choice of [Livewire](https://livewire.laravel.com) or [Inertia](https://inertiajs.com) driven frontend scaffolding. Complete documentation for installing Laravel Jetstream can be found within the [official Jetstream documentation](https://jetstream.laravel.com).
243112
## Writing Mailables 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. 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. <a name="configuring-the-sender"></a> ### Configuring the Sender <a name="using-the-envelope"></a> #### 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 specify the "from" address on your message's envelope: 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: return new Envelope( from: new Address('jeffrey@example.com', 'Jeffrey Way'), replyTo: [ new Address('taylor@example.com', 'Taylor Otwell'), ], subject: 'Order Shipped', ); <a name="using-a-global-from-address"></a> #### Using a Global `from` Address 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' => 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'], <a name="configuring-the-view"></a> ### 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: /** * Get the message content definition. */ public function content(): Content { return new Content( view: 'mail.orders.shipped', ); } > [!NOTE] > 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. <a name="plain-text-emails"></a> #### Plain Text Emails 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: /** * 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: return new Content( html: 'mail.orders.shipped', text: 'mail.orders.shipped-text' ); <a name="view-data"></a> ### View Data <a name="via-public-properties"></a> #### 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's constructor and set that data to public properties defined on the class: <?php namespace App\Mail; use App\Models\Order; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Queue\SerializesModels; class OrderShipped extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. */ public function __construct( public Order $order, ) {} /** * Get the message content definition. */ public function content(): Content { 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: <div> Price: {{ $order->price }} </div> <a name="via-the-with-parameter"></a> #### Via the `with` Parameter: 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: <?php namespace App\Mail; use App\Models\Order; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Queue\SerializesModels; class OrderShipped extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. */ public function __construct( protected Order $order, ) {} /** * Get the message content definition. */ public function content(): Content { 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: <div> Price: {{ $orderPrice }} </div> <a name="attachments"></a>
243114
### 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: 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/#tagging) and [metadata](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/#attaching-data-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. <a name="customizing-the-symfony-message"></a> ### 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: 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) { // ... }, ] ); } <a name="markdown-mailables"></a> ## Markdown Mailables Markdown mailable messages allow you to take advantage of the pre-built templates and components of [mail notifications](/docs/{{version}}/notifications#mail-notifications) in your mailables. 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. <a name="generating-markdown-mailables"></a> ### Generating Markdown Mailables 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=mail.orders.shipped ``` Then, when configuring the mailable `Content` definition within its `content` method, use the `markdown` parameter instead of the `view` parameter: 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, ], ); } <a name="writing-markdown-messages"></a> ### Writing Markdown Messages 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 <x-mail::message> # Order Shipped Your order has been shipped! <x-mail::button :url="$url"> View Order </x-mail::button> Thanks,<br> {{ config('app.name') }} </x-mail::message> ``` > [!NOTE] > Do not use excess indentation when writing Markdown emails. Per Markdown standards, Markdown parsers will render indented content as code blocks. <a name="button-component"></a> #### 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`, `success`, and `error`. You may add as many button components to a message as you wish: ```blade <x-mail::button :url="$url" color="success"> View Order </x-mail::button> ``` <a name="panel-component"></a> #### Panel Component 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 <x-mail::panel> This is the panel content. </x-mail::panel> ``` <a name="table-component"></a> #### Table Component 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 <x-mail::table> | Laravel | Table | Example | | ------------- | :-----------: | ------------: | | Col 2 is | Centered | $10 | | Col 3 is | Right-Aligned | $20 | </x-mail::table> ``` <a name="customizing-the-components"></a> ### 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: ```shell 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. <a name="customizing-the-css"></a> #### 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. If you would like to build an entirely new theme for Laravel's Markdown components, you may place a CSS file within the `html/themes` directory. After naming and saving your CSS file, update the `theme` option of your application's `config/mail.php` configuration file to match the name of your new theme. To customize the theme for an individual mailable, you may set the `$theme` property of the mailable class to the name of the theme that should be used when sending that mailable. <a name="sending-mail"></a>
243120
## Redirects Redirect responses are instances of the `Illuminate\Http\RedirectResponse` class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a `RedirectResponse` instance. The simplest method is to use the global `redirect` helper: Route::get('/dashboard', function () { return redirect('/home/dashboard'); }); Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global `back` helper function. Since this feature utilizes the [session](/docs/{{version}}/session), make sure the route calling the `back` function is using the `web` middleware group: Route::post('/user/profile', function () { // Validate the request... return back()->withInput(); }); <a name="redirecting-named-routes"></a> ### Redirecting to Named Routes When you call the `redirect` helper with no parameters, an instance of `Illuminate\Routing\Redirector` is returned, allowing you to call any method on the `Redirector` instance. For example, to generate a `RedirectResponse` to a named route, you may use the `route` method: return redirect()->route('login'); If your route has parameters, you may pass them as the second argument to the `route` method: // For a route with the following URI: /profile/{id} return redirect()->route('profile', ['id' => 1]); <a name="populating-parameters-via-eloquent-models"></a> #### Populating Parameters via Eloquent Models If you are redirecting to a route with an "ID" parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically: // For a route with the following URI: /profile/{id} return redirect()->route('profile', [$user]); If you would like to customize the value that is placed in the route parameter, you can specify the column in the route parameter definition (`/profile/{id:slug}`) or you can override the `getRouteKey` method on your Eloquent model: /** * Get the value of the model's route key. */ public function getRouteKey(): mixed { return $this->slug; } <a name="redirecting-controller-actions"></a> ### Redirecting to Controller Actions You may also generate redirects to [controller actions](/docs/{{version}}/controllers). To do so, pass the controller and action name to the `action` method: use App\Http\Controllers\UserController; return redirect()->action([UserController::class, 'index']); If your controller route requires parameters, you may pass them as the second argument to the `action` method: return redirect()->action( [UserController::class, 'profile'], ['id' => 1] ); <a name="redirecting-external-domains"></a> ### Redirecting to External Domains Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the `away` method, which creates a `RedirectResponse` without any additional URL encoding, validation, or verification: return redirect()->away('https://www.google.com'); <a name="redirecting-with-flashed-session-data"></a> ### Redirecting With Flashed Session Data Redirecting to a new URL and [flashing data to the session](/docs/{{version}}/session#flash-data) are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a `RedirectResponse` instance and flash data to the session in a single, fluent method chain: Route::post('/user/profile', function () { // ... return redirect('/dashboard')->with('status', 'Profile updated!'); }); After the user is redirected, you may display the flashed message from the [session](/docs/{{version}}/session). For example, using [Blade syntax](/docs/{{version}}/blade): @if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif <a name="redirecting-with-input"></a> #### Redirecting With Input You may use the `withInput` method provided by the `RedirectResponse` instance to flash the current request's input data to the session before redirecting the user to a new location. This is typically done if the user has encountered a validation error. Once the input has been flashed to the session, you may easily [retrieve it](/docs/{{version}}/requests#retrieving-old-input) during the next request to repopulate the form: return back()->withInput(); <a name="other-response-types"></a>
243121
## Other Response Types The `response` helper may be used to generate other types of response instances. When the `response` helper is called without arguments, an implementation of the `Illuminate\Contracts\Routing\ResponseFactory` [contract](/docs/{{version}}/contracts) is returned. This contract provides several helpful methods for generating responses. <a name="view-responses"></a> ### View Responses If you need control over the response's status and headers but also need to return a [view](/docs/{{version}}/views) as the response's content, you should use the `view` method: return response() ->view('hello', $data, 200) ->header('Content-Type', $type); Of course, if you do not need to pass a custom HTTP status code or custom headers, you may use the global `view` helper function. <a name="json-responses"></a> ### JSON Responses The `json` method will automatically set the `Content-Type` header to `application/json`, as well as convert the given array to JSON using the `json_encode` PHP function: return response()->json([ 'name' => 'Abigail', 'state' => 'CA', ]); If you would like to create a JSONP response, you may use the `json` method in combination with the `withCallback` method: return response() ->json(['name' => 'Abigail', 'state' => 'CA']) ->withCallback($request->input('callback')); <a name="file-downloads"></a> ### File Downloads 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 response()->download($pathToFile); return response()->download($pathToFile, $name, $headers); > [!WARNING] > Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII filename. <a name="file-responses"></a> ### File Responses The `file` method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the absolute path to the file as its first argument and an array of headers as its second argument: return response()->file($pathToFile); return response()->file($pathToFile, $headers); <a name="streamed-responses"></a> ### Streamed Responses By streaming data to the client as it is generated, you can significantly reduce memory usage and improve performance, especially for very large responses. Streamed responses allow the client to begin processing data before the server has finished sending it: function streamedContent(): Generator { yield 'Hello, '; yield 'World!'; } Route::get('/stream', function () { return response()->stream(function (): void { foreach (streamedContent() as $chunk) { echo $chunk; ob_flush(); flush(); sleep(2); // Simulate delay between chunks... } }, 200, ['X-Accel-Buffering' => 'no']); }); > [!NOTE] > Internally, Laravel utilizes PHP's output buffering functionality. As you can see in the example above, you should use the `ob_flush` and `flush` functions to push buffered content to the client. <a name="streamed-json-responses"></a> #### Streamed JSON Responses If you need to stream JSON data incrementally, you may utilize the `streamJson` method. This method is especially useful for large datasets that need to be sent progressively to the browser in a format that can be easily parsed by JavaScript: use App\Models\User; Route::get('/users.json', function () { return response()->streamJson([ 'users' => User::cursor(), ]); }); <a name="streamed-downloads"></a> #### Streamed Downloads Sometimes you may wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the `streamDownload` method in this scenario. This method accepts a callback, filename, and an optional array of headers as its arguments: use App\Services\GitHub; return response()->streamDownload(function () { echo GitHub::api('repo') ->contents() ->readme('laravel', 'laravel')['contents']; }, 'laravel-readme.md'); <a name="response-macros"></a> ## Response Macros If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the `macro` method on the `Response` facade. Typically, you should call this method from the `boot` method of one of your application's [service providers](/docs/{{version}}/providers), such as the `App\Providers\AppServiceProvider` service provider: <?php namespace App\Providers; use Illuminate\Support\Facades\Response; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. */ public function boot(): void { Response::macro('caps', function (string $value) { return Response::make(strtoupper($value)); }); } } The `macro` function accepts a name as its first argument and a closure as its second argument. The macro's closure will be executed when calling the macro name from a `ResponseFactory` implementation or the `response` helper: return response()->caps('foo');
243123
## 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; $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, $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']; In addition to the response methods listed above, the following methods may be used to determine if the response has a given status code: $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 <a name="uri-templates"></a> #### 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' => '11.x', 'topic' => 'validation', ])->get('{+endpoint}/{page}/{version}/{topic}'); ``` <a name="dumping-requests"></a> #### 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'); <a name="request-data"></a> ### 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; $response = Http::post('http://example.com/users', [ 'name' => 'Steve', 'role' => 'Network Administrator', ]); <a name="get-request-query-parameters"></a> #### 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, ]); Alternatively, the `withQueryParameters` method may be used: Http::retry(3, 100)->withQueryParameters([ 'name' => 'Taylor', 'page' => 1, ])->get('http://example.com/users') <a name="sending-form-url-encoded-requests"></a> #### 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', ]); <a name="sending-a-raw-request-body"></a> #### 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'); <a name="multi-part-requests"></a> #### 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, 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', ['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'); $response = Http::attach( 'attachment', $photo, 'photo.jpg' )->post('http://example.com/attachments'); <a name="headers"></a> ### 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', ]); 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'); 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'); 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', ]); ``` <a name="authentication"></a> ### 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(/* ... */); // Digest authentication... $response = Http::withDigestAuth('taylor@laravel.com', 'secret')->post(/* ... */); <a name="bearer-tokens"></a> #### 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(/* ... */); <a name="timeout"></a> ### Timeout 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(/* ... */); 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: $response = Http::connectTimeout(3)->get(/* ... */); <a name="retries"></a>
243124
### Retries 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: $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: 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([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`: 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: 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(/* ... */); > [!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`. <a name="error-handling"></a> ### 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(); // 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 500 level status code... $response->serverError(); // Immediately execute the given callback if there was a client or server error... $response->onError(callable $callback); <a name="throwing-exceptions"></a> #### 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: use Illuminate\Http\Client\Response; $response = Http::post(/* ... */); // Throw an exception if a client or server error occurred... $response->throw(); // 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(); 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: use Illuminate\Http\Client\Response; use Illuminate\Http\Client\RequestException; return Http::post(/* ... */)->throw(function (Response $response, RequestException $e) { // ... })->json(); <a name="guzzle-middleware"></a> ### 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: 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: 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'); <a name="global-middleware"></a> #### 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() )); ``` <a name="guzzle-options"></a> ### Guzzle Options 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: $response = Http::withOptions([ 'debug' => true, ])->get('http://example.com/users'); <a name="global-options"></a> #### 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; /** * Bootstrap any application services. */ public function boot(): void { Http::globalOptions([ 'allow_redirects' => false, ]); } ``` <a name="concurrent-requests"></a>
243128
# Package Development - [Introduction](#introduction) - [A Note on Facades](#a-note-on-facades) - [Package Discovery](#package-discovery) - [Service Providers](#service-providers) - [Resources](#resources) - [Configuration](#configuration) - [Migrations](#migrations) - [Routes](#routes) - [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) <a name="introduction"></a> ## Introduction 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 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 name="a-note-on-facades"></a> ### 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. <a name="package-discovery"></a> ## Package Discovery 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": { "laravel": { "providers": [ "Barryvdh\\Debugbar\\ServiceProvider" ], "aliases": { "Debugbar": "Barryvdh\\Debugbar\\Facade" } } }, ``` 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. <a name="opting-out-of-package-discovery"></a> #### 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: ```json "extra": { "laravel": { "dont-discover": [ "barryvdh/laravel-debugbar" ] } }, ``` You may disable package discovery for all packages using the `*` character inside of your application's `dont-discover` directive: ```json "extra": { "laravel": { "dont-discover": [ "*" ] } }, ``` <a name="service-providers"></a> ## 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 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). <a name="resources"></a>
243129
## Resources <a name="configuration"></a> ### Configuration 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. */ 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'); > [!WARNING] > You should not define closures in your configuration files. They cannot be serialized correctly when users execute the `config:cache` Artisan command. <a name="default-package-configuration"></a> #### Default Package Configuration You may also merge your own package configuration file with the application's published copy. This will allow your users to define only the options they actually want to override in the published copy of the configuration file. To merge the configuration file values, use the `mergeConfigFrom` method within your service provider's `register` method. 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. */ public function register(): void { $this->mergeConfigFrom( __DIR__.'/../config/courier.php', 'courier' ); } > [!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. <a name="routes"></a> ### 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. */ public function boot(): void { $this->loadRoutesFrom(__DIR__.'/../routes/web.php'); } <a name="migrations"></a> ### Migrations 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: /** * Bootstrap any package services. */ public function boot(): void { $this->publishesMigrations([ __DIR__.'/../database/migrations' => database_path('migrations'), ]); } <a name="language-files"></a> ### Language Files 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: /** * Bootstrap any package services. */ public function boot(): void { $this->loadTranslationsFrom(__DIR__.'/../lang', 'courier'); } 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: echo trans('courier::messages.welcome'); 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: ```php /** * Bootstrap any package services. */ public function boot(): void { $this->loadJsonTranslationsFrom(__DIR__.'/../lang'); } ``` <a name="publishing-language-files"></a> #### Publishing Language Files 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. */ public function boot(): void { $this->loadTranslationsFrom(__DIR__.'/../lang', '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 language files will be published to the specified publish location. <a name="views"></a> ### 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. */ 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'); }); <a name="overriding-package-views"></a> #### Overriding Package Views When you use the `loadViewsFrom` method, Laravel actually registers two locations for your views: the application's `resources/views/vendor` directory and the directory you specify. So, using the `courier` package as an example, Laravel will first check if a custom version of the view has been placed in the `resources/views/vendor/courier` directory by the developer. Then, if the view has not been customized, Laravel will search the package view directory you specified in your call to `loadViewsFrom`. This makes it easy for package users to customize / override your package's views. <a name="publishing-views"></a> #### Publishing Views 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. */ 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. <a name="view-components"></a>
243130
### View Components 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: 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 <x-package-alert/> ``` <a name="autoloading-package-components"></a> #### 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: 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 <x-nightshade::calendar /> <x-nightshade::color-picker /> ``` 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. <a name="anonymous-components"></a> #### 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 the [`loadViewsFrom` method](#views)). Then, you may render them by prefixing the component name with the package's view namespace: ```blade <x-courier::alert /> ``` <a name="about-artisan-command"></a> ### "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: use Illuminate\Foundation\Console\AboutCommand; /** * Bootstrap any application services. */ public function boot(): void { AboutCommand::add('My Package', fn () => ['Version' => '1.0.0']); } <a name="commands"></a> ## 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. */ public function boot(): void { if ($this->app->runningInConsole()) { $this->commands([ InstallCommand::class, NetworkCommand::class, ]); } } <a name="optimize-commands"></a> ### 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: /** * Bootstrap any package services. */ public function boot(): void { if ($this->app->runningInConsole()) { $this->optimizes( optimize: 'package:optimize', clear: 'package:clear-optimizations', ); } } <a name="public-assets"></a> ## 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. */ 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: ```shell php artisan vendor:publish --tag=public --force ``` <a name="publishing-file-groups"></a> ## Publishing File Groups 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. */ 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 ```
243133
# Laravel Sail - [Introduction](#introduction) - [Installation and Setup](#installation) - [Installing Sail Into Existing Applications](#installing-sail-into-existing-applications) - [Rebuilding Sail Images](#rebuilding-sail-images) - [Configuring A Shell Alias](#configuring-a-shell-alias) - [Starting and Stopping Sail](#starting-and-stopping-sail) - [Executing Commands](#executing-sail-commands) - [Executing PHP Commands](#executing-php-commands) - [Executing Composer Commands](#executing-composer-commands) - [Executing Artisan Commands](#executing-artisan-commands) - [Executing Node / NPM Commands](#executing-node-npm-commands) - [Interacting With Databases](#interacting-with-sail-databases) - [MySQL](#mysql) - [Redis](#redis) - [Meilisearch](#meilisearch) - [Typesense](#typesense) - [File Storage](#file-storage) - [Running Tests](#running-tests) - [Laravel Dusk](#laravel-dusk) - [Previewing Emails](#previewing-emails) - [Container CLI](#sail-container-cli) - [PHP Versions](#sail-php-versions) - [Node Versions](#sail-node-versions) - [Sharing Your Site](#sharing-your-site) - [Debugging With Xdebug](#debugging-with-xdebug) - [Xdebug CLI Usage](#xdebug-cli-usage) - [Xdebug Browser Usage](#xdebug-browser-usage) - [Customization](#sail-customization) <a name="introduction"></a> ## Introduction [Laravel Sail](https://github.com/laravel/sail) is a light-weight command-line interface for interacting with Laravel's default Docker development environment. Sail provides a great starting point for building a Laravel application using PHP, MySQL, and Redis without requiring prior Docker experience. At its heart, Sail is the `docker-compose.yml` file and the `sail` script that is stored at the root of your project. The `sail` script provides a CLI with convenient methods for interacting with the Docker containers defined by the `docker-compose.yml` file. Laravel Sail is supported on macOS, Linux, and Windows (via [WSL2](https://docs.microsoft.com/en-us/windows/wsl/about)). <a name="installation"></a> ## Installation and Setup Laravel Sail is automatically installed with all new Laravel applications so you may start using it immediately. To learn how to create a new Laravel application, please consult Laravel's [installation documentation](/docs/{{version}}/installation#docker-installation-using-sail) for your operating system. During installation, you will be asked to choose which Sail supported services your application will be interacting with. <a name="installing-sail-into-existing-applications"></a> ### Installing Sail Into Existing Applications If you are interested in using Sail with an existing Laravel application, you may simply install Sail using the Composer package manager. Of course, these steps assume that your existing local development environment allows you to install Composer dependencies: ```shell composer require laravel/sail --dev ``` After Sail has been installed, you may run the `sail:install` Artisan command. This command will publish Sail's `docker-compose.yml` file to the root of your application and modify your `.env` file with the required environment variables in order to connect to the Docker services: ```shell php artisan sail:install ``` Finally, you may start Sail. To continue learning how to use Sail, please continue reading the remainder of this documentation: ```shell ./vendor/bin/sail up ``` > [!WARNING] > If you are using Docker Desktop for Linux, you should use the `default` Docker context by executing the following command: `docker context use default`. <a name="adding-additional-services"></a> #### Adding Additional Services If you would like to add an additional service to your existing Sail installation, you may run the `sail:add` Artisan command: ```shell php artisan sail:add ``` <a name="using-devcontainers"></a> #### Using Devcontainers If you would like to develop within a [Devcontainer](https://code.visualstudio.com/docs/remote/containers), you may provide the `--devcontainer` option to the `sail:install` command. The `--devcontainer` option will instruct the `sail:install` command to publish a default `.devcontainer/devcontainer.json ` file to the root of your application: ```shell php artisan sail:install --devcontainer ``` <a name="rebuilding-sail-images"></a> ### Rebuilding Sail Images Sometimes you may want to completely rebuild your Sail images to ensure all of the image's packages and software are up to date. You may accomplish this using the `build` command: ```shell docker compose down -v sail build --no-cache sail up ``` <a name="configuring-a-shell-alias"></a> ### Configuring A Shell Alias By default, Sail commands are invoked using the `vendor/bin/sail` script that is included with all new Laravel applications: ```shell ./vendor/bin/sail up ``` However, instead of repeatedly typing `vendor/bin/sail` to execute Sail commands, you may wish to configure a shell alias that allows you to execute Sail's commands more easily: ```shell alias sail='sh $([ -f sail ] && echo sail || echo vendor/bin/sail)' ``` To make sure this is always available, you may add this to your shell configuration file in your home directory, such as `~/.zshrc` or `~/.bashrc`, and then restart your shell. Once the shell alias has been configured, you may execute Sail commands by simply typing `sail`. The remainder of this documentation's examples will assume that you have configured this alias: ```shell sail up ``` <a name="starting-and-stopping-sail"></a> ## Starting and Stopping Sail Laravel Sail's `docker-compose.yml` file defines a variety of Docker containers that work together to help you build Laravel applications. Each of these containers is an entry within the `services` configuration of your `docker-compose.yml` file. The `laravel.test` container is the primary application container that will be serving your application. Before starting Sail, you should ensure that no other web servers or databases are running on your local computer. To start all of the Docker containers defined in your application's `docker-compose.yml` file, you should execute the `up` command: ```shell sail up ``` To start all of the Docker containers in the background, you may start Sail in "detached" mode: ```shell sail up -d ``` Once the application's containers have been started, you may access the project in your web browser at: http://localhost. To stop all of the containers, you may simply press Control + C to stop the container's execution. Or, if the containers are running in the background, you may use the `stop` command: ```shell sail stop ``` <a name="executing-sail-commands"></a>
243134
## Executing Commands When using Laravel Sail, your application is executing within a Docker container and is isolated from your local computer. However, Sail provides a convenient way to run various commands against your application such as arbitrary PHP commands, Artisan commands, Composer commands, and Node / NPM commands. **When reading the Laravel documentation, you will often see references to Composer, Artisan, and Node / NPM commands that do not reference Sail.** Those examples assume that these tools are installed on your local computer. If you are using Sail for your local Laravel development environment, you should execute those commands using Sail: ```shell # Running Artisan commands locally... php artisan queue:work # Running Artisan commands within Laravel Sail... sail artisan queue:work ``` <a name="executing-php-commands"></a> ### Executing PHP Commands PHP commands may be executed using the `php` command. Of course, these commands will execute using the PHP version that is configured for your application. To learn more about the PHP versions available to Laravel Sail, consult the [PHP version documentation](#sail-php-versions): ```shell sail php --version sail php script.php ``` <a name="executing-composer-commands"></a> ### Executing Composer Commands Composer commands may be executed using the `composer` command. Laravel Sail's application container includes a Composer installation: ```shell sail composer require laravel/sanctum ``` <a name="installing-composer-dependencies-for-existing-projects"></a> #### Installing Composer Dependencies for Existing Applications If you are developing an application with a team, you may not be the one that initially creates the Laravel application. Therefore, none of the application's Composer dependencies, including Sail, will be installed after you clone the application's repository to your local computer. You may install the application's dependencies by navigating to the application's directory and executing the following command. This command uses a small Docker container containing PHP and Composer to install the application's dependencies: ```shell docker run --rm \ -u "$(id -u):$(id -g)" \ -v "$(pwd):/var/www/html" \ -w /var/www/html \ laravelsail/php83-composer:latest \ composer install --ignore-platform-reqs ``` When using the `laravelsail/phpXX-composer` image, you should use the same version of PHP that you plan to use for your application (`80`, `81`, `82`, or `83`). <a name="executing-artisan-commands"></a> ### Executing Artisan Commands Laravel Artisan commands may be executed using the `artisan` command: ```shell sail artisan queue:work ``` <a name="executing-node-npm-commands"></a> ### Executing Node / NPM Commands Node commands may be executed using the `node` command while NPM commands may be executed using the `npm` command: ```shell sail node --version sail npm run dev ``` If you wish, you may use Yarn instead of NPM: ```shell sail yarn ``` <a name="interacting-with-sail-databases"></a> ## Interacting With Databases <a name="mysql"></a> ### MySQL As you may have noticed, your application's `docker-compose.yml` file contains an entry for a MySQL container. This container uses a [Docker volume](https://docs.docker.com/storage/volumes/) so that the data stored in your database is persisted even when stopping and restarting your containers. In addition, the first time the MySQL container starts, it will create two databases for you. The first database is named using the value of your `DB_DATABASE` environment variable and is for your local development. The second is a dedicated testing database named `testing` and will ensure that your tests do not interfere with your development data. Once you have started your containers, you may connect to the MySQL instance within your application by setting your `DB_HOST` environment variable within your application's `.env` file to `mysql`. To connect to your application's MySQL database from your local machine, you may use a graphical database management application such as [TablePlus](https://tableplus.com). By default, the MySQL database is accessible at `localhost` port 3306 and the access credentials correspond to the values of your `DB_USERNAME` and `DB_PASSWORD` environment variables. Or, you may connect as the `root` user, which also utilizes the value of your `DB_PASSWORD` environment variable as its password. <a name="redis"></a> ### Redis Your application's `docker-compose.yml` file also contains an entry for a [Redis](https://redis.io) container. This container uses a [Docker volume](https://docs.docker.com/storage/volumes/) so that the data stored in your Redis data is persisted even when stopping and restarting your containers. Once you have started your containers, you may connect to the Redis instance within your application by setting your `REDIS_HOST` environment variable within your application's `.env` file to `redis`. To connect to your application's Redis database from your local machine, you may use a graphical database management application such as [TablePlus](https://tableplus.com). By default, the Redis database is accessible at `localhost` port 6379. <a name="meilisearch"></a> ### Meilisearch If you chose to install the [Meilisearch](https://www.meilisearch.com) service when installing Sail, your application's `docker-compose.yml` file will contain an entry for this powerful search engine that is integrated with [Laravel Scout](/docs/{{version}}/scout). Once you have started your containers, you may connect to the Meilisearch instance within your application by setting your `MEILISEARCH_HOST` environment variable to `http://meilisearch:7700`. From your local machine, you may access Meilisearch's web based administration panel by navigating to `http://localhost:7700` in your web browser. <a name="typesense"></a> ### Typesense If you chose to install the [Typesense](https://typesense.org) service when installing Sail, your application's `docker-compose.yml` file will contain an entry for this lightning fast, open-source search engine that is natively integrated with [Laravel Scout](/docs/{{version}}/scout#typesense). Once you have started your containers, you may connect to the Typesense instance within your application by setting the following environment variables: ```ini TYPESENSE_HOST=typesense TYPESENSE_PORT=8108 TYPESENSE_PROTOCOL=http TYPESENSE_API_KEY=xyz ``` From your local machine, you may access Typesense's API via `http://localhost:8108`. <a name="file-storage"></a> ## File Storage If you plan to use Amazon S3 to store files while running your application in its production environment, you may wish to install the [MinIO](https://min.io) service when installing Sail. MinIO provides an S3 compatible API that you may use to develop locally using Laravel's `s3` file storage driver without creating "test" storage buckets in your production S3 environment. If you choose to install MinIO while installing Sail, a MinIO configuration section will be added to your application's `docker-compose.yml` file. By default, your application's `filesystems` configuration file already 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 by simply modifying the associated environment variables that control its configuration. For example, when using MinIO, your filesystem environment variable configuration should be defined as follows: ```ini FILESYSTEM_DISK=s3 AWS_ACCESS_KEY_ID=sail AWS_SECRET_ACCESS_KEY=password AWS_DEFAULT_REGION=us-east-1 AWS_BUCKET=local AWS_ENDPOINT=http://minio:9000 AWS_USE_PATH_STYLE_ENDPOINT=true ``` 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: ```ini AWS_URL=http://localhost:9000/local ``` You may create buckets via the MinIO console, which is available at `http://localhost:8900`. The default username for the MinIO console is `sail` while the default password is `password`. > [!WARNING] > Generating temporary storage URLs via the `temporaryUrl` method is not supported when using MinIO. <a name="running-tests"></a>
243135
## Running Tests Laravel provides amazing testing support out of the box, and you may use Sail's `test` command to run your applications [feature and unit tests](/docs/{{version}}/testing). Any CLI options that are accepted by Pest / PHPUnit may also be passed to the `test` command: ```shell sail test sail test --group orders ``` The Sail `test` command is equivalent to running the `test` Artisan command: ```shell sail artisan test ``` By default, Sail will create a dedicated `testing` database so that your tests do not interfere with the current state of your database. In a default Laravel installation, Sail will also configure your `phpunit.xml` file to use this database when executing your tests: ```xml <env name="DB_DATABASE" value="testing"/> ``` <a name="laravel-dusk"></a> ### Laravel Dusk [Laravel Dusk](/docs/{{version}}/dusk) provides an expressive, easy-to-use browser automation and testing API. Thanks to Sail, you may run these tests without ever installing Selenium or other tools on your local computer. To get started, uncomment the Selenium service in your application's `docker-compose.yml` file: ```yaml selenium: image: 'selenium/standalone-chrome' extra_hosts: - 'host.docker.internal:host-gateway' volumes: - '/dev/shm:/dev/shm' networks: - sail ``` Next, ensure that the `laravel.test` service in your application's `docker-compose.yml` file has a `depends_on` entry for `selenium`: ```yaml depends_on: - mysql - redis - selenium ``` Finally, you may run your Dusk test suite by starting Sail and running the `dusk` command: ```shell sail dusk ``` <a name="selenium-on-apple-silicon"></a> #### Selenium on Apple Silicon If your local machine contains an Apple Silicon chip, your `selenium` service must use the `selenium/standalone-chromium` image: ```yaml selenium: image: 'selenium/standalone-chromium' extra_hosts: - 'host.docker.internal:host-gateway' volumes: - '/dev/shm:/dev/shm' networks: - sail ``` <a name="previewing-emails"></a> ## Previewing Emails Laravel Sail's default `docker-compose.yml` file contains a service entry for [Mailpit](https://github.com/axllent/mailpit). Mailpit intercepts emails sent by your application during local development and provides a convenient web interface so that you can preview your email messages in your browser. When using Sail, Mailpit's default host is `mailpit` and is available via port 1025: ```ini MAIL_HOST=mailpit MAIL_PORT=1025 MAIL_ENCRYPTION=null ``` When Sail is running, you may access the Mailpit web interface at: http://localhost:8025 <a name="sail-container-cli"></a> ## Container CLI Sometimes you may wish to start a Bash session within your application's container. You may use the `shell` command to connect to your application's container, allowing you to inspect its files and installed services as well as execute arbitrary shell commands within the container: ```shell sail shell sail root-shell ``` To start a new [Laravel Tinker](https://github.com/laravel/tinker) session, you may execute the `tinker` command: ```shell sail tinker ``` <a name="sail-php-versions"></a> ## PHP Versions Sail currently supports serving your application via PHP 8.3, 8.2, 8.1, or PHP 8.0. The default PHP version used by Sail is currently PHP 8.3. To change the PHP version that is used to serve your application, you should update the `build` definition of the `laravel.test` container in your application's `docker-compose.yml` file: ```yaml # PHP 8.3 context: ./vendor/laravel/sail/runtimes/8.3 # PHP 8.2 context: ./vendor/laravel/sail/runtimes/8.2 # PHP 8.1 context: ./vendor/laravel/sail/runtimes/8.1 # PHP 8.0 context: ./vendor/laravel/sail/runtimes/8.0 ``` In addition, you may wish to update your `image` name to reflect the version of PHP being used by your application. This option is also defined in your application's `docker-compose.yml` file: ```yaml image: sail-8.2/app ``` After updating your application's `docker-compose.yml` file, you should rebuild your container images: ```shell sail build --no-cache sail up ``` <a name="sail-node-versions"></a> ## Node Versions Sail installs Node 20 by default. To change the Node version that is installed when building your images, you may update the `build.args` definition of the `laravel.test` service in your application's `docker-compose.yml` file: ```yaml build: args: WWWGROUP: '${WWWGROUP}' NODE_VERSION: '18' ``` After updating your application's `docker-compose.yml` file, you should rebuild your container images: ```shell sail build --no-cache sail up ``` <a name="sharing-your-site"></a> ## Sharing Your Site Sometimes you may need to share your site publicly in order to preview your site for a colleague or to test webhook integrations with your application. To share your site, you may use the `share` command. After executing this command, you will be issued a random `laravel-sail.site` URL that you may use to access your application: ```shell sail share ``` When sharing your site via the `share` command, you should configure your application's trusted proxies using the `trustProxies` middleware method in your application's `bootstrap/app.php` file. Otherwise, URL generation helpers such as `url` and `route` will be unable to determine the correct HTTP host that should be used during URL generation: ->withMiddleware(function (Middleware $middleware) { $middleware->trustProxies(at: '*'); }) If you would like to choose the subdomain for your shared site, you may provide the `subdomain` option when executing the `share` command: ```shell sail share --subdomain=my-sail-site ``` > [!NOTE] > The `share` command is powered by [Expose](https://github.com/beyondcode/expose), an open source tunneling service by [BeyondCode](https://beyondco.de). <a name="debugging-with-xdebug"></a>
243137
# Blade Templates - [Introduction](#introduction) - [Supercharging Blade With Livewire](#supercharging-blade-with-livewire) - [Displaying Data](#displaying-data) - [HTML Entity Encoding](#html-entity-encoding) - [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) - [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) - [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) - [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) - [Forms](#forms) - [CSRF Field](#csrf-field) - [Method Field](#method-field) - [Validation Errors](#validation-errors) - [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) <a name="introduction"></a> ## Introduction 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 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']); }); <a name="supercharging-blade-with-livewire"></a> ### Supercharging Blade With Livewire 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. <a name="displaying-data"></a> ## 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']); }); You may display the contents of the `name` variable like so: ```blade Hello, {{ $name }}. ``` > [!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: ```blade The current UNIX timestamp is {{ time() }}. ``` <a name="html-entity-encoding"></a> ### HTML Entity Encoding 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`: <?php namespace App\Providers; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. */ public function boot(): void { Blade::withoutDoubleEncoding(); } } <a name="displaying-unescaped-data"></a> #### Displaying Unescaped Data By default, Blade `{{ }}` statements are automatically sent through PHP's `htmlspecialchars` function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax: ```blade Hello, {!! $name !!}. ``` > [!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. <a name="blade-and-javascript-frameworks"></a> ### 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: ```blade <h1>Laravel</h1> Hello, @{{ name }}. ``` In this example, the `@` symbol will be removed by Blade; however, `{{ name }}` expression will remain untouched by the Blade engine, allowing it to be rendered by your JavaScript framework. The `@` symbol may also be used to escape Blade directives: ```blade {{-- Blade template --}} @@if() <!-- HTML output --> @if() ``` <a name="rendering-json"></a> #### Rendering JSON 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 <script> var app = <?php echo json_encode($array); ?>; </script> ``` 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: ```blade <script> var app = {{ Illuminate\Support\Js::from($array) }}; </script> ``` The latest versions of the Laravel application skeleton include a `Js` facade, which provides convenient access to this functionality within your Blade templates: ```blade <script> var app = {{ Js::from($array) }}; </script> ``` > [!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. <a name="the-at-verbatim-directive"></a> #### The `@verbatim` Directive If you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the `@verbatim` directive so that you do not have to prefix each Blade echo statement with an `@` symbol: ```blade @verbatim <div class="container"> Hello, {{ name }}. </div> @endverbatim ``` <a name="blade-directives"></a>
243138
## Blade Directives In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures while also remaining familiar to their PHP counterparts. <a name="if-statements"></a> ### If Statements You may construct `if` statements using the `@if`, `@elseif`, `@else`, and `@endif` directives. These directives function identically to their PHP counterparts: ```blade @if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif ``` For convenience, Blade also provides an `@unless` directive: ```blade @unless (Auth::check()) You are not signed in. @endunless ``` In addition to the conditional directives already discussed, the `@isset` and `@empty` directives may be used as convenient shortcuts for their respective PHP functions: ```blade @isset($records) // $records is defined and is not null... @endisset @empty($records) // $records is "empty"... @endempty ``` <a name="authentication-directives"></a> #### Authentication Directives The `@auth` and `@guest` directives may be used to quickly determine if the current user is [authenticated](/docs/{{version}}/authentication) or is a guest: ```blade @auth // The user is authenticated... @endauth @guest // The user is not authenticated... @endguest ``` If needed, you may specify the authentication guard that should be checked when using the `@auth` and `@guest` directives: ```blade @auth('admin') // The user is authenticated... @endauth @guest('admin') // The user is not authenticated... @endguest ``` <a name="environment-directives"></a> #### Environment Directives You may check if the application is running in the production environment using the `@production` directive: ```blade @production // Production specific content... @endproduction ``` Or, you may determine if the application is running in a specific environment using the `@env` directive: ```blade @env('staging') // The application is running in "staging"... @endenv @env(['staging', 'production']) // The application is running in "staging" or "production"... @endenv ``` <a name="section-directives"></a> #### Section Directives You may determine if a template inheritance section has content using the `@hasSection` directive: ```blade @hasSection('navigation') <div class="pull-right"> @yield('navigation') </div> <div class="clearfix"></div> @endif ``` You may use the `sectionMissing` directive to determine if a section does not have content: ```blade @sectionMissing('navigation') <div class="pull-right"> @include('default-navigation') </div> @endif ``` <a name="session-directives"></a> #### 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') <div class="p-4 bg-green-100"> {{ $value }} </div> @endsession ``` <a name="switch-statements"></a> ### Switch Statements Switch statements can be constructed using the `@switch`, `@case`, `@break`, `@default` and `@endswitch` directives: ```blade @switch($i) @case(1) First case... @break @case(2) Second case... @break @default Default case... @endswitch ``` <a name="loops"></a> ### Loops In addition to conditional statements, Blade provides simple directives for working with PHP's loop structures. Again, each of these directives functions identically to their PHP counterparts: ```blade @for ($i = 0; $i < 10; $i++) The current value is {{ $i }} @endfor @foreach ($users as $user) <p>This is user {{ $user->id }}</p> @endforeach @forelse ($users as $user) <li>{{ $user->name }}</li> @empty <p>No users</p> @endforelse @while (true) <p>I'm looping forever.</p> @endwhile ``` > [!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 skip the current iteration or end the loop using the `@continue` and `@break` directives: ```blade @foreach ($users as $user) @if ($user->type == 1) @continue @endif <li>{{ $user->name }}</li> @if ($user->number == 5) @break @endif @endforeach ``` You may also include the continuation or break condition within the directive declaration: ```blade @foreach ($users as $user) @continue($user->type == 1) <li>{{ $user->name }}</li> @break($user->number == 5) @endforeach ``` <a name="the-loop-variable"></a> ### The Loop Variable While iterating through a `foreach` loop, a `$loop` variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop: ```blade @foreach ($users as $user) @if ($loop->first) This is the first iteration. @endif @if ($loop->last) This is the last iteration. @endif <p>This is user {{ $user->id }}</p> @endforeach ``` If you are in a nested loop, you may access the parent loop's `$loop` variable via the `parent` property: ```blade @foreach ($users as $user) @foreach ($user->posts as $post) @if ($loop->parent->first) This is the first iteration of the parent loop. @endif @endforeach @endforeach ``` The `$loop` variable also contains a variety of other useful properties: <div class="overflow-auto"> | 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. | </div> <a name="conditional-classes"></a> ### 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: ```blade @php $isActive = false; $hasError = true; @endphp <span @class([ 'p-4', 'font-bold' => $isActive, 'text-gray-500' => ! $isActive, 'bg-red' => $hasError, ])></span> <span class="p-4 text-gray-500 bg-red"></span> ``` Likewise, the `@style` directive may be used to conditionally add inline CSS styles to an HTML element: ```blade @php $isActive = true; @endphp <span @style([ 'background-color: red', 'font-weight: bold' => $isActive, ])></span> <span style="background-color: red; font-weight: bold;"></span> ``` <a name="additional-attributes"></a>
243139
### 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 <input type="checkbox" name="active" value="active" @checked(old('active', $user->active)) /> ``` Likewise, the `@selected` directive may be used to indicate if a given select option should be "selected": ```blade <select name="version"> @foreach ($product->versions as $version) <option value="{{ $version }}" @selected(old('version') == $version)> {{ $version }} </option> @endforeach </select> ``` Additionally, the `@disabled` directive may be used to indicate if a given element should be "disabled": ```blade <button type="submit" @disabled($errors->isNotEmpty())>Submit</button> ``` Moreover, the `@readonly` directive may be used to indicate if a given element should be "readonly": ```blade <input type="email" name="email" value="email@laravel.com" @readonly($user->isNotAdmin()) /> ``` In addition, the `@required` directive may be used to indicate if a given element should be "required": ```blade <input type="text" name="title" value="title" @required($user->isAdmin()) /> ``` <a name="including-subviews"></a> ### Including Subviews > [!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: ```blade <div> @include('shared.errors') <form> <!-- Form Contents --> </form> </div> ``` Even though the included view will inherit all data available in the parent view, you may also pass an array of additional data that should be made available to the included view: ```blade @include('view.name', ['status' => 'complete']) ``` If you attempt to `@include` a view which does not exist, Laravel will throw an error. If you would like to include a view that may or may not be present, you should use the `@includeIf` directive: ```blade @includeIf('view.name', ['status' => 'complete']) ``` If you would like to `@include` a view if a given boolean expression evaluates to `true` or `false`, you may use the `@includeWhen` and `@includeUnless` directives: ```blade @includeWhen($boolean, 'view.name', ['status' => 'complete']) @includeUnless($boolean, 'view.name', ['status' => 'complete']) ``` To include the first view that exists from a given array of views, you may use the `includeFirst` directive: ```blade @includeFirst(['custom.admin', 'admin'], ['status' => 'complete']) ``` > [!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. <a name="rendering-views-for-collections"></a> #### Rendering Views for Collections You may combine loops and includes into one line with Blade's `@each` directive: ```blade @each('view.name', $jobs, 'job') ``` The `@each` directive's first argument is the view to render for each element in the array or collection. The second argument is the array or collection you wish to iterate over, while the third argument is the variable name that will be assigned to the current iteration within the view. So, for example, if you are iterating over an array of `jobs`, typically you will want to access each job as a `job` variable within the view. The array key for the current iteration will be available as the `key` variable within the view. You may also pass a fourth argument to the `@each` directive. This argument determines the view that will be rendered if the given array is empty. ```blade @each('view.name', $jobs, 'job', 'view.empty') ``` > [!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. <a name="the-once-directive"></a> ### The `@once` Directive The `@once` directive allows you to define a portion of the template that will only be evaluated once per rendering cycle. This may be useful for pushing a given piece of JavaScript into the page's header using [stacks](#stacks). For example, if you are rendering a given [component](#components) within a loop, you may wish to only push the JavaScript to the header the first time the component is rendered: ```blade @once @push('scripts') <script> // Your custom JavaScript... </script> @endpush @endonce ``` Since the `@once` directive is often used in conjunction with the `@push` or `@prepend` directives, the `@pushOnce` and `@prependOnce` directives are available for your convenience: ```blade @pushOnce('scripts') <script> // Your custom JavaScript... </script> @endPushOnce ``` <a name="raw-php"></a> ### Raw PHP In some situations, it's useful to embed PHP code into your views. You can use the Blade `@php` directive to execute a block of plain PHP within your template: ```blade @php $counter = 1; @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: ```php @use('App\Models\Flight', 'FlightModel') ``` <a name="comments"></a> ### Comments Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application: ```blade {{-- This comment will not be present in the rendered HTML --}} ``` <a name="components"></a>
243141
### 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: ```blade <x-alert type="error" :message="$message"/> ``` 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: <?php namespace App\View\Components; use Illuminate\View\Component; use Illuminate\View\View; class Alert extends Component { /** * Create the component instance. */ public function __construct( public string $type, public string $message, ) {} /** * Get the view / contents that represent the component. */ public function render(): View { 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: ```blade <div class="alert alert-{{ $type }}"> {{ $message }} </div> ``` <a name="casing"></a> #### Casing 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. */ public function __construct( public string $alertType, ) {} The `$alertType` argument may be provided to the component like so: ```blade <x-alert alert-type="danger" /> ``` <a name="short-attribute-syntax"></a> #### 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... --}} <x-profile :$userId :$name /> {{-- Is equivalent to... --}} <x-profile :user-id="$userId" :name="$name" /> ``` <a name="escaping-attribute-rendering"></a> #### Escaping Attribute Rendering Since some JavaScript frameworks such as Alpine.js also use colon-prefixed attributes, you may use a double colon (`::`) prefix to inform Blade that the attribute is not a PHP expression. For example, given the following component: ```blade <x-button ::class="{ danger: isDeleting }"> Submit </x-button> ``` The following HTML will be rendered by Blade: ```blade <button :class="{ danger: isDeleting }"> Submit </button> ``` <a name="component-methods"></a> #### Component Methods 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. */ 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 <option {{ $isSelected($value) ? 'selected' : '' }} value="{{ $value }}"> {{ $label }} </option> ``` <a name="using-attributes-slots-within-component-class"></a> #### 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: use Closure; /** * Get the view / contents that represent the component. */ public function render(): Closure { return function () { return '<div {{ $attributes }}>Components content</div>'; }; } 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: return function (array $data) { // $data['componentName']; // $data['attributes']; // $data['slot']; return '<div {{ $attributes }}>Components content</div>'; } > [!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 `<x-alert />`'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. The closure should return a string. If the returned string corresponds to an existing view, that view will be rendered; otherwise, the returned string will be evaluated as an inline Blade view. <a name="additional-dependencies"></a> #### Additional Dependencies If your component requires dependencies from Laravel's [service container](/docs/{{version}}/container), you may list them before any of the component's data attributes and they will automatically be injected by the container: ```php use App\Services\AlertCreator; /** * Create the component instance. */ public function __construct( public AlertCreator $creator, public string $type, public string $message, ) {} ``` <a name="hiding-attributes-and-methods"></a> #### Hiding Attributes / Methods 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: <?php namespace App\View\Components; use Illuminate\View\Component; class Alert extends Component { /** * The properties / methods that should not be exposed to the component template. * * @var array */ protected $except = ['type']; /** * Create the component instance. */ public function __construct( public string $type, ) {} } <a name="component-attributes"></a>
243142
### Component Attributes We've already examined how to pass data attributes to a component; however, sometimes you may need to specify additional HTML attributes, such as `class`, that are not part of the data required for a component to function. Typically, you want to pass these additional attributes down to the root element of the component template. For example, imagine we want to render an `alert` component like so: ```blade <x-alert type="error" :message="$message" class="mt-4"/> ``` All of the attributes that are not part of the component's constructor will automatically be added to the component's "attribute bag". This attribute bag is automatically made available to the component via the `$attributes` variable. All of the attributes may be rendered within the component by echoing this variable: ```blade <div {{ $attributes }}> <!-- Component content --> </div> ``` > [!WARNING] > Using directives such as `@env` within component tags is not supported at this time. For example, `<x-alert :live="@env('production')"/>` will not be compiled. <a name="default-merged-attributes"></a> #### Default / Merged Attributes Sometimes you may need to specify default values for attributes or merge additional values into some of the component's attributes. To accomplish this, you may use the attribute bag's `merge` method. This method is particularly useful for defining a set of default CSS classes that should always be applied to a component: ```blade <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}> {{ $message }} </div> ``` If we assume this component is utilized like so: ```blade <x-alert type="error" :message="$message" class="mb-4"/> ``` The final, rendered HTML of the component will appear like the following: ```blade <div class="alert alert-error mb-4"> <!-- Contents of the $message variable --> </div> ``` <a name="conditionally-merge-classes"></a> #### Conditionally Merge Classes Sometimes you may wish to merge classes if a given condition is `true`. You can accomplish this via the `class` method, which 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: ```blade <div {{ $attributes->class(['p-4', 'bg-red' => $hasError]) }}> {{ $message }} </div> ``` If you need to merge other attributes onto your component, you can chain the `merge` method onto the `class` method: ```blade <button {{ $attributes->class(['p-4'])->merge(['type' => 'button']) }}> {{ $slot }} </button> ``` > [!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). <a name="non-class-attribute-merging"></a> #### Non-Class Attribute Merging When merging attributes that are not `class` attributes, the values provided to the `merge` method will be considered the "default" values of the attribute. However, unlike the `class` attribute, these attributes will not be merged with injected attribute values. Instead, they will be overwritten. For example, a `button` component's implementation may look like the following: ```blade <button {{ $attributes->merge(['type' => 'button']) }}> {{ $slot }} </button> ``` To render the button component with a custom `type`, it may be specified when consuming the component. If no type is specified, the `button` type will be used: ```blade <x-button type="submit"> Submit </x-button> ``` The rendered HTML of the `button` component in this example would be: ```blade <button type="submit"> Submit </button> ``` If you would like an attribute other than `class` to have its default value and injected values joined together, you may use the `prepends` method. In this example, the `data-controller` attribute will always begin with `profile-controller` and any additional injected `data-controller` values will be placed after this default value: ```blade <div {{ $attributes->merge(['data-controller' => $attributes->prepends('profile-controller')]) }}> {{ $slot }} </div> ``` <a name="filtering-attributes"></a> #### 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 (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: ```blade {{ $attributes->whereStartsWith('wire:model') }} ``` Conversely, the `whereDoesntStartWith` method may be used to exclude all attributes whose keys begin with a given string: ```blade {{ $attributes->whereDoesntStartWith('wire:model') }} ``` Using the `first` method, you may render the first attribute in a given attribute bag: ```blade {{ $attributes->whereStartsWith('wire:model')->first() }} ``` If you would like to check if an attribute is present on the component, you may use the `has` method. This method accepts the attribute name as its only argument and returns a boolean indicating whether or not the attribute is present: ```blade @if ($attributes->has('class')) <div>Class attribute is present</div> @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'])) <div>All of the attributes are present</div> @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'])) <div>One of the attributes is present</div> @endif ``` You may retrieve a specific attribute's value using the `get` method: ```blade {{ $attributes->get('class') }} ``` <a name="reserved-keywords"></a> ### Reserved Keywords By default, some keywords are reserved for Blade's internal use in order to render components. The following keywords cannot be defined as public properties or method names within your components: <div class="content-list" markdown="1"> - `data` - `render` - `resolveView` - `shouldRender` - `view` - `withAttributes` - `withName` </div> <a name="slots"></a>
243143
### Slots You will often need to pass additional content to your component via "slots". Component slots are rendered by echoing the `$slot` variable. To explore this concept, let's imagine that an `alert` component has the following markup: ```blade <!-- /resources/views/components/alert.blade.php --> <div class="alert alert-danger"> {{ $slot }} </div> ``` We may pass content to the `slot` by injecting content into the component: ```blade <x-alert> <strong>Whoops!</strong> Something went wrong! </x-alert> ``` Sometimes a component may need to render multiple different slots in different locations within the component. Let's modify our alert component to allow for the injection of a "title" slot: ```blade <!-- /resources/views/components/alert.blade.php --> <span class="alert-title">{{ $title }}</span> <div class="alert alert-danger"> {{ $slot }} </div> ``` You may define the content of the named slot using the `x-slot` tag. Any content not within an explicit `x-slot` tag will be passed to the component in the `$slot` variable: ```xml <x-alert> <x-slot:title> Server Error </x-slot> <strong>Whoops!</strong> Something went wrong! </x-alert> ``` You may invoke a slot's `isEmpty` method to determine if the slot contains content: ```blade <span class="alert-title">{{ $title }}</span> <div class="alert alert-danger"> @if ($slot->isEmpty()) This is default content if the slot is empty. @else {{ $slot }} @endif </div> ``` 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 ``` <a name="scoped-slots"></a> #### Scoped Slots If you have used a JavaScript framework such as Vue, you may be familiar with "scoped slots", which allow you to access data or methods from the component within your slot. You may achieve similar behavior in Laravel by defining public methods or properties on your component and accessing the component within your slot via the `$component` variable. In this example, we will assume that the `x-alert` component has a public `formatAlert` method defined on its component class: ```blade <x-alert> <x-slot:title> {{ $component->formatAlert('Server Error') }} </x-slot> <strong>Whoops!</strong> Something went wrong! </x-alert> ``` <a name="slot-attributes"></a> #### Slot Attributes Like Blade components, you may assign additional [attributes](#component-attributes) to slots such as CSS class names: ```xml <x-card class="shadow-sm"> <x-slot:heading class="font-bold"> Heading </x-slot> Content <x-slot:footer class="text-sm"> Footer </x-slot> </x-card> ``` To interact with slot attributes, you may access the `attributes` property of the slot's variable. For more information on how to interact with attributes, please consult the documentation on [component attributes](#component-attributes): ```blade @props([ 'heading', 'footer', ]) <div {{ $attributes->class(['border']) }}> <h1 {{ $heading->attributes->class(['text-lg']) }}> {{ $heading }} </h1> {{ $slot }} <footer {{ $footer->attributes->class(['text-gray-700']) }}> {{ $footer }} </footer> </div> ``` <a name="inline-component-views"></a> ### Inline Component Views 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. */ public function render(): string { return <<<'blade' <div class="alert alert-danger"> {{ $slot }} </div> blade; } <a name="generating-inline-view-components"></a> #### Generating Inline View Components To create a component that renders an inline view, you may use the `inline` option when executing the `make:component` command: ```shell php artisan make:component Alert --inline ``` <a name="dynamic-components"></a> ### 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"; <x-dynamic-component :component="$componentName" class="mt-4" /> ``` <a name="manually-registering-components"></a> ### 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: 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 <x-package-alert/> ``` #### 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: 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 <x-nightshade::calendar /> <x-nightshade::color-picker /> ``` 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. <a name="anonymous-components"></a>
243144
## 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: ```blade <x-alert/> ``` You may use the `.` character to indicate if a component is nested deeper inside the `components` directory. For example, assuming the component is defined at `resources/views/components/inputs/button.blade.php`, you may render it like so: ```blade <x-inputs.button/> ``` <a name="anonymous-index-components"></a> ### 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 /resources/views/components/accordion.blade.php /resources/views/components/accordion/item.blade.php ``` This directory structure allows you to render the accordion component and its item like so: ```blade <x-accordion> <x-accordion.item> ... </x-accordion.item> </x-accordion> ``` 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 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/accordion.blade.php /resources/views/components/accordion/item.blade.php ``` <a name="data-properties-attributes"></a> ### 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). You may specify which attributes should be considered data variables using the `@props` directive at the top of your component's Blade template. All other attributes on the component will be available via the component's attribute bag. If you wish to give a data variable a default value, you may specify the variable's name as the array key and the default value as the array value: ```blade <!-- /resources/views/components/alert.blade.php --> @props(['type' => 'info', 'message']) <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}> {{ $message }} </div> ``` Given the component definition above, we may render the component like so: ```blade <x-alert type="error" :message="$message" class="mb-4"/> ``` <a name="accessing-parent-data"></a> ### 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 `<x-menu>` and child `<x-menu.item>`: ```blade <x-menu color="purple"> <x-menu.item>...</x-menu.item> <x-menu.item>...</x-menu.item> </x-menu> ``` The `<x-menu>` component may have an implementation like the following: ```blade <!-- /resources/views/components/menu/index.blade.php --> @props(['color' => 'gray']) <ul {{ $attributes->merge(['class' => 'bg-'.$color.'-200']) }}> {{ $slot }} </ul> ``` Because the `color` prop was only passed into the parent (`<x-menu>`), it won't be available inside `<x-menu.item>`. However, if we use the `@aware` directive, we can make it available inside `<x-menu.item>` as well: ```blade <!-- /resources/views/components/menu/item.blade.php --> @aware(['color' => 'gray']) <li {{ $attributes->merge(['class' => 'text-'.$color.'-800']) }}> {{ $slot }} </li> ``` > [!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. <a name="anonymous-component-paths"></a> ### Anonymous Component Paths 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. 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): /** * Bootstrap any application services. */ public function boot(): void { Blade::anonymousComponentPath(__DIR__.'/../components'); } 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 <x-panel /> ``` Prefix "namespaces" may be provided as the second argument to the `anonymousComponentPath` method: Blade::anonymousComponentPath(__DIR__.'/../components', 'dashboard'); 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 <x-dashboard::panel /> ``` <a name="building-layouts"></a>
243145
## Building Layouts <a name="layouts-using-components"></a> ### Layouts Using Components 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. <a name="defining-the-layout-component"></a> #### 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: ```blade <!-- resources/views/components/layout.blade.php --> <html> <head> <title>{{ $title ?? 'Todo Manager' }}</title> </head> <body> <h1>Todos</h1> <hr/> {{ $slot }} </body> </html> ``` <a name="applying-the-layout-component"></a> #### 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: ```blade <!-- resources/views/tasks.blade.php --> <x-layout> @foreach ($tasks as $task) <div>{{ $task }}</div> @endforeach </x-layout> ``` Remember, content that is injected into a component will be supplied to the default `$slot` variable within our `layout` component. As you may have noticed, our `layout` also respects a `$title` slot if one is provided; otherwise, a default title is shown. We may inject a custom title from our task list view using the standard slot syntax discussed in the [component documentation](#components): ```blade <!-- resources/views/tasks.blade.php --> <x-layout> <x-slot:title> Custom Title </x-slot> @foreach ($tasks as $task) <div>{{ $task }}</div> @endforeach </x-layout> ``` 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; Route::get('/tasks', function () { return view('tasks', ['tasks' => Task::all()]); }); <a name="layouts-using-template-inheritance"></a> ### Layouts Using Template Inheritance <a name="defining-a-layout"></a> #### 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). To get started, let's take a look at a simple example. First, we will examine a page layout. Since most web applications maintain the same general layout across various pages, it's convenient to define this layout as a single Blade view: ```blade <!-- resources/views/layouts/app.blade.php --> <html> <head> <title>App Name - @yield('title')</title> </head> <body> @section('sidebar') This is the master sidebar. @show <div class="container"> @yield('content') </div> </body> </html> ``` As you can see, this file contains typical HTML mark-up. However, take note of the `@section` and `@yield` directives. The `@section` directive, as the name implies, defines a section of content, while the `@yield` directive is used to display the contents of a given section. Now that we have defined a layout for our application, let's define a child page that inherits the layout. <a name="extending-a-layout"></a> #### 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`: ```blade <!-- resources/views/child.blade.php --> @extends('layouts.app') @section('title', 'Page Title') @section('sidebar') @@parent <p>This is appended to the master sidebar.</p> @endsection @section('content') <p>This is my body content.</p> @endsection ``` 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. > [!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: ```blade @yield('content', 'Default content') ``` <a name="forms"></a> ## Forms <a name="csrf-field"></a> ### CSRF Field Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that [the CSRF protection](/docs/{{version}}/csrf) middleware can validate the request. You may use the `@csrf` Blade directive to generate the token field: ```blade <form method="POST" action="/profile"> @csrf ... </form> ``` <a name="method-field"></a> ### Method Field Since HTML forms can't make `PUT`, `PATCH`, or `DELETE` requests, you will need to add a hidden `_method` field to spoof these HTTP verbs. The `@method` Blade directive can create this field for you: ```blade <form action="/foo/bar" method="POST"> @method('PUT') ... </form> ``` <a name="validation-errors"></a> ### Validation Errors The `@error` directive may be used to quickly check if [validation error messages](/docs/{{version}}/validation#quick-displaying-the-validation-errors) exist for a given attribute. Within an `@error` directive, you may echo the `$message` variable to display the error message: ```blade <!-- /resources/views/post/create.blade.php --> <label for="title">Post Title</label> <input id="title" type="text" class="@error('title') is-invalid @enderror" /> @error('title') <div class="alert alert-danger">{{ $message }}</div> @enderror ``` Since the `@error` directive compiles to an "if" statement, you may use the `@else` directive to render content when there is not an error for an attribute: ```blade <!-- /resources/views/auth.blade.php --> <label for="email">Email address</label> <input id="email" type="email" 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: ```blade <!-- /resources/views/auth.blade.php --> <label for="email">Email address</label> <input id="email" type="email" class="@error('email', 'login') is-invalid @enderror" /> @error('email', 'login') <div class="alert alert-danger">{{ $message }}</div> @enderror ``` <a name="stacks"></a> ## Stacks Blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be particularly useful for specifying any JavaScript libraries required by your child views: ```blade @push('scripts') <script src="/example.js"></script> @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') <script src="/example.js"></script> @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 <head> <!-- Head Contents --> @stack('scripts') </head> ``` If you would like to prepend content onto the beginning of a stack, you should use the `@prepend` directive: ```blade @push('scripts') This will be second... @endpush // Later... @prepend('scripts') This will be first... @endprepend ``` <a name="service-injection"></a>
243148
## Using Vue / React 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 Vue or React. 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 Vue or React 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 Vue / React frameworks such as [Nuxt](https://nuxt.com/) and [Next](https://nextjs.org/); 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. <a name="inertia"></a> ### Inertia Thankfully, Laravel offers the best of both worlds. [Inertia](https://inertiajs.com) bridges the gap between your Laravel application and your modern Vue or React frontend, allowing you to build full-fledged, modern frontends using Vue or React 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 Vue / React 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 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Models\User; use Inertia\Inertia; use Inertia\Response; class UserController extends Controller { /** * Show the profile for a given user. */ public function show(string $id): Response { return Inertia::render('Users/Profile', [ 'user' => User::findOrFail($id) ]); } } ``` An Inertia page corresponds to a Vue or React 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: ```vue <script setup> import Layout from '@/Layouts/Authenticated.vue'; import { Head } from '@inertiajs/vue3'; const props = defineProps(['user']); </script> <template> <Head title="User Profile" /> <Layout> <template #header> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> Profile </h2> </template> <div class="py-12"> Hello, {{ user.name }} </div> </Layout> </template> ``` As you can see, Inertia allows you to leverage the full power of Vue or React 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 Forge](https://forge.laravel.com), it's a breeze to ensure that Inertia's server-side rendering process is always running. <a name="inertia-starter-kits"></a> ### Starter Kits If you would like to build your frontend using Inertia and Vue / React, you can leverage our Breeze or Jetstream [starter kits](/docs/{{version}}/starter-kits#breeze-and-inertia) 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. <a name="bundling-assets"></a> ## 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 [Laravel Breeze](/docs/{{version}}/starter-kits#laravel-breeze), our simplest starter kit that 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).
243152
# HTTP Session - [Introduction](#introduction) - [Configuration](#configuration) - [Driver Prerequisites](#driver-prerequisites) - [Interacting With the Session](#interacting-with-the-session) - [Retrieving Data](#retrieving-data) - [Storing Data](#storing-data) - [Flash Data](#flash-data) - [Deleting Data](#deleting-data) - [Regenerating the Session ID](#regenerating-the-session-id) - [Session Blocking](#session-blocking) - [Adding Custom Session Drivers](#adding-custom-session-drivers) - [Implementing the Driver](#implementing-the-driver) - [Registering the Driver](#registering-the-driver) <a name="introduction"></a> ## Introduction Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests. That user information is typically placed in a persistent store / backend that can be accessed from subsequent requests. Laravel ships with a variety of session backends that are accessed through an expressive, unified API. Support for popular backends such as [Memcached](https://memcached.org), [Redis](https://redis.io), and databases is included. <a name="configuration"></a> ### Configuration Your application's session configuration file is stored at `config/session.php`. Be sure to review the options available to you in this file. By default, Laravel is configured to use the `database` session driver. The session `driver` configuration option defines where session data will be stored for each request. Laravel includes a variety of drivers: <div class="content-list" markdown="1"> - `file` - sessions are stored in `storage/framework/sessions`. - `cookie` - sessions are stored in secure, encrypted cookies. - `database` - sessions are stored in a relational database. - `memcached` / `redis` - sessions are stored in one of these fast, cache based stores. - `dynamodb` - sessions are stored in AWS DynamoDB. - `array` - sessions are stored in a PHP array and will not be persisted. </div> > [!NOTE] > The array driver is primarily used during [testing](/docs/{{version}}/testing) and prevents the data stored in the session from being persisted. <a name="driver-prerequisites"></a> ### Driver Prerequisites <a name="database"></a> #### Database When using the `database` session driver, you will need to ensure that you have a database table to contain the session data. Typically, this is included in Laravel's default `0001_01_01_000000_create_users_table.php` [database migration](/docs/{{version}}/migrations); however, if for any reason you do not have a `sessions` table, you may use the `make:session-table` Artisan command to generate this migration: ```shell php artisan make:session-table php artisan migrate ``` <a name="redis"></a> #### Redis Before using Redis sessions with Laravel, you will need to either install the PhpRedis PHP extension via PECL or install the `predis/predis` package (~1.0) via Composer. For more information on configuring Redis, consult Laravel's [Redis documentation](/docs/{{version}}/redis#configuration). > [!NOTE] > The `SESSION_CONNECTION` environment variable, or the `connection` option in the `session.php` configuration file, may be used to specify which Redis connection is used for session storage. <a name="interacting-with-the-session"></a>
243155
# Upgrade Guide - [Upgrading To 11.0 From 10.x](#upgrade-11.0) <a name="high-impact-changes"></a> ## High Impact Changes <div class="content-list" markdown="1"> - [Updating Dependencies](#updating-dependencies) - [Application Structure](#application-structure) - [Floating-Point Types](#floating-point-types) - [Modifying Columns](#modifying-columns) - [SQLite Minimum Version](#sqlite-minimum-version) - [Updating Sanctum](#updating-sanctum) </div> <a name="medium-impact-changes"></a> ## Medium Impact Changes <div class="content-list" markdown="1"> - [Carbon 3](#carbon-3) - [Password Rehashing](#password-rehashing) - [Per-Second Rate Limiting](#per-second-rate-limiting) - [Spatie Once Package](#spatie-once-package) </div> <a name="low-impact-changes"></a> ## Low Impact Changes <div class="content-list" markdown="1"> - [Doctrine DBAL Removal](#doctrine-dbal-removal) - [Eloquent Model `casts` Method](#eloquent-model-casts-method) - [Spatial Types](#spatial-types) - [The `Enumerable` Contract](#the-enumerable-contract) - [The `UserProvider` Contract](#the-user-provider-contract) - [The `Authenticatable` Contract](#the-authenticatable-contract) </div> <a name="upgrade-11.0"></a> ## Upgrading To 11.0 From 10.x <a name="estimated-upgrade-time-??-minutes"></a> #### Estimated Upgrade Time: 15 Minutes > [!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. <a name="updating-dependencies"></a> ### Updating Dependencies **Likelihood Of Impact: High** #### PHP 8.2.0 Required Laravel now requires PHP 8.2.0 or greater. #### curl 7.34.0 Required Laravel's HTTP client now requires curl 7.34.0 or greater. #### Composer Dependencies You should update the following dependencies in your application's `composer.json` file: <div class="content-list" markdown="1"> - `laravel/framework` to `^11.0` - `nunomaduro/collision` to `^8.1` - `laravel/breeze` to `^2.0` (If installed) - `laravel/cashier` to `^15.0` (If installed) - `laravel/dusk` to `^8.0` (If installed) - `laravel/jetstream` to `^5.0` (If installed) - `laravel/octane` to `^2.3` (If installed) - `laravel/passport` to `^12.0` (If installed) - `laravel/sanctum` to `^4.0` (If installed) - `laravel/scout` to `^10.0` (If installed) - `laravel/spark-stripe` to `^5.0` (If installed) - `laravel/telescope` to `^5.0` (If installed) - `livewire/livewire` to `^3.4` (If installed) - `inertiajs/inertia-laravel` to `^1.0` (If installed) </div> If your application is using Laravel Cashier Stripe, Passport, Sanctum, Spark Stripe, or Telescope, you will need to publish their migrations to your application. Cashier Stripe, Passport, Sanctum, Spark Stripe, and Telescope **no longer automatically load migrations from their own migrations** directory. Therefore, you should run the following command to publish their migrations to your application: ```bash php artisan vendor:publish --tag=cashier-migrations php artisan vendor:publish --tag=passport-migrations php artisan vendor:publish --tag=sanctum-migrations php artisan vendor:publish --tag=spark-migrations php artisan vendor:publish --tag=telescope-migrations ``` In addition, you should review the upgrade guides for each of these packages to ensure you are aware of any additional breaking changes: - [Laravel Cashier Stripe](#cashier-stripe) - [Laravel Passport](#passport) - [Laravel Sanctum](#sanctum) - [Laravel Spark Stripe](#spark-stripe) - [Laravel Telescope](#telescope) If you have manually installed the Laravel installer, you should update the installer via Composer: ```bash composer global require laravel/installer:^5.6 ``` Finally, you may remove the `doctrine/dbal` Composer dependency if you have previously added it to your application, as Laravel is no longer dependent on this package. <a name="application-structure"></a> ### Application Structure Laravel 11 introduces a new default application structure with fewer default files. Namely, new Laravel applications contain fewer service providers, middleware, and configuration files. However, we do **not recommend** that Laravel 10 applications upgrading to Laravel 11 attempt to migrate their application structure, as Laravel 11 has been carefully tuned to also support the Laravel 10 application structure. <a name="authentication"></a> ### Authentication <a name="password-rehashing"></a> #### Password Rehashing **Likelihood Of Impact: Low** Laravel 11 will automatically rehash your user's passwords during authentication if your hashing algorithm's "work factor" has been updated since the password was last hashed. Typically, this should not disrupt your application; however, if your `User` model's "password" field has a name other than `password`, you should specify the field's name via the model's `authPasswordName` property: protected $authPasswordName = 'custom_password_field'; Alternatively, you may disable password rehashing by adding the `rehash_on_login` option to your application's `config/hashing.php` configuration file: 'rehash_on_login' => false, <a name="the-user-provider-contract"></a> #### The `UserProvider` Contract **Likelihood Of Impact: Low** The `Illuminate\Contracts\Auth\UserProvider` contract has received a new `rehashPasswordIfRequired` method. This method is responsible for re-hashing and storing the user's password in storage when the application's hashing algorithm work factor has changed. If your application or package defines a class that implements this interface, you should add the new `rehashPasswordIfRequired` method to your implementation. A reference implementation can be found within the `Illuminate\Auth\EloquentUserProvider` class: ```php public function rehashPasswordIfRequired(Authenticatable $user, array $credentials, bool $force = false); ``` <a name="the-authenticatable-contract"></a> #### The `Authenticatable` Contract **Likelihood Of Impact: Low** The `Illuminate\Contracts\Auth\Authenticatable` contract has received a new `getAuthPasswordName` method. This method is responsible for returning the name of your authenticatable entity's password column. If your application or package defines a class that implements this interface, you should add the new `getAuthPasswordName` method to your implementation: ```php public function getAuthPasswordName() { return 'password'; } ``` The default `User` model included with Laravel receives this method automatically since the method is included within the `Illuminate\Auth\Authenticatable` trait. <a name="the-authentication-exception-class"></a> #### The `AuthenticationException` Class **Likelihood Of Impact: Very Low** The `redirectTo` method of the `Illuminate\Auth\AuthenticationException` class now requires an `Illuminate\Http\Request` instance as its first argument. If you are manually catching this exception and calling the `redirectTo` method, you should update your code accordingly: ```php if ($e instanceof AuthenticationException) { $path = $e->redirectTo($request); } ``` <a name="cache"></a> ### Cache <a name="cache-key-prefixes"></a> #### Cache Key Prefixes **Likelihood Of Impact: Very Low** Previously, if a cache key prefix was defined for the DynamoDB, Memcached, or Redis cache stores, Laravel would append a `:` to the prefix. In Laravel 11, the cache key prefix does not receive the `:` suffix. If you would like to maintain the previous prefixing behavior, you can manually add the `:` suffix to your cache key prefix. <a name="collections"></a> ### Collections <a name="the-enumerable-contract"></a> #### The `Enumerable` Contract **Likelihood Of Impact: Low** The `dump` method of the `Illuminate\Support\Enumerable` contract has been updated to accept a variadic `...$args` argument. If you are implementing this interface you should update your implementation accordingly: ```php public function dump(...$args); ``` <a name="database"></a>
243156
### Database <a name="sqlite-minimum-version"></a> #### SQLite 3.26.0+ **Likelihood Of Impact: High** If your application is utilizing an SQLite database, SQLite 3.26.0 or greater is required. <a name="eloquent-model-casts-method"></a> #### Eloquent Model `casts` Method **Likelihood Of Impact: Low** The base Eloquent model class now defines a `casts` method in order to support the definition of attribute casts. If one of your application's models is defining a `casts` relationship, it may conflict with the `casts` method now present on the base Eloquent model class. <a name="modifying-columns"></a> #### Modifying Columns **Likelihood Of Impact: High** When modifying a column, you must now explicitly include all the modifiers you want to keep on the column definition after it is changed. Any missing attributes will be dropped. For example, to retain the `unsigned`, `default`, and `comment` attributes, you must call each modifier explicitly when changing the column, even if those attributes have been assigned to the column by a previous migration. For example, imagine you have a migration that creates a `votes` column with the `unsigned`, `default`, and `comment` attributes: ```php Schema::create('users', function (Blueprint $table) { $table->integer('votes')->unsigned()->default(1)->comment('The vote count'); }); ``` Later, you write a migration that changes the column to be `nullable` as well: ```php Schema::table('users', function (Blueprint $table) { $table->integer('votes')->nullable()->change(); }); ``` In Laravel 10, this migration would retain the `unsigned`, `default`, and `comment` attributes on the column. However, in Laravel 11, the migration must now also include all of the attributes that were previously defined on the column. Otherwise, they will be dropped: ```php Schema::table('users', function (Blueprint $table) { $table->integer('votes') ->unsigned() ->default(1) ->comment('The vote count') ->nullable() ->change(); }); ``` 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: ```php // Add an index... $table->bigIncrements('id')->primary()->change(); // Drop an index... $table->char('postal_code', 10)->unique(false)->change(); ``` If you do not want to update all of the existing "change" migrations in your application to retain the column's existing attributes, you may simply [squash your migrations](/docs/{{version}}/migrations#squashing-migrations): ```bash php artisan schema:dump ``` Once your migrations have been squashed, Laravel will "migrate" the database using your application's schema file before running any pending migrations. <a name="floating-point-types"></a> #### Floating-Point Types **Likelihood Of Impact: High** The `double` and `float` migration column types have been rewritten to be consistent across all databases. The `double` column type now creates a `DOUBLE` equivalent column without total digits and places (digits after decimal point), which is the standard SQL syntax. Therefore, you may remove the arguments for `$total` and `$places`: ```php $table->double('amount'); ``` The `float` column type now creates a `FLOAT` equivalent column without total digits and places (digits after decimal point), but with an optional `$precision` specification to determine storage size as a 4-byte single-precision column or an 8-byte double-precision column. Therefore, you may remove the arguments for `$total` and `$places` and specify the optional `$precision` to your desired value and according to your database's documentation: ```php $table->float('amount', precision: 53); ``` The `unsignedDecimal`, `unsignedDouble`, and `unsignedFloat` methods have been removed, as the unsigned modifier for these column types has been deprecated by MySQL, and was never standardized on other database systems. However, if you wish to continue using the deprecated unsigned attribute for these column types, you may chain the `unsigned` method onto the column's definition: ```php $table->decimal('amount', total: 8, places: 2)->unsigned(); $table->double('amount')->unsigned(); $table->float('amount', precision: 53)->unsigned(); ``` <a name="dedicated-mariadb-driver"></a> #### Dedicated MariaDB Driver **Likelihood Of Impact: Very Low** Instead of always utilizing the MySQL driver when connecting to MariaDB databases, Laravel 11 adds a dedicated database driver for MariaDB. If your application connects to a MariaDB database, you may update the connection configuration to the new `mariadb` driver to benefit from MariaDB specific features in the future: 'driver' => 'mariadb', 'url' => env('DB_URL'), 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), // ... Currently, the new MariaDB driver behaves like the current MySQL driver with one exception: the `uuid` schema builder method creates native UUID columns instead of `char(36)` columns. If your existing migrations utilize the `uuid` schema builder method and you choose to use the new `mariadb` database driver, you should update your migration's invocations of the `uuid` method to `char` to avoid breaking changes or unexpected behavior: ```php Schema::table('users', function (Blueprint $table) { $table->char('uuid', 36); // ... }); ``` <a name="spatial-types"></a> #### Spatial Types **Likelihood Of Impact: Low** The spatial column types of database migrations have been rewritten to be consistent across all databases. Therefore, you may remove `point`, `lineString`, `polygon`, `geometryCollection`, `multiPoint`, `multiLineString`, `multiPolygon`, and `multiPolygonZ` methods from your migrations and use `geometry` or `geography` methods instead: ```php $table->geometry('shapes'); $table->geography('coordinates'); ``` To explicitly restrict the type or the spatial reference system identifier for values stored in the column on MySQL, MariaDB, and PostgreSQL, you may pass the `subtype` and `srid` to the method: ```php $table->geometry('dimension', subtype: 'polygon', srid: 0); $table->geography('latitude', subtype: 'point', srid: 4326); ``` The `isGeometry` and `projection` column modifiers of the PostgreSQL grammar have been removed accordingly. <a name="doctrine-dbal-removal"></a> #### Doctrine DBAL Removal **Likelihood Of Impact: Low** The following list of Doctrine DBAL related classes and methods have been removed. Laravel is no longer dependent on this package and registering custom Doctrines types is no longer necessary for the proper creation and alteration of various column types that previously required custom types: <div class="content-list" markdown="1"> - `Illuminate\Database\Schema\Builder::$alwaysUsesNativeSchemaOperationsIfPossible` class property - `Illuminate\Database\Schema\Builder::useNativeSchemaOperationsIfPossible()` method - `Illuminate\Database\Connection::usingNativeSchemaOperations()` method - `Illuminate\Database\Connection::isDoctrineAvailable()` method - `Illuminate\Database\Connection::getDoctrineConnection()` method - `Illuminate\Database\Connection::getDoctrineSchemaManager()` method - `Illuminate\Database\Connection::getDoctrineColumn()` method - `Illuminate\Database\Connection::registerDoctrineType()` method - `Illuminate\Database\DatabaseManager::registerDoctrineType()` method - `Illuminate\Database\PDO` directory - `Illuminate\Database\DBAL\TimestampType` class - `Illuminate\Database\Schema\Grammars\ChangeColumn` class - `Illuminate\Database\Schema\Grammars\RenameColumn` class - `Illuminate\Database\Schema\Grammars\Grammar::getDoctrineTableDiff()` method </div> In addition, registering custom Doctrine types via `dbal.types` in your application's `database` configuration file is no longer required. If you were previously using Doctrine DBAL to inspect your database and its associated tables, you may use Laravel's new native schema methods (`Schema::getTables()`, `Schema::getColumns()`, `Schema::getIndexes()`, `Schema::getForeignKeys()`, etc.) instead. <a name="deprecated-schema-methods"></a> #### Deprecated Schema Methods **Likelihood Of Impact: Very Low** The deprecated, Doctrine based `Schema::getAllTables()`, `Schema::getAllViews()`, and `Schema::getAllTypes()` methods have been removed in favor of new Laravel native `Schema::getTables()`, `Schema::getViews()`, and `Schema::getTypes()` methods. When using PostgreSQL and SQL Server, none of the new schema methods will accept a three-part reference (e.g. `database.schema.table`). Therefore, you should use `connection()` to declare the database instead: ```php Schema::connection('database')->hasTable('schema.table'); ``` <a name="get-column-types"></a>
243157
#### Schema Builder `getColumnType()` Method **Likelihood Of Impact: Very Low** The `Schema::getColumnType()` method now always returns actual type of the given column, not the Doctrine DBAL equivalent type. <a name="database-connection-interface"></a> #### Database Connection Interface **Likelihood Of Impact: Very Low** The `Illuminate\Database\ConnectionInterface` interface has received a new `scalar` method. If you are defining your own implementation of this interface, you should add the `scalar` method to your implementation: ```php public function scalar($query, $bindings = [], $useReadPdo = true); ``` <a name="dates"></a> ### Dates <a name="carbon-3"></a> #### Carbon 3 **Likelihood Of Impact: Medium** Laravel 11 supports both Carbon 2 and Carbon 3. Carbon is a date manipulation library utilized extensively by Laravel and packages throughout the ecosystem. If you upgrade to Carbon 3, be aware that `diffIn*` methods now return floating-point numbers and may return negative values to indicate time direction, which is a significant change from Carbon 2. Review Carbon's [change log](https://github.com/briannesbitt/Carbon/releases/tag/3.0.0) and [documentation](https://carbon.nesbot.com/docs/#api-carbon-3) for detailed information on how to handle these and other changes. <a name="mail"></a> ### Mail <a name="the-mailer-contract"></a> #### The `Mailer` Contract **Likelihood Of Impact: Very Low** The `Illuminate\Contracts\Mail\Mailer` contract has received a new `sendNow` method. If your application or package is manually implementing this contract, you should add the new `sendNow` method to your implementation: ```php public function sendNow($mailable, array $data = [], $callback = null); ``` <a name="packages"></a> ### Packages <a name="publishing-service-providers"></a> #### Publishing Service Providers to the Application **Likelihood Of Impact: Very Low** If you have written a Laravel package that manually publishes a service provider to the application's `app/Providers` directory and manually modifies the application's `config/app.php` configuration file to register the service provider, you should update your package to utilize the new `ServiceProvider::addProviderToBootstrapFile` method. The `addProviderToBootstrapFile` method will automatically add the service provider you have published to the application's `bootstrap/providers.php` file, since the `providers` array does not exist within the `config/app.php` configuration file in new Laravel 11 applications. ```php use Illuminate\Support\ServiceProvider; ServiceProvider::addProviderToBootstrapFile(Provider::class); ``` <a name="queues"></a> ### Queues <a name="the-batch-repository-interface"></a> #### The `BatchRepository` Interface **Likelihood Of Impact: Very Low** The `Illuminate\Bus\BatchRepository` interface has received a new `rollBack` method. If you are implementing this interface within your own package or application, you should add this method to your implementation: ```php public function rollBack(); ``` <a name="synchronous-jobs-in-database-transactions"></a> #### Synchronous Jobs in Database Transactions **Likelihood Of Impact: Very Low** Previously, synchronous jobs (jobs using the `sync` queue driver) would execute immediately, regardless of whether the `after_commit` configuration option of the queue connection was set to `true` or the `afterCommit` method was invoked on the job. In Laravel 11, synchronous queue jobs will now respect the "after commit" configuration of the queue connection or job. <a name="rate-limiting"></a> ### Rate Limiting <a name="per-second-rate-limiting"></a> #### Per-Second Rate Limiting **Likelihood Of Impact: Medium** Laravel 11 supports per-second rate limiting instead of being limited to per-minute granularity. There are a variety of potential breaking changes you should be aware of related to this change. The `GlobalLimit` class constructor now accepts seconds instead of minutes. This class is not documented and would not typically be used by your application: ```php new GlobalLimit($attempts, 2 * 60); ``` The `Limit` class constructor now accepts seconds instead of minutes. All documented usages of this class are limited to static constructors such as `Limit::perMinute` and `Limit::perSecond`. However, if you are instantiating this class manually, you should update your application to provide seconds to the class's constructor: ```php new Limit($key, $attempts, 2 * 60); ``` The `Limit` class's `decayMinutes` property has been renamed to `decaySeconds` and now contains seconds instead of minutes. The `Illuminate\Queue\Middleware\ThrottlesExceptions` and `Illuminate\Queue\Middleware\ThrottlesExceptionsWithRedis` class constructors now accept seconds instead of minutes: ```php new ThrottlesExceptions($attempts, 2 * 60); new ThrottlesExceptionsWithRedis($attempts, 2 * 60); ``` <a name="cashier-stripe"></a> ### Cashier Stripe <a name="updating-cashier-stripe"></a> #### Updating Cashier Stripe **Likelihood Of Impact: High** Laravel 11 no longer supports Cashier Stripe 14.x. Therefore, you should update your application's Laravel Cashier Stripe dependency to `^15.0` in your `composer.json` file. Cashier Stripe 15.0 no longer automatically loads migrations from its own migrations directory. Instead, you should run the following command to publish Cashier Stripe's migrations to your application: ```shell php artisan vendor:publish --tag=cashier-migrations ``` Please review the complete [Cashier Stripe upgrade guide](https://github.com/laravel/cashier-stripe/blob/15.x/UPGRADE.md) for additional breaking changes. <a name="spark-stripe"></a> ### Spark (Stripe) <a name="updating-spark-stripe"></a> #### Updating Spark Stripe **Likelihood Of Impact: High** Laravel 11 no longer supports Laravel Spark Stripe 4.x. Therefore, you should update your application's Laravel Spark Stripe dependency to `^5.0` in your `composer.json` file. Spark Stripe 5.0 no longer automatically loads migrations from its own migrations directory. Instead, you should run the following command to publish Spark Stripe's migrations to your application: ```shell php artisan vendor:publish --tag=spark-migrations ``` Please review the complete [Spark Stripe upgrade guide](https://spark.laravel.com/docs/spark-stripe/upgrade.html) for additional breaking changes. <a name="passport"></a> ### Passport <a name="updating-telescope"></a> #### Updating Passport **Likelihood Of Impact: High** Laravel 11 no longer supports Laravel Passport 11.x. Therefore, you should update your application's Laravel Passport dependency to `^12.0` in your `composer.json` file. Passport 12.0 no longer automatically loads migrations from its own migrations directory. Instead, you should run the following command to publish Passport's migrations to your application: ```shell php artisan vendor:publish --tag=passport-migrations ``` In addition, the password grant type is disabled by default. You may enable it by invoking the `enablePasswordGrant` method in the `boot` method of your application's `AppServiceProvider`: public function boot(): void { Passport::enablePasswordGrant(); } <a name="sanctum"></a> ### Sanctum <a name="updating-sanctum"></a> #### Updating Sanctum **Likelihood Of Impact: High** Laravel 11 no longer supports Laravel Sanctum 3.x. Therefore, you should update your application's Laravel Sanctum dependency to `^4.0` in your `composer.json` file. Sanctum 4.0 no longer automatically loads migrations from its own migrations directory. Instead, you should run the following command to publish Sanctum's migrations to your application: ```shell php artisan vendor:publish --tag=sanctum-migrations ``` Then, in your application's `config/sanctum.php` configuration file, you should update the references to the `authenticate_session`, `encrypt_cookies`, and `validate_csrf_token` middleware to the following: 'middleware' => [ 'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class, 'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class, 'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class, ], <a name="telescope"></a> ### Telescope <a name="updating-telescope"></a> #### Updating Telescope **Likelihood Of Impact: High** Laravel 11 no longer supports Laravel Telescope 4.x. Therefore, you should update your application's Laravel Telescope dependency to `^5.0` in your `composer.json` file. Telescope 5.0 no longer automatically loads migrations from its own migrations directory. Instead, you should run the following command to publish Telescope's migrations to your application: ```shell php artisan vendor:publish --tag=telescope-migrations ``` <a name="spatie-once-package"></a>
243162
### 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 ); ``` <a name="search-validation"></a> #### 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. <a name="multisearch"></a> ### 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 ); ``` <a name="multisearch-required"></a> #### 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.' ); ``` <a name="multisearch-validation"></a> #### 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. <a name="pause"></a> ### 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.'); ``` <a name="transforming-input-before-validation"></a> ## 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 } ); ``` <a name="forms"></a>
243168
# Laravel Scout - [Introduction](#introduction) - [Installation](#installation) - [Queueing](#queueing) - [Driver Prerequisites](#driver-prerequisites) - [Algolia](#algolia) - [Meilisearch](#meilisearch) - [Typesense](#typesense) - [Configuration](#configuration) - [Configuring Model Indexes](#configuring-model-indexes) - [Configuring Searchable Data](#configuring-searchable-data) - [Configuring the Model ID](#configuring-the-model-id) - [Configuring Search Engines per Model](#configuring-search-engines-per-model) - [Identifying Users](#identifying-users) - [Database / Collection Engines](#database-and-collection-engines) - [Database Engine](#database-engine) - [Collection Engine](#collection-engine) - [Indexing](#indexing) - [Batch Import](#batch-import) - [Adding Records](#adding-records) - [Updating Records](#updating-records) - [Removing Records](#removing-records) - [Pausing Indexing](#pausing-indexing) - [Conditionally Searchable Model Instances](#conditionally-searchable-model-instances) - [Searching](#searching) - [Where Clauses](#where-clauses) - [Pagination](#pagination) - [Soft Deleting](#soft-deleting) - [Customizing Engine Searches](#customizing-engine-searches) - [Custom Engines](#custom-engines) <a name="introduction"></a> ## Introduction [Laravel Scout](https://github.com/laravel/scout) provides a simple, driver based solution for adding full-text search to your [Eloquent models](/docs/{{version}}/eloquent). Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records. Currently, Scout ships with [Algolia](https://www.algolia.com/), [Meilisearch](https://www.meilisearch.com), [Typesense](https://typesense.org), and MySQL / PostgreSQL (`database`) drivers. In addition, Scout includes a "collection" driver that is designed for local development usage and does not require any external dependencies or third-party services. Furthermore, writing custom drivers is simple and you are free to extend Scout with your own search implementations. <a name="installation"></a> ## Installation First, install Scout via the Composer package manager: ```shell composer require laravel/scout ``` After installing Scout, you should publish the Scout configuration file using the `vendor:publish` Artisan command. This command will publish the `scout.php` configuration file to your application's `config` directory: ```shell php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" ``` Finally, add the `Laravel\Scout\Searchable` trait to the model you would like to make searchable. This trait will register a model observer that will automatically keep the model in sync with your search driver: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; class Post extends Model { use Searchable; } <a name="queueing"></a> ### Queueing While not strictly required to use Scout, you should strongly consider configuring a [queue driver](/docs/{{version}}/queues) before using the library. Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application's web interface. Once you have configured a queue driver, set the value of the `queue` option in your `config/scout.php` configuration file to `true`: 'queue' => true, Even when the `queue` option is set to `false`, it's important to remember that some Scout drivers like Algolia and Meilisearch always index records asynchronously. Meaning, even though the index operation has completed within your Laravel application, the search engine itself may not reflect the new and updated records immediately. To specify the connection and queue that your Scout jobs utilize, you may define the `queue` configuration option as an array: 'queue' => [ 'connection' => 'redis', 'queue' => 'scout' ], Of course, if you customize the connection and queue that Scout jobs utilize, you should run a queue worker to process jobs on that connection and queue: php artisan queue:work redis --queue=scout <a name="driver-prerequisites"></a>
243169
## Driver Prerequisites <a name="algolia"></a> ### Algolia When using the Algolia driver, you should configure your Algolia `id` and `secret` credentials in your `config/scout.php` configuration file. Once your credentials have been configured, you will also need to install the Algolia PHP SDK via the Composer package manager: ```shell composer require algolia/algoliasearch-client-php ``` <a name="meilisearch"></a> ### Meilisearch [Meilisearch](https://www.meilisearch.com) is a blazingly fast and open source search engine. If you aren't sure how to install Meilisearch on your local machine, you may use [Laravel Sail](/docs/{{version}}/sail#meilisearch), Laravel's officially supported Docker development environment. When using the Meilisearch driver you will need to install the Meilisearch PHP SDK via the Composer package manager: ```shell composer require meilisearch/meilisearch-php http-interop/http-factory-guzzle ``` Then, set the `SCOUT_DRIVER` environment variable as well as your Meilisearch `host` and `key` credentials within your application's `.env` file: ```ini SCOUT_DRIVER=meilisearch MEILISEARCH_HOST=http://127.0.0.1:7700 MEILISEARCH_KEY=masterKey ``` For more information regarding Meilisearch, please consult the [Meilisearch documentation](https://docs.meilisearch.com/learn/getting_started/quick_start.html). In addition, you should ensure that you install a version of `meilisearch/meilisearch-php` that is compatible with your Meilisearch binary version by reviewing [Meilisearch's documentation regarding binary compatibility](https://github.com/meilisearch/meilisearch-php#-compatibility-with-meilisearch). > [!WARNING] > When upgrading Scout on an application that utilizes Meilisearch, you should always [review any additional breaking changes](https://github.com/meilisearch/Meilisearch/releases) to the Meilisearch service itself. <a name="typesense"></a> ### Typesense [Typesense](https://typesense.org) is a lightning-fast, open source search engine and supports keyword search, semantic search, geo search, and vector search. You can [self-host](https://typesense.org/docs/guide/install-typesense.html#option-2-local-machine-self-hosting) Typesense or use [Typesense Cloud](https://cloud.typesense.org). To get started using Typesense with Scout, install the Typesense PHP SDK via the Composer package manager: ```shell composer require typesense/typesense-php ``` Then, set the `SCOUT_DRIVER` environment variable as well as your Typesense host and API key credentials within your application's .env file: ```ini SCOUT_DRIVER=typesense TYPESENSE_API_KEY=masterKey TYPESENSE_HOST=localhost ``` If you are using [Laravel Sail](/docs/{{version}}/sail), you may need to adjust the `TYPESENSE_HOST` environment variable to match the Docker container name. You may also optionally specify your installation's port, path, and protocol: ```ini TYPESENSE_PORT=8108 TYPESENSE_PATH= TYPESENSE_PROTOCOL=http ``` Additional settings and schema definitions for your Typesense collections can be found within your application's `config/scout.php` configuration file. For more information regarding Typesense, please consult the [Typesense documentation](https://typesense.org/docs/guide/#quick-start). <a name="preparing-data-for-storage-in-typesense"></a> #### Preparing Data for Storage in Typesense When utilizing Typesense, your searchable model's must define a `toSearchableArray` method that casts your model's primary key to a string and creation date to a UNIX timestamp: ```php /** * Get the indexable data array for the model. * * @return array<string, mixed> */ public function toSearchableArray() { return array_merge($this->toArray(),[ 'id' => (string) $this->id, 'created_at' => $this->created_at->timestamp, ]); } ``` You should also define your Typesense collection schemas in your application's `config/scout.php` file. A collection schema describes the data types of each field that is searchable via Typesense. For more information on all available schema options, please consult the [Typesense documentation](https://typesense.org/docs/latest/api/collections.html#schema-parameters). If you need to change your Typesense collection's schema after it has been defined, you may either run `scout:flush` and `scout:import`, which will delete all existing indexed data and recreate the schema. Or, you may use Typesense's API to modify the collection's schema without removing any indexed data. If your searchable model is soft deletable, you should define a `__soft_deleted` field in the model's corresponding Typesense schema within your application's `config/scout.php` configuration file: ```php User::class => [ 'collection-schema' => [ 'fields' => [ // ... [ 'name' => '__soft_deleted', 'type' => 'int32', 'optional' => true, ], ], ], ], ``` <a name="typesense-dynamic-search-parameters"></a> #### Dynamic Search Parameters Typesense allows you to modify your [search parameters](https://typesense.org/docs/latest/api/search.html#search-parameters) dynamically when performing a search operation via the `options` method: ```php use App\Models\Todo; Todo::search('Groceries')->options([ 'query_by' => 'title, description' ])->get(); ``` <a name="configuration"></a>
243170
## Configuration <a name="configuring-model-indexes"></a> ### Configuring Model Indexes Each Eloquent model is synced with a given search "index", which contains all of the searchable records for that model. In other words, you can think of each index like a MySQL table. By default, each model will be persisted to an index matching the model's typical "table" name. Typically, this is the plural form of the model name; however, you are free to customize the model's index by overriding the `searchableAs` method on the model: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; class Post extends Model { use Searchable; /** * Get the name of the index associated with the model. */ public function searchableAs(): string { return 'posts_index'; } } <a name="configuring-searchable-data"></a> ### Configuring Searchable Data By default, the entire `toArray` form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the `toSearchableArray` method on the model: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; class Post extends Model { use Searchable; /** * Get the indexable data array for the model. * * @return array<string, mixed> */ public function toSearchableArray(): array { $array = $this->toArray(); // Customize the data array... return $array; } } Some search engines such as Meilisearch will only perform filter operations (`>`, `<`, etc.) on data of the correct type. So, when using these search engines and customizing your searchable data, you should ensure that numeric values are cast to their correct type: public function toSearchableArray() { return [ 'id' => (int) $this->id, 'name' => $this->name, 'price' => (float) $this->price, ]; } <a name="configuring-filterable-data-for-meilisearch"></a> #### Configuring Filterable Data and Index Settings (Meilisearch) Unlike Scout's other drivers, Meilisearch requires you to pre-define index search settings such as filterable attributes, sortable attributes, and [other supported settings fields](https://docs.meilisearch.com/reference/api/settings.html). Filterable attributes are any attributes you plan to filter on when invoking Scout's `where` method, while sortable attributes are any attributes you plan to sort by when invoking Scout's `orderBy` method. To define your index settings, adjust the `index-settings` portion of your `meilisearch` configuration entry in your application's `scout` configuration file: ```php use App\Models\User; use App\Models\Flight; 'meilisearch' => [ 'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'), 'key' => env('MEILISEARCH_KEY', null), 'index-settings' => [ User::class => [ 'filterableAttributes'=> ['id', 'name', 'email'], 'sortableAttributes' => ['created_at'], // Other settings fields... ], Flight::class => [ 'filterableAttributes'=> ['id', 'destination'], 'sortableAttributes' => ['updated_at'], ], ], ], ``` If the model underlying a given index is soft deletable and is included in the `index-settings` array, Scout will automatically include support for filtering on soft deleted models on that index. If you have no other filterable or sortable attributes to define for a soft deletable model index, you may simply add an empty entry to the `index-settings` array for that model: ```php 'index-settings' => [ Flight::class => [] ], ``` After configuring your application's index settings, you must invoke the `scout:sync-index-settings` Artisan command. This command will inform Meilisearch of your currently configured index settings. For convenience, you may wish to make this command part of your deployment process: ```shell php artisan scout:sync-index-settings ``` <a name="configuring-the-model-id"></a> ### Configuring the Model ID By default, Scout will use the primary key of the model as the model's unique ID / key that is stored in the search index. If you need to customize this behavior, you may override the `getScoutKey` and the `getScoutKeyName` methods on the model: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; class User extends Model { use Searchable; /** * Get the value used to index the model. */ public function getScoutKey(): mixed { return $this->email; } /** * Get the key name used to index the model. */ public function getScoutKeyName(): mixed { return 'email'; } } <a name="configuring-search-engines-per-model"></a> ### Configuring Search Engines per Model When searching, Scout will typically use the default search engine specified in your application's `scout` configuration file. However, the search engine for a particular model can be changed by overriding the `searchableUsing` method on the model: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Engines\Engine; use Laravel\Scout\EngineManager; use Laravel\Scout\Searchable; class User extends Model { use Searchable; /** * Get the engine used to index the model. */ public function searchableUsing(): Engine { return app(EngineManager::class)->engine('meilisearch'); } } <a name="identifying-users"></a> ### Identifying Users Scout also allows you to auto identify users when using [Algolia](https://algolia.com). Associating the authenticated user with search operations may be helpful when viewing your search analytics within Algolia's dashboard. You can enable user identification by defining a `SCOUT_IDENTIFY` environment variable as `true` in your application's `.env` file: ```ini SCOUT_IDENTIFY=true ``` Enabling this feature will also pass the request's IP address and your authenticated user's primary identifier to Algolia so this data is associated with any search request that is made by the user. <a name="database-and-collection-engines"></a>
243173
## Searching You may begin searching a model using the `search` method. The search method accepts a single string that will be used to search your models. You should then chain the `get` method onto the search query to retrieve the Eloquent models that match the given search query: use App\Models\Order; $orders = Order::search('Star Trek')->get(); Since Scout searches return a collection of Eloquent models, you may even return the results directly from a route or controller and they will automatically be converted to JSON: use App\Models\Order; use Illuminate\Http\Request; Route::get('/search', function (Request $request) { return Order::search($request->search)->get(); }); If you would like to get the raw search results before they are converted to Eloquent models, you may use the `raw` method: $orders = Order::search('Star Trek')->raw(); <a name="custom-indexes"></a> #### Custom Indexes Search queries will typically be performed on the index specified by the model's [`searchableAs`](#configuring-model-indexes) method. However, you may use the `within` method to specify a custom index that should be searched instead: $orders = Order::search('Star Trek') ->within('tv_shows_popularity_desc') ->get(); <a name="where-clauses"></a> ### Where Clauses Scout allows you to add simple "where" clauses to your search queries. Currently, these clauses only support basic numeric equality checks and are primarily useful for scoping search queries by an owner ID: use App\Models\Order; $orders = Order::search('Star Trek')->where('user_id', 1)->get(); In addition, the `whereIn` method may be used to verify that a given column's value is contained within the given array: $orders = Order::search('Star Trek')->whereIn( 'status', ['open', 'paid'] )->get(); The `whereNotIn` method verifies that the given column's value is not contained in the given array: $orders = Order::search('Star Trek')->whereNotIn( 'status', ['closed'] )->get(); Since a search index is not a relational database, more advanced "where" clauses are not currently supported. > [!WARNING] > If your application is using Meilisearch, you must configure your application's [filterable attributes](#configuring-filterable-data-for-meilisearch) before utilizing Scout's "where" clauses. <a name="pagination"></a> ### Pagination In addition to retrieving a collection of models, you may paginate your search results using the `paginate` method. This method will return an `Illuminate\Pagination\LengthAwarePaginator` instance just as if you had [paginated a traditional Eloquent query](/docs/{{version}}/pagination): use App\Models\Order; $orders = Order::search('Star Trek')->paginate(); You may specify how many models to retrieve per page by passing the amount as the first argument to the `paginate` method: $orders = Order::search('Star Trek')->paginate(15); Once you have retrieved the results, you may display the results and render the page links using [Blade](/docs/{{version}}/blade) just as if you had paginated a traditional Eloquent query: ```html <div class="container"> @foreach ($orders as $order) {{ $order->price }} @endforeach </div> {{ $orders->links() }} ``` Of course, if you would like to retrieve the pagination results as JSON, you may return the paginator instance directly from a route or controller: use App\Models\Order; use Illuminate\Http\Request; Route::get('/orders', function (Request $request) { return Order::search($request->input('query'))->paginate(15); }); > [!WARNING] > Since search engines are not aware of your Eloquent model's global scope definitions, you should not utilize global scopes in applications that utilize Scout pagination. Or, you should recreate the global scope's constraints when searching via Scout. <a name="soft-deleting"></a> ### Soft Deleting If your indexed models are [soft deleting](/docs/{{version}}/eloquent#soft-deleting) and you need to search your soft deleted models, set the `soft_delete` option of the `config/scout.php` configuration file to `true`: 'soft_delete' => true, When this configuration option is `true`, Scout will not remove soft deleted models from the search index. Instead, it will set a hidden `__soft_deleted` attribute on the indexed record. Then, you may use the `withTrashed` or `onlyTrashed` methods to retrieve the soft deleted records when searching: use App\Models\Order; // Include trashed records when retrieving results... $orders = Order::search('Star Trek')->withTrashed()->get(); // Only include trashed records when retrieving results... $orders = Order::search('Star Trek')->onlyTrashed()->get(); > [!NOTE] > When a soft deleted model is permanently deleted using `forceDelete`, Scout will remove it from the search index automatically. <a name="customizing-engine-searches"></a> ### Customizing Engine Searches If you need to perform advanced customization of the search behavior of an engine you may pass a closure as the second argument to the `search` method. For example, you could use this callback to add geo-location data to your search options before the search query is passed to Algolia: use Algolia\AlgoliaSearch\SearchIndex; use App\Models\Order; Order::search( 'Star Trek', function (SearchIndex $algolia, string $query, array $options) { $options['body']['query']['bool']['filter']['geo_distance'] = [ 'distance' => '1000km', 'location' => ['lat' => 36, 'lon' => 111], ]; return $algolia->search($query, $options); } )->get(); <a name="customizing-the-eloquent-results-query"></a> #### Customizing the Eloquent Results Query After Scout retrieves a list of matching Eloquent models from your application's search engine, Eloquent is used to retrieve all of the matching models by their primary keys. You may customize this query by invoking the `query` method. The `query` method accepts a closure that will receive the Eloquent query builder instance as an argument: ```php use App\Models\Order; use Illuminate\Database\Eloquent\Builder; $orders = Order::search('Star Trek') ->query(fn (Builder $query) => $query->with('invoices')) ->get(); ``` Since this callback is invoked after the relevant models have already been retrieved from your application's search engine, the `query` method should not be used for "filtering" results. Instead, you should use [Scout where clauses](#where-clauses). <a name="custom-engines"></a> ## Custom Engines <a name="writing-the-engine"></a> #### Writing the Engine If one of the built-in Scout search engines doesn't fit your needs, you may write your own custom engine and register it with Scout. Your engine should extend the `Laravel\Scout\Engines\Engine` abstract class. This abstract class contains eight methods your custom engine must implement: use Laravel\Scout\Builder; abstract public function update($models); abstract public function delete($models); abstract public function search(Builder $builder); abstract public function paginate(Builder $builder, $perPage, $page); abstract public function mapIds($results); abstract public function map(Builder $builder, $results, $model); abstract public function getTotalCount($results); abstract public function flush($model); You may find it helpful to review the implementations of these methods on the `Laravel\Scout\Engines\AlgoliaEngine` class. This class will provide you with a good starting point for learning how to implement each of these methods in your own engine. <a name="registering-the-engine"></a> #### Registering the Engine Once you have written your custom engine, you may register it with Scout using the `extend` method of the Scout engine manager. Scout's engine manager may be resolved from the Laravel service container. You should call the `extend` method from the `boot` method of your `App\Providers\AppServiceProvider` class or any other service provider used by your application: use App\ScoutExtensions\MySqlSearchEngine; use Laravel\Scout\EngineManager; /** * Bootstrap any application services. */ public function boot(): void { resolve(EngineManager::class)->extend('mysql', function () { return new MySqlSearchEngine; }); } Once your engine has been registered, you may specify it as your default Scout `driver` in your application's `config/scout.php` configuration file: 'driver' => 'mysql',
243174
# Eloquent: API Resources - [Introduction](#introduction) - [Generating Resources](#generating-resources) - [Concept Overview](#concept-overview) - [Resource Collections](#resource-collections) - [Writing Resources](#writing-resources) - [Data Wrapping](#data-wrapping) - [Pagination](#pagination) - [Conditional Attributes](#conditional-attributes) - [Conditional Relationships](#conditional-relationships) - [Adding Meta Data](#adding-meta-data) - [Resource Responses](#resource-responses) <a name="introduction"></a> ## Introduction When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. For example, you may wish to display certain attributes for a subset of users and not others, or you may wish to always include certain relationships in the JSON representation of your models. Eloquent's resource classes allow you to expressively and easily transform your models and model collections into JSON. Of course, you may always convert Eloquent models or collections to JSON using their `toJson` methods; however, Eloquent resources provide more granular and robust control over the JSON serialization of your models and their relationships. <a name="generating-resources"></a> ## Generating Resources To generate a resource class, you may use the `make:resource` Artisan command. By default, resources will be placed in the `app/Http/Resources` directory of your application. Resources extend the `Illuminate\Http\Resources\Json\JsonResource` class: ```shell php artisan make:resource UserResource ``` <a name="generating-resource-collections"></a> #### Resource Collections In addition to generating resources that transform individual models, you may generate resources that are responsible for transforming collections of models. This allows your JSON responses to include links and other meta information that is relevant to an entire collection of a given resource. To create a resource collection, you should use the `--collection` flag when creating the resource. Or, including the word `Collection` in the resource name will indicate to Laravel that it should create a collection resource. Collection resources extend the `Illuminate\Http\Resources\Json\ResourceCollection` class: ```shell php artisan make:resource User --collection php artisan make:resource UserCollection ``` <a name="concept-overview"></a> ## Concept Overview > [!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: <?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { 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; Route::get('/user/{id}', function (string $id) { return new UserResource(User::findOrFail($id)); }); <a name="resource-collections"></a> ### 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; Route::get('/users', function () { return UserResource::collection(User::all()); }); 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: ```shell 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: <?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\ResourceCollection; class UserCollection extends ResourceCollection { /** * Transform the resource collection into an array. * * @return array<int|string, mixed> */ public function toArray(Request $request): array { 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; Route::get('/users', function () { return new UserCollection(User::all()); }); <a name="preserving-collection-keys"></a> #### 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: <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { /** * Indicates if the resource's collection keys should be preserved. * * @var bool */ public $preserveKeys = true; } When the `preserveKeys` property is set to `true`, collection keys will be preserved when the collection is returned from a route or controller: use App\Http\Resources\UserResource; use App\Models\User; Route::get('/users', function () { return UserResource::collection(User::all()->keyBy->id); }); <a name="customizing-the-underlying-resource-class"></a> #### 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: <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\ResourceCollection; class UserCollection extends ResourceCollection { /** * The resource that this resource collects. * * @var string */ public $collects = Member::class; } <a name="writing-resources"></a>
243175
## Writing Resources > [!NOTE] > If you have not read the [concept overview](#concept-overview), you are highly encouraged to do so before proceeding with this documentation. 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: <?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $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 (string $id) { return new UserResource(User::findOrFail($id)); }); <a name="relationships"></a> #### 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; /** * Transform the resource into an array. * * @return array<string, mixed> */ 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, ]; } > [!NOTE] > If you would like to include relationships only when they have already been loaded, check out the documentation on [conditional relationships](#conditional-relationships). <a name="writing-resource-collections"></a> #### 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: use App\Http\Resources\UserResource; use App\Models\User; Route::get('/users', function () { return UserResource::collection(User::all()); }); However, if you need to customize the meta data returned with the collection, it is necessary to define your own resource collection: <?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\ResourceCollection; class UserCollection extends ResourceCollection { /** * Transform the resource collection into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { 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; Route::get('/users', function () { return new UserCollection(User::all()); }); <a name="data-wrapping"></a> ### Data Wrapping By default, your outermost resource is wrapped in a `data` key when the resource response is converted to JSON. So, for example, a typical resource collection response looks like the following: ```json { "data": [ { "id": 1, "name": "Eladio Schroeder Sr.", "email": "therese28@example.com" }, { "id": 2, "name": "Liliana Mayert", "email": "evandervort@example.com" } ] } ``` 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: <?php namespace App\Providers; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any application services. */ public function register(): void { // ... } /** * Bootstrap any application services. */ public function boot(): void { JsonResource::withoutWrapping(); } } > [!WARNING] > The `withoutWrapping` method only affects the outermost response and will not remove `data` keys that you manually add to your own resource collections. <a name="wrapping-nested-resources"></a> #### Wrapping Nested Resources You have total freedom to determine how your resource's relationships are wrapped. If you would like all resource collections to be wrapped in a `data` key, regardless of their nesting, you should define a resource collection class for each resource and return the collection within a `data` key. 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: <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\ResourceCollection; class CommentsCollection extends ResourceCollection { /** * Transform the resource collection into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return ['data' => $this->collection]; } } <a name="data-wrapping-and-pagination"></a> #### 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: ```json { "data": [ { "id": 1, "name": "Eladio Schroeder Sr.", "email": "therese28@example.com" }, { "id": 2, "name": "Liliana Mayert", "email": "evandervort@example.com" } ], "links":{ "first": "http://example.com/users?page=1", "last": "http://example.com/users?page=1", "prev": null, "next": null }, "meta":{ "current_page": 1, "from": 1, "last_page": 1, "path": "http://example.com/users", "per_page": 15, "to": 10, "total": 10 } } ``` <a name="pagination"></a>
243176
### Pagination 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; Route::get('/users', function () { return new UserCollection(User::paginate()); }); Paginated responses always contain `meta` and `links` keys with information about the paginator's state: ```json { "data": [ { "id": 1, "name": "Eladio Schroeder Sr.", "email": "therese28@example.com" }, { "id": 2, "name": "Liliana Mayert", "email": "evandervort@example.com" } ], "links":{ "first": "http://example.com/users?page=1", "last": "http://example.com/users?page=1", "prev": null, "next": null }, "meta":{ "current_page": 1, "from": 1, "last_page": 1, "path": "http://example.com/users", "per_page": 15, "to": 10, "total": 10 } } ``` <a name="customizing-the-pagination-information"></a> #### 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: /** * 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; } <a name="conditional-attributes"></a> ### 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: /** * Transform the resource into an array. * * @return array<string, mixed> */ 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($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: '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: 'name' => $this->whenNotNull($this->name), <a name="merging-conditional-attributes"></a> #### 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. * * @return array<string, mixed> */ 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. > [!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. <a name="conditional-relationships"></a>
243177
### Conditional Relationships In addition to conditionally loading attributes, you may conditionally include relationships on your resource responses based on if the relationship has already been loaded on the model. This allows your controller to decide which relationships should be loaded on the model and your resource can easily include them only when they have actually been loaded. Ultimately, this makes it easier to avoid "N+1" query problems within your resources. 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; /** * Transform the resource into an array. * * @return array<string, mixed> */ 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. <a name="conditional-relationship-counts"></a> #### 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: 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: /** * Transform the resource into an array. * * @return array<string, mixed> */ 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'), ``` <a name="conditional-pivot-information"></a> #### 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. * * @return array<string, mixed> */ 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; }), If your intermediate table is using an accessor other than `pivot`, you may use the `whenPivotLoadedAs` method: /** * Transform the resource into an array. * * @return array<string, mixed> */ 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; }), ]; } <a name="adding-meta-data"></a> ### 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 `links` information when transforming a resource collection: /** * Transform the resource into an array. * * @return array<string, mixed> */ 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. <a name="top-level-meta-data"></a> #### Top Level Meta Data 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: <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\ResourceCollection; class UserCollection extends ResourceCollection { /** * Transform the resource collection into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return parent::toArray($request); } /** * Get additional data that should be returned with the resource array. * * @return array<string, mixed> */ public function with(Request $request): array { return [ 'meta' => [ 'key' => 'value', ], ]; } } <a name="adding-meta-data-when-constructing-resources"></a> #### 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', ]]); <a name="resource-responses"></a> ## 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; Route::get('/user/{id}', function (string $id) { return new UserResource(User::findOrFail($id)); }); 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; Route::get('/user', function () { return (new UserResource(User::find(1))) ->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: <?php namespace App\Http\Resources; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $this->id, ]; } /** * Customize the outgoing response for the resource. */ public function withResponse(Request $request, JsonResponse $response): void { $response->header('X-Value', 'True'); } }
243178
# Database Testing - [Introduction](#introduction) - [Resetting the Database After Each Test](#resetting-the-database-after-each-test) - [Model Factories](#model-factories) - [Running Seeders](#running-seeders) - [Available Assertions](#available-assertions) <a name="introduction"></a> ## Introduction 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. <a name="resetting-the-database-after-each-test"></a> ### 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: ```php tab=Pest <?php use Illuminate\Foundation\Testing\RefreshDatabase; uses(RefreshDatabase::class); test('basic example', function () { $response = $this->get('/'); // ... }); ``` ```php tab=PHPUnit <?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; class ExampleTest extends TestCase { use RefreshDatabase; /** * A basic functional test example. */ public function test_basic_example(): void { $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, 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. <a name="model-factories"></a> ## 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](/docs/{{version}}/eloquent-factories). 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: ```php tab=Pest use App\Models\User; test('models can be instantiated', function () { $user = User::factory()->create(); // ... }); ``` ```php tab=PHPUnit use App\Models\User; public function test_models_can_be_instantiated(): void { $user = User::factory()->create(); // ... } ``` <a name="running-seeders"></a> ## 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: ```php tab=Pest <?php use Database\Seeders\OrderStatusSeeder; use Database\Seeders\TransactionStatusSeeder; use Illuminate\Foundation\Testing\RefreshDatabase; uses(RefreshDatabase::class); test('orders can be created', function () { // Run the DatabaseSeeder... $this->seed(); // Run a specific seeder... $this->seed(OrderStatusSeeder::class); // ... // Run an array of specific seeders... $this->seed([ OrderStatusSeeder::class, TransactionStatusSeeder::class, // ... ]); }); ``` ```php tab=PHPUnit <?php namespace Tests\Feature; use Database\Seeders\OrderStatusSeeder; use Database\Seeders\TransactionStatusSeeder; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; class ExampleTest extends TestCase { use RefreshDatabase; /** * Test creating a new order. */ public function test_orders_can_be_created(): void { // Run the DatabaseSeeder... $this->seed(); // Run a specific seeder... $this->seed(OrderStatusSeeder::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: <?php namespace Tests; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { /** * Indicates whether the default seeder should run before each test. * * @var bool */ protected $seed = true; } When the `$seed` property is `true`, the test will run the `Database\Seeders\DatabaseSeeder` class before each test that uses the `RefreshDatabase` trait. However, you may specify a specific seeder that should be executed by defining a `$seeder` property on your test class: use Database\Seeders\OrderStatusSeeder; /** * Run a specific seeder before each test. * * @var string */ protected $seeder = OrderStatusSeeder::class; <a name="available-assertions"></a> ## Available Assertions 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. <a name="assert-database-count"></a> #### assertDatabaseCount Assert that a table in the database contains the given number of records: $this->assertDatabaseCount('users', 5); <a name="assert-database-has"></a> #### assertDatabaseHas Assert that a table in the database contains records matching the given key / value query constraints: $this->assertDatabaseHas('users', [ 'email' => 'sally@example.com', ]); <a name="assert-database-missing"></a> #### 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', ]); <a name="assert-deleted"></a> #### assertSoftDeleted The `assertSoftDeleted` method may be used to assert a given Eloquent model has been "soft deleted": $this->assertSoftDeleted($user); <a name="assert-not-deleted"></a> #### assertNotSoftDeleted The `assertNotSoftDeleted` method may be used to assert a given Eloquent model hasn't been "soft deleted": $this->assertNotSoftDeleted($user); <a name="assert-model-exists"></a> #### assertModelExists Assert that a given model exists in the database: use App\Models\User; $user = User::factory()->create(); $this->assertModelExists($user); <a name="assert-model-missing"></a> #### assertModelMissing Assert that a given model does not exist in the database: use App\Models\User; $user = User::factory()->create(); $user->delete(); $this->assertModelMissing($user); <a name="expects-database-query-count"></a> #### 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: $this->expectsDatabaseQueryCount(5); // Test...
243179
# Installation - [Meet Laravel](#meet-laravel) - [Why Laravel?](#why-laravel) - [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) - [Local Installation Using Herd](#local-installation-using-herd) - [Herd on macOS](#herd-on-macos) - [Herd on Windows](#herd-on-windows) - [Docker Installation Using Sail](#docker-installation-using-sail) - [Sail on macOS](#sail-on-macos) - [Sail on Windows](#sail-on-windows) - [Sail on Linux](#sail-on-linux) - [Choosing Your Sail Services](#choosing-your-sail-services) - [IDE Support](#ide-support) - [Next Steps](#next-steps) - [Laravel the Full Stack Framework](#laravel-the-fullstack-framework) - [Laravel the API Backend](#laravel-the-api-backend) <a name="meet-laravel"></a> ## Meet Laravel Laravel is a web application framework with expressive, elegant syntax. A web framework provides a structure and starting point for creating your application, allowing you to focus on creating something amazing while we sweat the details. 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 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. > [!NOTE] > New to Laravel? Check out the [Laravel Bootcamp](https://bootcamp.laravel.com) for a hands-on tour of the framework while we walk you through building your first Laravel application. <a name="why-laravel"></a> ### Why Laravel? There are a variety of tools and frameworks available to you when building a web application. However, we believe Laravel is the best choice for building modern, full-stack web applications. #### A Progressive Framework We like to call Laravel a "progressive" framework. By that, we mean that Laravel grows with you. If you're just taking your first steps into web development, Laravel's vast library of documentation, guides, and [video tutorials](https://laracasts.com) will help you learn the ropes without becoming overwhelmed. If you're a senior developer, Laravel gives you robust tools for [dependency injection](/docs/{{version}}/container), [unit testing](/docs/{{version}}/testing), [queues](/docs/{{version}}/queues), [real-time events](/docs/{{version}}/broadcasting), and more. Laravel is fine-tuned for building professional web applications and ready to handle enterprise work loads. #### A Scalable Framework 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. #### 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. <a name="creating-a-laravel-project"></a> ## Creating a Laravel Application <a name="installing-php"></a> ### Installing PHP and the Laravel Installer 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 [Node and NPM](https://nodejs.org) so that you can compile your application's frontend assets. 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: ```shell tab=macOS /bin/bash -c "$(curl -fsSL https://php.new/install/mac)" ``` ```shell tab=Windows PowerShell 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')) ``` ```shell tab=Linux /bin/bash -c "$(curl -fsSL https://php.new/install/linux)" ``` 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. If you already have PHP and Composer installed, you may install the Laravel installer via Composer: ```shell composer global require laravel/installer ``` > [!NOTE] > For a fully-featured, graphical PHP installation and management experience, check out [Laravel Herd](#local-installation-using-herd). <a name="creating-an-application"></a> ### Creating an Application 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: ```nothing laravel new example-app ``` 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: ```nothing cd example-app composer run dev ``` 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). > [!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. <a name="initial-configuration"></a>
243180
## Initial Configuration 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. 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. <a name="environment-based-configuration"></a> ### Environment Based Configuration 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. 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. > [!NOTE] > For more information about the `.env` file and environment based configuration, check out the full [configuration documentation](/docs/{{version}}/configuration#environment-configuration). <a name="databases-and-migrations"></a> ### Databases and Migrations 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 a SQLite database. 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. 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: ```ini DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD= ``` 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 php artisan migrate ``` > [!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). <a name="directory-configuration"></a> ### Directory Configuration 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. <a name="local-installation-using-herd"></a> ## Local Installation Using Herd [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. 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`. > [!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. <a name="herd-on-macos"></a> ### Herd on macOS 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. 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. After installing Herd, the fastest way to create a new Laravel application is using the Laravel CLI, which is bundled with Herd: ```nothing cd ~/Herd laravel new my-app cd my-app herd open ``` 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. You can learn more about Herd by checking out the [Herd documentation](https://herd.laravel.com/docs). <a name="herd-on-windows"></a> ### 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. 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. 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: ```nothing cd ~\Herd laravel new my-app cd my-app herd open ``` You can learn more about Herd by checking out the [Herd documentation for Windows](https://herd.laravel.com/docs/windows). <a name="docker-installation-using-sail"></a>
243183
# Laravel Fortify - [Introduction](#introduction) - [What is Fortify?](#what-is-fortify) - [When Should I Use Fortify?](#when-should-i-use-fortify) - [Installation](#installation) - [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 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) - [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) - [Customizing Password Resets](#customizing-password-resets) - [Email Verification](#email-verification) - [Protecting Routes](#protecting-routes) - [Password Confirmation](#password-confirmation) <a name="introduction"></a> ## Introduction [Laravel Fortify](https://github.com/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. After installing Fortify, you may run the `route:list` Artisan command to see the routes that Fortify has registered. 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. > [!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. <a name="what-is-fortify"></a> ### 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. 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. <a name="when-should-i-use-fortify"></a> ### 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. 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. If you choose to install Fortify, your user interface will make requests to Fortify's authentication routes that are detailed in this documentation in order to authenticate and register users. 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. <a name="laravel-fortify-and-laravel-sanctum"></a> #### 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. Laravel Sanctum is only concerned with managing API tokens and authenticating existing users using session cookies or tokens. Sanctum does not provide any routes that handle user registration, password reset, etc. If you are attempting to manually build the authentication layer for an application that offers an API or serves as the backend for a single-page application, it is entirely possible that you will utilize both Laravel Fortify (for user registration, password reset, etc.) and Laravel Sanctum (API token management, session authentication). <a name="installation"></a> ## Installation To get started, install Fortify using the Composer package manager: ```shell composer require laravel/fortify ``` Next, publish Fortify's resources using the `fortify:install` Artisan command: ```shell 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, the `FortifyServiceProvider`, configuration file, and all necessary database migrations will be published. Next, you should migrate your database: ```shell php artisan migrate ``` <a name="fortify-features"></a> ### 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: ```php 'features' => [ Features::registration(), Features::resetPasswords(), Features::emailVerification(), ], ``` <a name="disabling-views"></a> ### Disabling Views By default, Fortify defines routes that are intended to return views, such as a login screen or registration screen. However, if you are building a JavaScript driven single-page application, you may not need these routes. For that reason, you may disable these routes entirely by setting the `views` configuration value within your application's `config/fortify.php` configuration file to `false`: ```php 'views' => false, ``` <a name="disabling-views-and-password-reset"></a> #### 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. <a name="authentication"></a>
243184
## Authentication To get started, we need to instruct Fortify how to return our "login" 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 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; /** * 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. If the login attempt is successful, Fortify will redirect you 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 request was not successful, the user will be redirected back to the login 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 the 422 HTTP response. <a name="customizing-user-authentication"></a> ### Customizing User Authentication Fortify will automatically retrieve and authenticate the user based on the provided credentials and the authentication guard that is configured for your application. However, you may sometimes wish to have full customization over how login credentials are authenticated and users are retrieved. Thankfully, Fortify allows you to easily accomplish this using the `Fortify::authenticateUsing` method. This method accepts a closure which receives the incoming HTTP request. The closure is responsible for validating the login credentials attached to the request and returning the associated user instance. If the credentials are invalid or no user can be found, `null` or `false` should be returned by the closure. Typically, this method should be called from the `boot` method of your `FortifyServiceProvider`: ```php use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Laravel\Fortify\Fortify; /** * Bootstrap any application services. */ public function boot(): void { Fortify::authenticateUsing(function (Request $request) { $user = User::where('email', $request->email)->first(); if ($user && Hash::check($request->password, $user->password)) { return $user; } }); // ... } ``` <a name="authentication-guard"></a> #### Authentication Guard 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). <a name="customizing-the-authentication-pipeline"></a> ### 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. To define your custom pipeline, you may use the `Fortify::authenticateThrough` method. This method accepts a closure which should return the array of classes to pipe the login request through. Typically, this method should be called from the `boot` method of your `App\Providers\FortifyServiceProvider` class. The example below contains the default pipeline definition that you may use as a starting point when making your own modifications: ```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, ]); }); ``` #### 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. <a name="customizing-authentication-redirects"></a> ### Customizing Redirects If the login attempt is successful, Fortify will redirect you 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. After a user logs out of the application, the user will be redirected to the `/` URI. If you need advanced customization of this behavior, you may bind implementations of the `LoginResponse` and `LogoutResponse` contracts into the Laravel [service container](/docs/{{version}}/container). Typically, this should be done within the `register` method of your application's `App\Providers\FortifyServiceProvider` class: ```php use Laravel\Fortify\Contracts\LogoutResponse; /** * Register any application services. */ public function register(): void { $this->app->instance(LogoutResponse::class, new class implements LogoutResponse { public function toResponse($request) { return redirect('/'); } }); } ``` <a name="two-factor-authentication"></a>
243185
## 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. Before getting started, you should first ensure that your application's `App\Models\User` model uses the `Laravel\Fortify\TwoFactorAuthenticatable` trait: ```php <?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Fortify\TwoFactorAuthenticatable; 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. > 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. <a name="enabling-two-factor-authentication"></a> ### Enabling Two Factor Authentication 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') <div class="mb-4 font-medium text-sm"> Please finish configuring two factor authentication below. </div> @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: ```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. <a name="confirming-two-factor-authentication"></a> #### 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') <div class="mb-4 font-medium text-sm"> Two factor authentication confirmed and enabled successfully. </div> @endif ``` If the request to the two factor authentication confirmation endpoint was made via an XHR request, a `200` HTTP response will be returned. <a name="displaying-the-recovery-codes"></a> #### 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: ```php (array) $request->user()->recoveryCodes() ``` If you are building a JavaScript powered frontend, you may make an XHR GET request to the `/user/two-factor-recovery-codes` endpoint. This endpoint will return a JSON array containing the user's recovery codes. To regenerate the user's recovery codes, your application should make a POST request to the `/user/two-factor-recovery-codes` endpoint. <a name="authenticating-with-two-factor-authentication"></a> ### 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. 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. */ public function boot(): void { Fortify::twoFactorChallengeView(function () { return view('auth.two-factor-challenge'); }); // ... } ``` Fortify will take care of defining the `/two-factor-challenge` route that returns this view. Your `two-factor-challenge` template should include a form that makes a POST request to the `/two-factor-challenge` endpoint. The `/two-factor-challenge` action expects a `code` field that contains a valid TOTP token or a `recovery_code` field that contains one of the user's recovery codes. 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. <a name="disabling-two-factor-authentication"></a> ### 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. <a name="registration"></a> ## 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 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. */ public function boot(): void { Fortify::registerView(function () { return view('auth.register'); }); // ... } ``` Fortify will take care of defining the `/register` route that returns this view. Your `register` template should include a form that makes a POST request to the `/register` endpoint defined by Fortify. 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 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. <a name="customizing-registration"></a> ### Customizing Registration The user validation and creation process may be customized by modifying the `App\Actions\Fortify\CreateNewUser` action that was generated when you installed Laravel Fortify. <a name="password-reset"></a>
243186
## Password Reset <a name="requesting-a-password-reset-link"></a> ### 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). 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 application's `App\Providers\FortifyServiceProvider` class: ```php use Laravel\Fortify\Fortify; /** * Bootstrap any application services. */ public function boot(): void { Fortify::requestPasswordResetLinkView(function () { return view('auth.forgot-password'); }); // ... } ``` Fortify will take care of defining the `/forgot-password` endpoint that returns this view. Your `forgot-password` template should include a form that makes a POST request to the `/forgot-password` endpoint. 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. <a name="handling-the-password-reset-link-request-response"></a> #### 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 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')) <div class="mb-4 font-medium text-sm text-green-600"> {{ session('status') }} </div> @endif ``` 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. <a name="resetting-the-password"></a> ### Resetting the Password To finish implementing our application's password reset functionality, we need to instruct Fortify how to return our "reset password" view. 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 application's `App\Providers\FortifyServiceProvider` class: ```php use Laravel\Fortify\Fortify; use Illuminate\Http\Request; /** * Bootstrap any application services. */ public function boot(): void { Fortify::resetPasswordView(function (Request $request) { return view('auth.reset-password', ['request' => $request]); }); // ... } ``` Fortify will take care of defining the route to display this view. Your `reset-password` template should include a form that makes a POST request to `/reset-password`. 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. <a name="handling-the-password-reset-response"></a> #### 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: ```blade @if (session('status')) <div class="mb-4 font-medium text-sm text-green-600"> {{ session('status') }} </div> @endif ``` If the request was an XHR request, a 200 HTTP response will be returned. If the request was not successful, the user will be redirected back to the reset password 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. <a name="customizing-password-resets"></a> ### Customizing Password Resets The password reset process may be customized by modifying the `App\Actions\ResetUserPassword` action that was generated when you installed Laravel Fortify. <a name="email-verification"></a> ## Email Verification After registration, you may wish for users to verify their email address before they continue accessing your application. To get started, ensure the `emailVerification` feature is enabled in your `fortify` configuration file's `features` array. Next, you should ensure that your `App\Models\User` class implements the `Illuminate\Contracts\Auth\MustVerifyEmail` interface. Once these two setup steps have been completed, newly registered users will receive an email prompting them to verify their email address ownership. However, we need to inform Fortify how to display the email verification screen which informs the user that they need to go click the verification link in the email. All of Fortify's 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: ```php use Laravel\Fortify\Fortify; /** * Bootstrap any application services. */ public function boot(): void { Fortify::verifyEmailView(function () { return view('auth.verify-email'); }); // ... } ``` Fortify will take care of defining the route that displays this view when a user is redirected to the `/email/verify` endpoint by Laravel's built-in `verified` middleware. Your `verify-email` template should include an informational message instructing the user to click the email verification link that was sent to their email address. <a name="resending-email-verification-links"></a> #### Resending Email Verification Links If you wish, you may add a button to your application's `verify-email` template that triggers a POST request to the `/email/verification-notification` endpoint. When this endpoint receives a request, a new verification email link will be emailed to the user, allowing the user to get a new verification link if the previous one was accidentally deleted or lost. If the request to resend the verification link email was successful, Fortify will redirect the user back to the `/email/verify` endpoint with a `status` session variable, allowing you to display an informational message to the user informing them the operation was successful. If the request was an XHR request, a 202 HTTP response will be returned: ```blade @if (session('status') == 'verification-link-sent') <div class="mb-4 font-medium text-sm text-green-600"> A new email verification link has been emailed to you! </div> @endif ``` <a name="protecting-routes"></a> ### 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. 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 () { // ... })->middleware(['verified']); ``` <a name="password-confirmation"></a>
243188
# Events - [Introduction](#introduction) - [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 and Database Transactions](#queued-event-listeners-and-database-transactions) - [Handling Failed Jobs](#handling-failed-jobs) - [Dispatching Events](#dispatching-events) - [Dispatching Events After Database Transactions](#dispatching-events-after-database-transactions) - [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) <a name="introduction"></a> ## Introduction Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within your application. Event classes are typically stored in the `app/Events` directory, while their listeners are stored in `app/Listeners`. Don't worry if you don't see these directories in your application as they will be created for you as you generate events and listeners using Artisan console commands. 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. <a name="generating-events-and-listeners"></a> ## Generating Events and Listeners To quickly generate events and listeners, you may use the `make:event` and `make:listener` Artisan commands: ```shell php artisan make:event PodcastProcessed php artisan make:listener SendPodcastNotification --event=PodcastProcessed ``` 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 php artisan make:listener ``` <a name="registering-events-and-listeners"></a> ## Registering Events and Listeners <a name="event-discovery"></a> ### Event Discovery 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: use App\Events\PodcastProcessed; class SendPodcastNotification { /** * Handle the given event. */ public function handle(PodcastProcessed $event): void { // ... } } You may listen to multiple events using PHP's union types: /** * Handle the given event. */ public function handle(PodcastProcessed|PodcastPublished $event): void { // ... } 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: ->withEvents(discover: [ __DIR__.'/../app/Domain/Orders/Listeners', ]) The `event:list` command may be used to list all of the listeners registered within your application: ```shell php artisan event:list ``` <a name="event-discovery-in-production"></a> #### Event Discovery in Production 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. <a name="manually-registering-events"></a> ### 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`: 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 ``` <a name="closure-listeners"></a> ### Closure Listeners 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`: use App\Events\PodcastProcessed; use Illuminate\Support\Facades\Event; /** * Bootstrap any application services. */ public function boot(): void { Event::listen(function (PodcastProcessed $event) { // ... }); } <a name="queuable-anonymous-event-listeners"></a> #### Queueable Anonymous Event Listeners 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): use App\Events\PodcastProcessed; use function Illuminate\Events\queueable; use Illuminate\Support\Facades\Event; /** * Bootstrap any application services. */ public function boot(): void { Event::listen(queueable(function (PodcastProcessed $event) { // ... })); } Like queued jobs, you may use the `onConnection`, `onQueue`, and `delay` methods to customize the execution of the queued listener: Event::listen(queueable(function (PodcastProcessed $event) { // ... })->onConnection('redis')->onQueue('podcasts')->delay(now()->addSeconds(10))); 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: 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... })); <a name="wildcard-event-listeners"></a> #### Wildcard Event Listeners 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: Event::listen('event.*', function (string $eventName, array $data) { // ... }); <a name="defining-events"></a> ## 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: <?php namespace App\Events; use App\Models\Order; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; 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). <a name="defining-listeners"></a>
243193
# Controllers - [Introduction](#introduction) - [Writing Controllers](#writing-controllers) - [Basic Controllers](#basic-controllers) - [Single Action Controllers](#single-action-controllers) - [Controller Middleware](#controller-middleware) - [Resource Controllers](#resource-controllers) - [Partial Resource Routes](#restful-partial-resource-routes) - [Nested Resources](#restful-nested-resources) - [Naming Resource Routes](#restful-naming-resource-routes) - [Naming Resource Route Parameters](#restful-naming-resource-route-parameters) - [Scoping Resource Routes](#restful-scoping-resource-routes) - [Localizing Resource URIs](#restful-localizing-resource-uris) - [Supplementing Resource Controllers](#restful-supplementing-resource-controllers) - [Singleton Resource Controllers](#singleton-resource-controllers) - [Dependency Injection and Controllers](#dependency-injection-and-controllers) <a name="introduction"></a> ## Introduction Instead of defining all of your request handling logic as closures in your route files, you may wish to organize this behavior using "controller" classes. Controllers can group related request handling logic into a single class. For example, a `UserController` class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the `app/Http/Controllers` directory. <a name="writing-controllers"></a> ## Writing Controllers <a name="basic-controllers"></a> ### Basic Controllers 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: ```shell php artisan make:controller UserController ``` Let's take a look at an example of a basic controller. A controller may have any number of public methods which will respond to incoming HTTP requests: <?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\View\View; class UserController extends Controller { /** * Show the profile for a given user. */ public function show(string $id): View { return view('user.profile', [ 'user' => User::findOrFail($id) ]); } } 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; 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. > [!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. <a name="single-action-controllers"></a> ### 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: <?php namespace App\Http\Controllers; class ProvisionServer extends Controller { /** * Provision a new web server. */ public function __invoke() { // ... } } When registering routes for single action controllers, you do not need to specify a controller method. Instead, you may simply pass the name of the controller to the router: use App\Http\Controllers\ProvisionServer; Route::post('/server', ProvisionServer::class); You may generate an invokable controller by using the `--invokable` option of the `make:controller` Artisan command: ```shell php artisan make:controller ProvisionServer --invokable ``` > [!NOTE] > Controller stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization). <a name="controller-middleware"></a> ## 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'); 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 namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Routing\Controllers\HasMiddleware; use Illuminate\Routing\Controllers\Middleware; class UserController extends Controller implements HasMiddleware { /** * Get the middleware that should be assigned to the controller. */ public static function middleware(): array { return [ 'auth', new Middleware('log', only: ['index']), new Middleware('subscribed', except: ['store']), ]; } // ... } You may also define controller middleware as closures, which provides a convenient way to define an inline middleware without writing an entire middleware class: 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); }, ]; } <a name="resource-controllers"></a>
243194
## Resource Controllers If you think of each Eloquent model in your application as a "resource", it is typical to perform the same sets of actions against each resource in your application. For example, imagine your application contains a `Photo` model and a `Movie` model. It is likely that users can create, read, update, or delete these resources. Because of this common use case, Laravel resource routing assigns the typical create, read, update, and delete ("CRUD") routes to a controller with a single line of code. To get started, we can use the `make:controller` Artisan command's `--resource` option to quickly create a controller to handle these actions: ```shell 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; 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, ]); <a name="actions-handled-by-resource-controllers"></a> #### Actions Handled by Resource Controllers <div class="overflow-auto"> | 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 | </div> <a name="customizing-missing-model-behavior"></a> #### 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 cannot be found for any of the resource's routes: 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'); }); <a name="soft-deleted-models"></a> #### 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; 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: Route::resource('photos', PhotoController::class)->withTrashed(['show']); <a name="specifying-the-resource-model"></a> #### 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: ```shell php artisan make:controller PhotoController --model=Photo --resource ``` <a name="generating-form-requests"></a> #### Generating Form Requests You may provide the `--requests` option when generating a resource controller to instruct Artisan to generate [form request classes](/docs/{{version}}/validation#form-request-validation) for the controller's storage and update methods: ```shell php artisan make:controller PhotoController --model=Photo --resource --requests ``` <a name="restful-partial-resource-routes"></a> ### Partial Resource Routes 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; Route::resource('photos', PhotoController::class)->only([ 'index', 'show' ]); Route::resource('photos', PhotoController::class)->except([ 'create', 'store', 'update', 'destroy' ]); <a name="api-resource-routes"></a> #### 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; 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; 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: ```shell php artisan make:controller PhotoController --api ``` <a name="restful-nested-resources"></a> ### Nested Resources 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; 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} <a name="scoping-nested-resources"></a> #### Scoping Nested Resources Laravel's [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. For more information on how to accomplish this, please see the documentation on [scoping resource routes](#restful-scoping-resource-routes). <a name="shallow-nesting"></a> #### Shallow Nesting 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; Route::resource('photos.comments', CommentController::class)->shallow(); This route definition will define the following routes: <div class="overflow-auto"> | 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 | </div> <a name="restful-naming-resource-routes"></a> ### 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; Route::resource('photos', PhotoController::class)->names([ 'create' => 'photos.build' ]); <a name="restful-naming-resource-route-parameters"></a>
243195
### 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; Route::resource('users', AdminUserController::class)->parameters([ 'users' => 'admin_user' ]); The example above generates the following URI for the resource's `show` route: /users/{admin_user} <a name="restful-scoping-resource-routes"></a> ### 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; 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} 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. <a name="restful-localizing-resource-uris"></a> ### Localizing Resource URIs 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`: /** * Bootstrap any application services. */ public function boot(): void { Route::resourceVerbs([ 'create' => 'crear', 'edit' => 'editar', ]); } 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: /publicacion/crear /publicacion/{publicaciones}/editar <a name="restful-supplementing-resource-controllers"></a> ### 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; 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. <a name="singleton-resource-controllers"></a> ### 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: <div class="overflow-auto"> | Verb | URI | Action | Route Name | | --------- | --------------- | ------ | -------------- | | GET | `/profile` | show | profile.show | | GET | `/profile/edit` | edit | profile.edit | | PUT/PATCH | `/profile` | update | profile.update | </div> 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: <div class="overflow-auto"> | 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 | </div> <a name="creatable-singleton-resources"></a> #### 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: <div class="overflow-auto"> | 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 | </div> 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(); ``` <a name="api-singleton-resources"></a> #### 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(); ``` <a name="dependency-injection-and-controllers"></a>
243196
## Dependency Injection and Controllers <a name="constructor-injection"></a> #### 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: <?php namespace App\Http\Controllers; use App\Repositories\UserRepository; class UserController extends Controller { /** * Create a new controller instance. */ public function __construct( protected UserRepository $users, ) {} } <a name="method-injection"></a> #### 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: <?php namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class UserController extends Controller { /** * Store a new user. */ public function store(Request $request): RedirectResponse { $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; 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: <?php namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class UserController extends Controller { /** * Update the given user. */ public function update(Request $request, string $id): RedirectResponse { // Update the user... return redirect('/users'); } }
243197
# Laravel Sanctum - [Introduction](#introduction) - [How it Works](#how-it-works) - [Installation](#installation) - [Configuration](#configuration) - [Overriding Default Models](#overriding-default-models) - [API Token Authentication](#api-token-authentication) - [Issuing API Tokens](#issuing-api-tokens) - [Token Abilities](#token-abilities) - [Protecting Routes](#protecting-routes) - [Revoking Tokens](#revoking-tokens) - [Token Expiration](#token-expiration) - [SPA Authentication](#spa-authentication) - [Configuration](#spa-configuration) - [Authenticating](#spa-authenticating) - [Protecting Routes](#protecting-spa-routes) - [Authorizing Private Broadcast Channels](#authorizing-private-broadcast-channels) - [Mobile Application Authentication](#mobile-application-authentication) - [Issuing API Tokens](#issuing-mobile-api-tokens) - [Protecting Routes](#protecting-mobile-api-routes) - [Revoking Tokens](#revoking-mobile-api-tokens) - [Testing](#testing) <a name="introduction"></a> ## Introduction [Laravel Sanctum](https://github.com/laravel/sanctum) provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform. <a name="how-it-works"></a> ### How it Works Laravel Sanctum exists to solve two separate problems. Let's discuss each before digging deeper into the library. <a name="how-it-works-api-tokens"></a> #### API Tokens First, Sanctum is a simple package you may use to issue API tokens to your users without the complication of OAuth. This feature is inspired by GitHub and other applications which issue "personal access tokens". For example, imagine the "account settings" of your application has a screen where a user may generate an API token for their account. You may use Sanctum to generate and manage those tokens. These tokens typically have a very long expiration time (years), but may be manually revoked by the user anytime. Laravel Sanctum offers this feature by storing user API tokens in a single database table and authenticating incoming HTTP requests via the `Authorization` header which should contain a valid API token. <a name="how-it-works-spa-authentication"></a> #### SPA Authentication Second, Sanctum exists to offer a simple way to authenticate single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository, such as an SPA created using Next.js or Nuxt. For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. Typically, Sanctum utilizes Laravel's `web` authentication guard to accomplish this. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS. Sanctum will only attempt to authenticate using cookies when the incoming request originates from your own SPA frontend. When Sanctum examines an incoming HTTP request, it will first check for an authentication cookie and, if none is present, Sanctum will then examine the `Authorization` header for a valid API token. > [!NOTE] > It is perfectly fine to use Sanctum only for API token authentication or only for SPA authentication. Just because you use Sanctum does not mean you are required to use both features it offers. <a name="installation"></a> ## Installation You may install Laravel Sanctum via the `install:api` Artisan command: ```shell php artisan install:api ``` Next, if you plan to utilize Sanctum to authenticate an SPA, please refer to the [SPA Authentication](#spa-authentication) section of this documentation. <a name="configuration"></a> ## Configuration <a name="overriding-default-models"></a> ### Overriding Default Models Although not typically required, you are free to extend the `PersonalAccessToken` model used internally by Sanctum: use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken; class PersonalAccessToken extends SanctumPersonalAccessToken { // ... } Then, you may instruct Sanctum to use your custom model via the `usePersonalAccessTokenModel` method provided by Sanctum. Typically, you should call this method in the `boot` method of your application's `AppServiceProvider` file: use App\Models\Sanctum\PersonalAccessToken; use Laravel\Sanctum\Sanctum; /** * Bootstrap any application services. */ public function boot(): void { Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class); } <a name="api-token-authentication"></a>
243198
## API Token Authentication > [!NOTE] > You should not use API tokens to authenticate your own first-party SPA. Instead, use Sanctum's built-in [SPA authentication features](#spa-authentication). <a name="issuing-api-tokens"></a> ### Issuing API Tokens Sanctum allows you to issue API tokens / personal access tokens that may be used to authenticate API requests to your application. When making requests using API tokens, the token should be included in the `Authorization` header as a `Bearer` token. To begin issuing tokens for users, your User model should use the `Laravel\Sanctum\HasApiTokens` trait: use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; } To issue a token, you may use the `createToken` method. The `createToken` method returns a `Laravel\Sanctum\NewAccessToken` instance. API tokens are hashed using SHA-256 hashing before being stored in your database, but you may access the plain-text value of the token using the `plainTextToken` property of the `NewAccessToken` instance. You should display this value to the user immediately after the token has been created: use Illuminate\Http\Request; Route::post('/tokens/create', function (Request $request) { $token = $request->user()->createToken($request->token_name); return ['token' => $token->plainTextToken]; }); You may access all of the user's tokens using the `tokens` Eloquent relationship provided by the `HasApiTokens` trait: foreach ($user->tokens as $token) { // ... } <a name="token-abilities"></a> ### Token Abilities Sanctum allows you to assign "abilities" to tokens. Abilities serve a similar purpose as OAuth's "scopes". You may pass an array of string abilities as the second argument to the `createToken` method: return $user->createToken('token-name', ['server:update'])->plainTextToken; When handling an incoming request authenticated by Sanctum, you may determine if the token has a given ability using the `tokenCan` method: if ($user->tokenCan('server:update')) { // ... } <a name="token-ability-middleware"></a> #### Token Ability Middleware Sanctum also includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given ability. To get started, define the following middleware aliases in your application's `bootstrap/app.php` file: use Laravel\Sanctum\Http\Middleware\CheckAbilities; use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility; ->withMiddleware(function (Middleware $middleware) { $middleware->alias([ 'abilities' => CheckAbilities::class, 'ability' => CheckForAnyAbility::class, ]); }) The `abilities` middleware may be assigned to a route to verify that the incoming request's token has all of the listed abilities: Route::get('/orders', function () { // Token has both "check-status" and "place-orders" abilities... })->middleware(['auth:sanctum', 'abilities:check-status,place-orders']); The `ability` middleware may be assigned to a route to verify that the incoming request's token has *at least one* of the listed abilities: Route::get('/orders', function () { // Token has the "check-status" or "place-orders" ability... })->middleware(['auth:sanctum', 'ability:check-status,place-orders']); <a name="first-party-ui-initiated-requests"></a> #### First-Party UI Initiated Requests For convenience, the `tokenCan` method will always return `true` if the incoming authenticated request was from your first-party SPA and you are using Sanctum's built-in [SPA authentication](#spa-authentication). However, this does not necessarily mean that your application has to allow the user to perform the action. Typically, your application's [authorization policies](/docs/{{version}}/authorization#creating-policies) will determine if the token has been granted the permission to perform the abilities as well as check that the user instance itself should be allowed to perform the action. For example, if we imagine an application that manages servers, this might mean checking that the token is authorized to update servers **and** that the server belongs to the user: ```php return $request->user()->id === $server->user_id && $request->user()->tokenCan('server:update') ``` At first, allowing the `tokenCan` method to be called and always return `true` for first-party UI initiated requests may seem strange; however, it is convenient to be able to always assume an API token is available and can be inspected via the `tokenCan` method. By taking this approach, you may always call the `tokenCan` method within your application's authorization policies without worrying about whether the request was triggered from your application's UI or was initiated by one of your API's third-party consumers. <a name="protecting-routes"></a> ### Protecting Routes To protect routes so that all incoming requests must be authenticated, you should attach the `sanctum` authentication guard to your protected routes within your `routes/web.php` and `routes/api.php` route files. This guard will ensure that incoming requests are authenticated as either stateful, cookie authenticated requests or contain a valid API token header if the request is from a third party. You may be wondering why we suggest that you authenticate the routes within your application's `routes/web.php` file using the `sanctum` guard. Remember, Sanctum will first attempt to authenticate incoming requests using Laravel's typical session authentication cookie. If that cookie is not present then Sanctum will attempt to authenticate the request using a token in the request's `Authorization` header. In addition, authenticating all requests using Sanctum ensures that we may always call the `tokenCan` method on the currently authenticated user instance: use Illuminate\Http\Request; Route::get('/user', function (Request $request) { return $request->user(); })->middleware('auth:sanctum'); <a name="revoking-tokens"></a> ### Revoking Tokens You may "revoke" tokens by deleting them from your database using the `tokens` relationship that is provided by the `Laravel\Sanctum\HasApiTokens` trait: // Revoke all tokens... $user->tokens()->delete(); // Revoke the token that was used to authenticate the current request... $request->user()->currentAccessToken()->delete(); // Revoke a specific token... $user->tokens()->where('id', $tokenId)->delete(); <a name="token-expiration"></a> ### Token Expiration By default, Sanctum tokens never expire and may only be invalidated by [revoking the token](#revoking-tokens). However, if you would like to configure an expiration time for your application's API tokens, you may do so via the `expiration` configuration option defined in your application's `sanctum` configuration file. This configuration option defines the number of minutes until an issued token will be considered expired: ```php 'expiration' => 525600, ``` If you would like to specify the expiration time of each token independently, you may do so by providing the expiration time as the third argument to the `createToken` method: ```php return $user->createToken( 'token-name', ['*'], now()->addWeek() )->plainTextToken; ``` If you have configured a token expiration time for your application, you may also wish to [schedule a task](/docs/{{version}}/scheduling) to prune your application's expired tokens. Thankfully, Sanctum includes a `sanctum:prune-expired` Artisan command that you may use to accomplish this. For example, you may configure a scheduled task to delete all expired token database records that have been expired for at least 24 hours: ```php use Illuminate\Support\Facades\Schedule; Schedule::command('sanctum:prune-expired --hours=24')->daily(); ``` <a name="spa-authentication"></a>
243199
## SPA Authentication Sanctum also exists to provide a simple method of authenticating single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository. For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. This approach to authentication provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS. > [!WARNING] > In order to authenticate, your SPA and API must share the same top-level domain. However, they may be placed on different subdomains. Additionally, you should ensure that you send the `Accept: application/json` header and either the `Referer` or `Origin` header with your request. <a name="spa-configuration"></a> ### Configuration <a name="configuring-your-first-party-domains"></a> #### Configuring Your First-Party Domains First, you should configure which domains your SPA will be making requests from. You may configure these domains using the `stateful` configuration option in your `sanctum` configuration file. This configuration setting determines which domains will maintain "stateful" authentication using Laravel session cookies when making requests to your API. > [!WARNING] > If you are accessing your application via a URL that includes a port (`127.0.0.1:8000`), you should ensure that you include the port number with the domain. <a name="sanctum-middleware"></a> #### Sanctum Middleware Next, you should instruct Laravel that incoming requests from your SPA can authenticate using Laravel's session cookies, while still allowing requests from third parties or mobile applications to authenticate using API tokens. This can be easily accomplished by invoking the `statefulApi` middleware method in your application's `bootstrap/app.php` file: ->withMiddleware(function (Middleware $middleware) { $middleware->statefulApi(); }) <a name="cors-and-cookies"></a> #### CORS and Cookies If you are having trouble authenticating with your application from an SPA that executes on a separate subdomain, you have likely misconfigured your CORS (Cross-Origin Resource Sharing) or session cookie settings. The `config/cors.php` configuration file is not published by default. If you need to customize Laravel's CORS options, you should publish the complete `cors` configuration file using the `config:publish` Artisan command: ```bash php artisan config:publish cors ``` Next, you should ensure that your application's CORS configuration is returning the `Access-Control-Allow-Credentials` header with a value of `True`. This may be accomplished by setting the `supports_credentials` option within your application's `config/cors.php` configuration file to `true`. In addition, you should enable the `withCredentials` and `withXSRFToken` options on your application's global `axios` instance. Typically, this should be performed in your `resources/js/bootstrap.js` file. If you are not using Axios to make HTTP requests from your frontend, you should perform the equivalent configuration on your own HTTP client: ```js axios.defaults.withCredentials = true; axios.defaults.withXSRFToken = true; ``` Finally, you should ensure your application's session cookie domain configuration supports any subdomain of your root domain. You may accomplish this by prefixing the domain with a leading `.` within your application's `config/session.php` configuration file: 'domain' => '.domain.com', <a name="spa-authenticating"></a> ### Authenticating <a name="csrf-protection"></a> #### CSRF Protection To authenticate your SPA, your SPA's "login" page should first make a request to the `/sanctum/csrf-cookie` endpoint to initialize CSRF protection for the application: ```js axios.get('/sanctum/csrf-cookie').then(response => { // Login... }); ``` During this request, Laravel will set an `XSRF-TOKEN` cookie containing the current CSRF token. This token should then be passed in an `X-XSRF-TOKEN` header on subsequent requests, which some HTTP client libraries like Axios and the Angular HttpClient will do automatically for you. If your JavaScript HTTP library does not set the value for you, you will need to manually set the `X-XSRF-TOKEN` header to match the value of the `XSRF-TOKEN` cookie that is set by this route. <a name="logging-in"></a> #### Logging In Once CSRF protection has been initialized, you should make a `POST` request to your Laravel application's `/login` route. This `/login` route may be [implemented manually](/docs/{{version}}/authentication#authenticating-users) or using a headless authentication package like [Laravel Fortify](/docs/{{version}}/fortify). If the login request is successful, you will be authenticated and subsequent requests to your application's routes will automatically be authenticated via the session cookie that the Laravel application issued to your client. In addition, since your application already made a request to the `/sanctum/csrf-cookie` route, subsequent requests should automatically receive CSRF protection as long as your JavaScript HTTP client sends the value of the `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. Of course, if your user's session expires due to lack of activity, subsequent requests to the Laravel application may receive a 401 or 419 HTTP error response. In this case, you should redirect the user to your SPA's login page. > [!WARNING] > You are free to write your own `/login` endpoint; however, you should ensure that it authenticates the user using the standard, [session based authentication services that Laravel provides](/docs/{{version}}/authentication#authenticating-users). Typically, this means using the `web` authentication guard. <a name="protecting-spa-routes"></a> ### Protecting Routes To protect routes so that all incoming requests must be authenticated, you should attach the `sanctum` authentication guard to your API routes within your `routes/api.php` file. This guard will ensure that incoming requests are authenticated as either stateful authenticated requests from your SPA or contain a valid API token header if the request is from a third party: use Illuminate\Http\Request; Route::get('/user', function (Request $request) { return $request->user(); })->middleware('auth:sanctum'); <a name="authorizing-private-broadcast-channels"></a> ### Authorizing Private Broadcast Channels If your SPA needs to authenticate with [private / presence broadcast channels](/docs/{{version}}/broadcasting#authorizing-channels), you should remove the `channels` entry from the `withRouting` method contained in your application's `bootstrap/app.php` file. Instead, you should invoke the `withBroadcasting` method so that you may specify the correct middleware for your application's broadcasting routes: return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', // ... ) ->withBroadcasting( __DIR__.'/../routes/channels.php', ['prefix' => 'api', 'middleware' => ['api', 'auth:sanctum']], ) Next, in order for Pusher's authorization requests to succeed, you will need to provide a custom Pusher `authorizer` when initializing [Laravel Echo](/docs/{{version}}/broadcasting#client-side-installation). This allows your application to configure Pusher to use the `axios` instance that is [properly configured for cross-domain requests](#cors-and-cookies): ```js window.Echo = new Echo({ broadcaster: "pusher", cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER, encrypted: true, key: import.meta.env.VITE_PUSHER_APP_KEY, 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); }); } }; }, }) ``` <a name="mobile-application-authentication"></a>
243200
## Mobile Application Authentication You may also use Sanctum tokens to authenticate your mobile application's requests to your API. The process for authenticating mobile application requests is similar to authenticating third-party API requests; however, there are small differences in how you will issue the API tokens. <a name="issuing-mobile-api-tokens"></a> ### Issuing API Tokens To get started, create a route that accepts the user's email / username, password, and device name, then exchanges those credentials for a new Sanctum token. The "device name" given to this endpoint is for informational purposes and may be any value you wish. In general, the device name value should be a name the user would recognize, such as "Nuno's iPhone 12". Typically, you will make a request to the token endpoint from your mobile application's "login" screen. The endpoint will return the plain-text API token which may then be stored on the mobile device and used to make additional API requests: use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\ValidationException; Route::post('/sanctum/token', function (Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required', 'device_name' => 'required', ]); $user = User::where('email', $request->email)->first(); if (! $user || ! Hash::check($request->password, $user->password)) { throw ValidationException::withMessages([ 'email' => ['The provided credentials are incorrect.'], ]); } return $user->createToken($request->device_name)->plainTextToken; }); When the mobile application uses the token to make an API request to your application, it should pass the token in the `Authorization` header as a `Bearer` token. > [!NOTE] > When issuing tokens for a mobile application, you are also free to specify [token abilities](#token-abilities). <a name="protecting-mobile-api-routes"></a> ### Protecting Routes As previously documented, you may protect routes so that all incoming requests must be authenticated by attaching the `sanctum` authentication guard to the routes: Route::get('/user', function (Request $request) { return $request->user(); })->middleware('auth:sanctum'); <a name="revoking-mobile-api-tokens"></a> ### Revoking Tokens To allow users to revoke API tokens issued to mobile devices, you may list them by name, along with a "Revoke" button, within an "account settings" portion of your web application's UI. When the user clicks the "Revoke" button, you can delete the token from the database. Remember, you can access a user's API tokens via the `tokens` relationship provided by the `Laravel\Sanctum\HasApiTokens` trait: // Revoke all tokens... $user->tokens()->delete(); // Revoke a specific token... $user->tokens()->where('id', $tokenId)->delete(); <a name="testing"></a> ## Testing While testing, the `Sanctum::actingAs` method may be used to authenticate a user and specify which abilities should be granted to their token: ```php tab=Pest use App\Models\User; use Laravel\Sanctum\Sanctum; test('task list can be retrieved', function () { Sanctum::actingAs( User::factory()->create(), ['view-tasks'] ); $response = $this->get('/api/task'); $response->assertOk(); }); ``` ```php tab=PHPUnit use App\Models\User; use Laravel\Sanctum\Sanctum; public function test_task_list_can_be_retrieved(): void { Sanctum::actingAs( User::factory()->create(), ['view-tasks'] ); $response = $this->get('/api/task'); $response->assertOk(); } ``` If you would like to grant all abilities to the token, you should include `*` in the ability list provided to the `actingAs` method: Sanctum::actingAs( User::factory()->create(), ['*'] );
243202
## Serving Sites Once Valet is installed, you're ready to start serving your Laravel applications. Valet provides two commands to help you serve your applications: `park` and `link`. <a name="the-park-command"></a> ### The `park` Command The `park` command registers a directory on your machine that contains your applications. Once the directory has been "parked" with Valet, all of the directories within that directory will be accessible in your web browser at `http://<directory-name>.test`: ```shell cd ~/Sites valet park ``` That's all there is to it. Now, any application you create within your "parked" directory will automatically be served using the `http://<directory-name>.test` convention. So, if your parked directory contains a directory named "laravel", the application within that directory will be accessible at `http://laravel.test`. In addition, Valet automatically allows you to access the site using wildcard subdomains (`http://foo.laravel.test`). <a name="the-link-command"></a> ### The `link` Command The `link` command can also be used to serve your Laravel applications. This command is useful if you want to serve a single site in a directory and not the entire directory: ```shell cd ~/Sites/laravel valet link ``` Once an application has been linked to Valet using the `link` command, you may access the application using its directory name. So, the site that was linked in the example above may be accessed at `http://laravel.test`. In addition, Valet automatically allows you to access the site using wildcard sub-domains (`http://foo.laravel.test`). If you would like to serve the application at a different hostname, you may pass the hostname to the `link` command. For example, you may run the following command to make an application available at `http://application.test`: ```shell 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 valet links ``` The `unlink` command may be used to destroy the symbolic link for a site: ```shell cd ~/Sites/laravel valet unlink ``` <a name="securing-sites"></a> ### Securing Sites With TLS By default, Valet serves sites over HTTP. However, if you would like to serve a site over encrypted TLS using HTTP/2, you may use the `secure` command. For example, if your site is being served by Valet on the `laravel.test` domain, you should run the following command to secure it: ```shell valet secure laravel ``` To "unsecure" a site and revert back to serving its traffic over plain HTTP, use the `unsecure` command. Like the `secure` command, this command accepts the hostname that you wish to unsecure: ```shell valet unsecure laravel ``` <a name="serving-a-default-site"></a> ### 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/example-site", <a name="per-site-php-versions"></a> ### 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 ``` <a name="sharing-sites"></a> ## Sharing Sites 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. 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 either `ngrok` or `expose`: ```shell valet share-tool ngrok ``` If you choose a tool and don't have it installed via Homebrew (for ngrok) 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 valet share ``` To stop sharing your site, you may press `Control + C`. > [!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. <a name="sharing-sites-via-ngrok"></a> #### Sharing Sites via Ngrok 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 valet set-ngrok-token YOUR_TOKEN_HERE ``` > [!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). <a name="sharing-sites-via-expose"></a> #### 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. <a name="sharing-sites-on-your-local-network"></a> ### 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. If you wish to allow other devices on your local network to access the Valet sites on your machine via your machine's IP address (eg: `192.168.1.10/application.test`), you will need to manually edit the appropriate Nginx configuration file for that site to remove the restriction on the `listen` directive. You should remove the `127.0.0.1:` prefix on the `listen` directive for ports 80 and 443. If you have not run `valet secure` on the project, you can open up network access for all non-HTTPS sites by editing the `/usr/local/etc/nginx/valet/valet.conf` file. However, if you're serving the project site over HTTPS (you have run `valet secure` for the site) then you should edit the `~/.config/valet/Nginx/app-name.test` file. Once you have updated your Nginx configuration, run the `valet restart` command to apply the configuration changes. <a name="site-specific-environment-variables"></a>
243203
## Site Specific Environment Variables 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: <?php return [ // Set $_SERVER['key'] to "value" for the laravel.test site... 'laravel' => [ 'key' => 'value', ], // Set $_SERVER['key'] to "value" for all sites... '*' => [ 'key' => 'value', ], ]; <a name="proxying-services"></a> ## Proxying Services Sometimes you may wish to proxy a Valet domain to another service on your local machine. For example, you may occasionally need to run Valet while also running a separate site in Docker; however, Valet and Docker can't both bind to port 80 at the same time. To solve this, you may use the `proxy` command to generate a proxy. For example, you may proxy all traffic from `http://elasticsearch.test` to `http://127.0.0.1:9200`: ```shell # Proxy over HTTP... valet proxy elasticsearch http://127.0.0.1:9200 # Proxy over TLS + HTTP/2... valet proxy elasticsearch http://127.0.0.1:9200 --secure ``` You may remove a proxy using the `unproxy` command: ```shell valet unproxy elasticsearch ``` You may use the `proxies` command to list all site configurations that are proxied: ```shell valet proxies ``` <a name="custom-valet-drivers"></a> ## Custom Valet Drivers You can write your own Valet "driver" to serve PHP applications running on a framework or CMS that is not natively supported by Valet. When you install Valet, a `~/.config/valet/Drivers` directory is created which contains a `SampleValetDriver.php` file. This file contains a sample driver implementation to demonstrate how to write a custom driver. Writing a driver only requires you to implement three methods: `serves`, `isStaticFile`, and `frontControllerPath`. All three methods receive the `$sitePath`, `$siteName`, and `$uri` values as their arguments. The `$sitePath` is the fully qualified path to the site being served on your machine, such as `/Users/Lisa/Sites/my-project`. The `$siteName` is the "host" / "site name" portion of the domain (`my-project`). The `$uri` is the incoming request URI (`/foo/bar`). Once you have completed your custom Valet driver, place it in the `~/.config/valet/Drivers` directory using the `FrameworkValetDriver.php` naming convention. For example, if you are writing a custom valet driver for WordPress, your filename should be `WordPressValetDriver.php`. Let's take a look at a sample implementation of each method your custom Valet driver should implement. <a name="the-serves-method"></a> #### The `serves` Method The `serves` method should return `true` if your driver should handle the incoming request. Otherwise, the method should return `false`. So, within this method, you should attempt to determine if the given `$sitePath` contains a project of the type you are trying to serve. 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. */ public function serves(string $sitePath, string $siteName, string $uri): bool { return is_dir($sitePath.'/wp-admin'); } <a name="the-isstaticfile-method"></a> #### 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. * * @return string|false */ public function isStaticFile(string $sitePath, string $siteName, string $uri) { if (file_exists($staticFilePath = $sitePath.'/public/'.$uri)) { return $staticFilePath; } 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 `/`. <a name="the-frontcontrollerpath-method"></a> #### 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. */ public function frontControllerPath(string $sitePath, string $siteName, string $uri): string { return $sitePath.'/public/index.php'; } <a name="local-drivers"></a> ### 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`: 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 { 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'; } } <a name="other-valet-commands"></a> ## Other Valet Commands <div class="overflow-auto"> | 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. | </div> <a name="valet-directories-and-files"></a>
243207
### Per Project Installation Instead of installing Homestead globally and sharing the same Homestead virtual machine across all of your projects, you may instead configure a Homestead instance for each project you manage. Installing Homestead per project may be beneficial if you wish to ship a `Vagrantfile` with your project, allowing others working on the project to `vagrant up` immediately after cloning the project's repository. You may install Homestead into your project using the Composer package manager: ```shell composer require laravel/homestead --dev ``` Once Homestead has been installed, invoke Homestead's `make` command to generate the `Vagrantfile` and `Homestead.yaml` file for your project. These files will be placed in the root of your project. The `make` command will automatically configure the `sites` and `folders` directives in the `Homestead.yaml` file: ```shell # macOS / Linux... php vendor/bin/homestead make # Windows... vendor\\bin\\homestead make ``` Next, run the `vagrant up` command in your terminal and access your project at `http://homestead.test` in your browser. Remember, you will still need to add an `/etc/hosts` file entry for `homestead.test` or the domain of your choice if you are not using automatic [hostname resolution](#hostname-resolution). <a name="installing-optional-features"></a> ### Installing Optional Features Optional software is installed using the `features` option within your `Homestead.yaml` file. Most features can be enabled or disabled with a boolean value, while some features allow multiple configuration options: ```yaml features: - blackfire: server_id: "server_id" server_token: "server_value" client_id: "client_id" client_token: "client_value" - cassandra: true - chronograf: true - couchdb: true - crystal: 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 - mongodb: true - neo4j: true - ohmyzsh: true - openresty: true - pm2: true - python: true - r-base: true - rabbitmq: true - rustc: true - rvm: true - solr: true - timescaledb: true - trader: true - webdriver: true ``` <a name="elasticsearch"></a> #### Elasticsearch 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. > [!NOTE] > Check out the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current) to learn how to customize your configuration. <a name="mariadb"></a> #### MariaDB Enabling MariaDB will remove MySQL and install MariaDB. MariaDB typically serves as a drop-in replacement for MySQL, so you should still use the `mysql` database driver in your application's database configuration. <a name="mongodb"></a> #### MongoDB The default MongoDB installation will set the database username to `homestead` and the corresponding password to `secret`. <a name="neo4j"></a> #### Neo4j The default Neo4j installation will set the database username to `homestead` and the corresponding password to `secret`. To access the Neo4j browser, visit `http://homestead.test:7474` via your web browser. The ports `7687` (Bolt), `7474` (HTTP), and `7473` (HTTPS) are ready to serve requests from the Neo4j client. <a name="aliases"></a> ### Aliases You may add Bash aliases to your Homestead virtual machine by modifying the `aliases` file within your Homestead directory: ```shell alias c='clear' alias ..='cd ..' ``` After you have updated the `aliases` file, you should re-provision the Homestead virtual machine using the `vagrant reload --provision` command. This will ensure that your new aliases are available on the machine. <a name="updating-homestead"></a> ## Updating Homestead Before you begin updating Homestead you should ensure you have removed your current virtual machine by running the following command in your Homestead directory: ```shell vagrant destroy ``` Next, you need to update the Homestead source code. If you cloned the repository, you can execute the following commands at the location you originally cloned the repository: ```shell git fetch git pull origin release ``` These commands pull the latest Homestead code from the GitHub repository, fetch the latest tags, and then check out the latest tagged release. You can find the latest stable release version on Homestead's [GitHub releases page](https://github.com/laravel/homestead/releases). If you have installed Homestead via your project's `composer.json` file, you should ensure your `composer.json` file contains `"laravel/homestead": "^12"` and update your dependencies: ```shell composer update ``` Next, you should update the Vagrant box using the `vagrant box update` command: ```shell vagrant box update ``` After updating the Vagrant box, you should run the `bash init.sh` command from the Homestead directory in order to update Homestead's additional configuration files. You will be asked whether you wish to overwrite your existing `Homestead.yaml`, `after.sh`, and `aliases` files: ```shell # macOS / Linux... bash init.sh # Windows... init.bat ``` Finally, you will need to regenerate your Homestead virtual machine to utilize the latest Vagrant installation: ```shell vagrant up ``` <a name="daily-usage"></a>
243208
## Daily Usage <a name="connecting-via-ssh"></a> ### Connecting via SSH You can SSH into your virtual machine by executing the `vagrant ssh` terminal command from your Homestead directory. <a name="adding-additional-sites"></a> ### Adding Additional Sites Once your Homestead environment is provisioned and running, you may want to add additional Nginx sites for your other Laravel projects. You can run as many Laravel projects as you wish on a single Homestead environment. To add an additional site, add the site to your `Homestead.yaml` file. ```yaml sites: - map: homestead.test to: /home/vagrant/project1/public - map: another.test to: /home/vagrant/project2/public ``` > [!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 Once the site has been added, execute the `vagrant reload --provision` terminal command from your Homestead directory. <a name="site-types"></a> #### Site Types Homestead supports several "types" of sites which allow you to easily run projects that are not based on Laravel. For example, we may easily add a Statamic application to Homestead using the `statamic` site type: ```yaml sites: - map: statamic.test to: /home/vagrant/my-symfony-project/web type: "statamic" ``` The available site types are: `apache`, `apache-proxy`, `apigility`, `expressive`, `laravel` (the default), `proxy` (for nginx), `silverstripe`, `statamic`, `symfony2`, `symfony4`, and `zf`. <a name="site-parameters"></a> #### Site Parameters You may add additional Nginx `fastcgi_param` values to your site via the `params` site directive: ```yaml sites: - map: homestead.test to: /home/vagrant/project1/public params: - key: FOO value: BAR ``` <a name="environment-variables"></a> ### Environment Variables You can define global environment variables by adding them to your `Homestead.yaml` file: ```yaml variables: - key: APP_ENV value: local - key: FOO value: bar ``` After updating the `Homestead.yaml` file, be sure to re-provision the machine by executing the `vagrant reload --provision` command. This will update the PHP-FPM configuration for all of the installed PHP versions and also update the environment for the `vagrant` user. <a name="ports"></a> ### Ports By default, the following ports are forwarded to your Homestead environment: <div class="content-list" markdown="1"> - **HTTP:** 8000 &rarr; Forwards To 80 - **HTTPS:** 44300 &rarr; Forwards To 443 </div> <a name="forwarding-additional-ports"></a> #### Forwarding Additional Ports If you wish, you may forward additional ports to the Vagrant box by defining a `ports` configuration entry within your `Homestead.yaml` file. After updating the `Homestead.yaml` file, be sure to re-provision the machine by executing the `vagrant reload --provision` command: ```yaml ports: - send: 50000 to: 5000 - send: 7777 to: 777 protocol: udp ``` Below is a list of additional Homestead service ports that you may wish to map from your host machine to your Vagrant box: <div class="content-list" markdown="1"> - **SSH:** 2222 &rarr; To 22 - **ngrok UI:** 4040 &rarr; To 4040 - **MySQL:** 33060 &rarr; To 3306 - **PostgreSQL:** 54320 &rarr; To 5432 - **MongoDB:** 27017 &rarr; To 27017 - **Mailpit:** 8025 &rarr; To 8025 - **Minio:** 9600 &rarr; To 9600 </div> <a name="php-versions"></a> ### PHP Versions 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: - map: homestead.test to: /home/vagrant/project1/public php: "7.1" ``` [Within your Homestead virtual machine](#connecting-via-ssh), you may use any of the supported PHP versions via the CLI: ```shell php5.6 artisan list php7.0 artisan list php7.1 artisan list php7.2 artisan list 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: ```shell php56 php70 php71 php72 php73 php74 php80 php81 php82 php83 ``` <a name="connecting-to-databases"></a> ### 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`. > [!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. <a name="database-backups"></a> ### 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 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. <a name="configuring-cron-schedules"></a> ### 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 `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: ```yaml sites: - map: homestead.test to: /home/vagrant/project1/public schedule: true ``` The cron job for the site will be defined in the `/etc/cron.d` directory of the Homestead virtual machine. <a name="configuring-mailpit"></a> ### Configuring Mailpit [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 MAIL_HOST=localhost MAIL_PORT=1025 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null ``` Once Mailpit has been configured, you may access the Mailpit dashboard at `http://localhost:8025`. <a name="configuring-minio"></a>
243212
# Eloquent: Mutators & Casting - [Introduction](#introduction) - [Accessors and Mutators](#accessors-and-mutators) - [Defining an Accessor](#defining-an-accessor) - [Defining a Mutator](#defining-a-mutator) - [Attribute Casting](#attribute-casting) - [Array and JSON Casting](#array-and-json-casting) - [Date Casting](#date-casting) - [Enum Casting](#enum-casting) - [Encrypted Casting](#encrypted-casting) - [Query Time Casting](#query-time-casting) - [Custom Casts](#custom-casts) - [Value Object Casting](#value-object-casting) - [Array / JSON Serialization](#array-json-serialization) - [Inbound Casting](#inbound-casting) - [Cast Parameters](#cast-parameters) - [Castables](#castables) <a name="introduction"></a> ## Introduction 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. <a name="accessors-and-mutators"></a> ## Accessors and Mutators <a name="defining-an-accessor"></a> ### 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`: <?php namespace App\Models; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Get the user's first name. */ protected function firstName(): Attribute { 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; $user = User::find(1); $firstName = $user->first_name; > [!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). <a name="building-value-objects-from-multiple-attributes"></a> #### Building Value Objects From Multiple Attributes Sometimes your accessor may need to transform multiple model attributes into a single "value object". To do so, your `get` closure may accept a second argument of `$attributes`, which will be automatically supplied to the closure and will contain an array of all of the model's current attributes: ```php use App\Support\Address; use Illuminate\Database\Eloquent\Casts\Attribute; /** * Interact with the user's address. */ protected function address(): Attribute { return Attribute::make( get: fn (mixed $value, array $attributes) => new Address( $attributes['address_line_one'], $attributes['address_line_two'], ), ); } ``` <a name="accessor-caching"></a> #### 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: use App\Models\User; $user = User::find(1); $user->address->lineOne = 'Updated Address Line 1 Value'; $user->address->lineTwo = 'Updated Address Line 2 Value'; $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. */ protected function address(): Attribute { return Attribute::make( get: fn (mixed $value, array $attributes) => new Address( $attributes['address_line_one'], $attributes['address_line_two'], ), )->withoutObjectCaching(); } ``` <a name="defining-a-mutator"></a> ### 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: <?php namespace App\Models; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Interact with the user's first name. */ protected function firstName(): Attribute { 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; $user = User::find(1); $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 the model's internal `$attributes` array. <a name="mutating-multiple-attributes"></a> #### Mutating Multiple Attributes Sometimes your mutator may need to set multiple attributes on the underlying model. To do so, you may return an array from the `set` closure. Each key in the array should correspond with an underlying attribute / database column associated with the model: ```php use App\Support\Address; use Illuminate\Database\Eloquent\Casts\Attribute; /** * Interact with the user's address. */ protected function address(): Attribute { return Attribute::make( get: fn (mixed $value, array $attributes) => new Address( $attributes['address_line_one'], $attributes['address_line_two'], ), set: fn (Address $value) => [ 'address_line_one' => $value->lineOne, 'address_line_two' => $value->lineTwo, ], ); } ``` <a name="attribute-casting"></a>
243213
## 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` method provides a convenient way of converting attributes to common data types. 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: <div class="content-list" markdown="1"> - `array` - `AsStringable::class` - `boolean` - `collection` - `date` - `datetime` - `immutable_date` - `immutable_datetime` - <code>decimal:&lt;precision&gt;</code> - `double` - `encrypted` - `encrypted:array` - `encrypted:collection` - `encrypted:object` - `float` - `hashed` - `integer` - `object` - `real` - `string` - `timestamp` </div> 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: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { 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); 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', ]); > [!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. <a name="stringable-casting"></a> #### 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}}/strings#fluent-strings-method-list): <?php namespace App\Models; use Illuminate\Database\Eloquent\Casts\AsStringable; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'directory' => AsStringable::class, ]; } } <a name="array-and-json-casting"></a> ### 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: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { 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; $user = User::find(1); $options = $user->options; $options['key'] = 'value'; $user->options = $options; $user->save(); 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); $user->update(['options->key' => 'value']); <a name="array-object-and-collection-casting"></a> #### 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); $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; /** * Get the attributes that should be cast. * * @return array<string, string> */ 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; /** * Get the attributes that should be cast. * * @return array<string, string> */ 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: use App\Collections\OptionCollection; use Illuminate\Database\Eloquent\Casts\AsCollection; /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'options' => AsCollection::using(OptionCollection::class), ]; } <a name="date-casting"></a>
243214
### 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` 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): /** * Get the attributes that should be cast. * * @return array<string, string> */ 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. */ 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'; <a name="date-casting-and-timezones"></a> #### Date Casting, Serialization, and Timezones 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. 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. <a name="enum-casting"></a> ### Enum Casting 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; /** * Get the attributes that should be cast. * * @return array<string, string> */ 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; $server->save(); } <a name="casting-arrays-of-enums"></a> #### 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: use App\Enums\ServerStatus; use Illuminate\Database\Eloquent\Casts\AsEnumCollection; /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'statuses' => AsEnumCollection::of(ServerStatus::class), ]; } <a name="encrypted-casting"></a> ### Encrypted Casting The `encrypted` cast will encrypt a model's attribute value using Laravel's built-in [encryption](/docs/{{version}}/encryption) features. In addition, the `encrypted:array`, `encrypted:collection`, `encrypted:object`, `AsEncryptedArrayObject`, and `AsEncryptedCollection` casts work like their unencrypted counterparts; however, as you might expect, the underlying value is encrypted when stored in your database. 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. <a name="key-rotation"></a> #### 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. <a name="query-time-casting"></a> ### 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(); 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(); <a name="custom-casts"></a>
243215
## Custom Casts 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: ```shell php artisan make:cast Json ``` All custom cast classes implement the `CastsAttributes` interface. 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: <?php namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Database\Eloquent\Model; class Json implements CastsAttributes { /** * Cast the given value. * * @param array<string, mixed> $attributes * @return array<string, mixed> */ 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<string, mixed> $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: <?php namespace App\Models; use App\Casts\Json; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'options' => Json::class, ]; } } <a name="value-object-casting"></a> ### 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. 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`: <?php namespace App\Casts; use App\ValueObjects\Address as AddressValueObject; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Database\Eloquent\Model; use InvalidArgumentException; class Address implements CastsAttributes { /** * Cast the given value. * * @param array<string, mixed> $attributes */ public function get(Model $model, string $key, mixed $value, array $attributes): AddressValueObject { return new AddressValueObject( $attributes['address_line_one'], $attributes['address_line_two'] ); } /** * Prepare the given value for storage. * * @param array<string, mixed> $attributes * @return array<string, string> */ public function set(Model $model, string $key, mixed $value, array $attributes): array { if (! $value instanceof AddressValueObject) { 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; $user = User::find(1); $user->address->lineOne = 'Updated Address Value'; $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. <a name="value-object-caching"></a> #### Value Object Caching 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. 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: ```php class Address implements CastsAttributes { public bool $withoutObjectCaching = true; // ... } ``` <a name="array-json-serialization"></a> ### Array / JSON Serialization When an Eloquent model is converted to an array or JSON using the `toArray` and `toJson` methods, your custom cast value objects will typically be serialized as well as long as they implement the `Illuminate\Contracts\Support\Arrayable` and `JsonSerializable` interfaces. However, when using value objects provided by third-party libraries, you may not have the ability to add these interfaces to the object. 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 array<string, mixed> $attributes */ public function serialize(Model $model, string $key, mixed $value, array $attributes): string { return (string) $value; } <a name="inbound-casting"></a> ### Inbound Casting 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. Inbound only custom casts should implement the `CastsInboundAttributes` interface, which only requires a `set` method to be defined. The `make:cast` Artisan command may be invoked with the `--inbound` option to generate an inbound only cast class: ```shell php artisan make:cast Hash --inbound ``` A classic example of an inbound only cast is a "hashing" cast. For example, we may define a cast that hashes inbound values via a given algorithm: <?php namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes; use Illuminate\Database\Eloquent\Model; class Hash implements CastsInboundAttributes { /** * Create a new cast class instance. */ public function __construct( protected string|null $algorithm = null, ) {} /** * Prepare the given value for storage. * * @param array<string, mixed> $attributes */ public function set(Model $model, string $key, mixed $value, array $attributes): string { return is_null($this->algorithm) ? bcrypt($value) : hash($this->algorithm, $value); } } <a name="cast-parameters"></a> ### 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: /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'secret' => Hash::class.':sha256', ]; } <a name="castables"></a>