YouTubestream· May 27, 2024· 9:53:24
!
Thank you.
I'm going to go ahead and get it.
Thank you.
So, let's go.
Thank you.
So, let's go.
Alright, I think we are about ready. Switch this over.
How's it going everyone? Hopefully everyone can hear me just fine. But for those tuning in, this is a complete read through of the
Laravel documentation and I don't know if I can pull up the Twitter comments. I don't know how that specifically works. First time streaming on Twitter itself. But a little bit of an echo.
Hopefully everything sounds pretty fine. The Echo might just be the room, but so we'll kind of just jump right into it. Yeah, we're going to be reading the Laravel documentation live on stream. If it's completely unbearable Echo, let me know. But the goal was for me to at least have a better relaxation piece to be able to do this
in that sense of not having a microphone like right in front of my face. So hopefully this works a little bit. Yeah, I think everything's going pretty good. We're gonna get started. So basically this isn't sponsored by Laravel at all. This is something that I wanted to do mostly just to have some fun with doing this completely but then also being able to read the documentation
start to finish and just learn a little bit more about the Laravel docs that I might not have heard before or might not have been able to read before I should say too.
Okay, so let's get into it. What's gonna happen, I guess, my milk, perfect. What's gonna do. So what's gonna happen is I'm just going to start reading the documentation. And again, this is just something to be able to say,
hey, this isn't like an official audio book or anything like that. This is just me saying, hey, here's the documentation that I printed out, all 1,472 pages. And I'm going to read it start to finish. I'm not going to read every single phrase, every single syllable, not all of the code blocks and everything like that. But we're just gonna see how far we can get. And the goal is, as long as it doesn't take days, the goal is to be able to read it from start to finish. So hopefully I'll be able to learn something, hopefully you'll be able to learn something,
and we'll kind of get going. I don't know exactly how to check Twitter comments like on the stream. I have like the broadcast window open, but I don't exactly know where the comments are for that. Let's see. One second.
Thank you.
All right. Again, hopefully you're not watching this the whole way through, but the goal is to be able to get through as much as possible, hopefully learn a little bit about the Laravel documentation as we go.
And then, I don't know where the actual comments show up for Twitter, but I posted a post on, so if you're watching on Twitter, I have a post, and if you comment on there, then I will be able to see it better. But for those watching on YouTube, I do see your comments. Looks like everything's going fairly well, and let's get going.
This is Laravel 11.x offline documentation. I found a GitHub repo to print these off. There's preface for why this PDF was created. Table of contents, we're not going to read that all the way straight through because we're going to get to each piece of the table of contents.
Release notes. Versioning scheme. Laravel and its other first-party packages follow semantic versioning. Major framework releases are released every year, while minor and patch releases may be released as often as every week. Minor and patch releases should never contain breaking changes when referencing the Laravel framework or its components from your application or package. You should always use a version constraint such as 11.0 since major releases of Laravel do include breaking changes. However we strive to always ensure you may update to a new major release in one day or
less. Named arguments. Named arguments are not covered by Laravel's backward compatibility guidelines. We may choose to remain function arguments when necessary in order to improve the Laravel code base. Therefore, using named arguments when calling Laravel methods should be done cautiously and with the understanding that the parameter names may change in the future. For all Laravel releases, bug fixes are provided for 18 months and security fixes are provided
for two years. For all additional libraries, including Lumen, only the latest major release receives bug fixes. In addition, please review the database version supported by Laravel. Laravel 11. Laravel 11 continues the improvements made in Laravel 10.x by introducing a streamlined application structure, per second rate limiting, health routing, graceful encryption key rotation, queue testing improvements, resend mail transport, prompt validator integration, new artisan commands, and more.
In addition, Laravel Reverp, first-party scalable WebSocket server, has been introduced to provide robust, real-time capabilities to your applications. PHP 8.2, Laravel 11.x requires a minimum PHP version of 8.2. Streamlined application structure. Laravel's streamlined application structure was developed by Taylor Otwell and Nuno Maduro. Laravel 11 introduces a streamlined application structure for new Laravel applications. without requiring any changes to existing applications,
the new application structure is intended to provide a leaner, more modern experience while retaining many of the concepts that Laravel developers are already familiar with. Below, we will discuss the highlights of Laravel's new application structure, the application bootstrap file, the bootstrap.app.php file has been revitalized as a code-first application configuration file. From this file, you may now customize your application's routing, middleware, service providers, exception handling, and more. This file unifies a variety of high-level application behavior settings that were previously scattered
throughout your application's file structure. Return application configure with routing, with middleware, with exceptions, create. Service providers, instead of the default Laravel application structure containing five service providers, Laravel 11 only includes a single app service provider. The functionality of the previous service providers has been incorporated into the bootstrap app.php. It's handled automatically by the framework or may be placed in your application's app service provider. For example, event discovery is now enabled by default,
largely eliminated the need for manual registration of events and their listeners. However, if you do need to manually register events, you may simply do so in the app service provider. Similarly, route model bindings are authorization gates you may have previously registered in the auth service provider, may also be registered in the app service provider. Optin API and broadcast routing. The api.php and channels.php route files are no longer present by default, as many applications do not require these files.
Instead, they may be created using simple Artisan commands, phpartisan install API, phpartisan install broadcasting. Middleware. Previously, new Laravel applications included nine middleware. These middleware performed a variety of tasks, such as authenticating requests, trimming input strings, and validating CRSRF tokens. In Laravel 11, these middleware have been moved into the framework itself, so that they do not add bulk to your application structure. New methods for customizing the behavior of these middleware have been added to the framework
and may be invoked from your application's bootstrapapp.php file. With middleware, function middleware, middleware validates CSRF tokens, middleware web, etc. Since all middleware can be easily customized via your application's bootstrapapp.php, the need for a separate HTTP kernel class has been eliminated. Scheduling.
Using a new schedule facade, scheduled tasks now can be defined directly in your application's routes console.php file, eliminating the need for a separate console kernel class. So schedule command, emails send daily. Exception handling. Like routing and middleware, exception handling can now be customized from your application's bootstrap app.php file instead of a separate exception handler class, reducing the overall number of files included in a new Laravel application.
For example, with exceptions, exceptions report. Base controller class. The base controller included in new Laravel applications has been simplified. It no longer extends Laravel's internal controller class and the authorization requests and validates requests have been removed, traits have been removed, as they may be included in your application's individual controllers if desired. Abstract class controller. Application defaults. By default, new Laravel applications use SQLite for database storage as well as the database
driver for Laravel session, cache, and queue. This allows you to begin building your application immediately after creating a new Laravel application without being required to install additional software or create additional database migrations. In addition, over time, the database drivers for these Laravel services have become robust enough for production usage in many application contexts. Therefore, they provide a sensible unified choice for both local and production applications. Laravel Reverb. Laravel Reverb was developed by Joe Dixon.
Laravel Reverb brings blazing fast and scalable real-time WebSocket communication directly to your Laravel application and provides seamless integration with Laravel's existing suite of event broadcasting tools such as Laravel Echo. PHP Artisan Reverb Start In addition, Reverb supports horizontal scaling via Redis' publish slash subscribe capabilities, allowing you to distribute your WebSocket traffic across multiple back-end Reverb servers, all supporting a single high-demand application.
For more information on Laravel Reverb, please consult the complete Reverb documentation. Per second rate limiting. Per second rate limiting was contributed by Tim McDonald. Laravel now supports per second rate limiting for all rate limiters, including those for HTTP requests and Q-Jobs. Previously, Laravel's rate limiters were limited to per minute granularity. So, rate limiter for invoices function return limit per second. For more information on rate limiting in Laravel, check out the rate limiting documentation.
Health Routing. Health Routing was contributed by Taylor Otwell. New Laravel 11 applications include a Health Routing Directive, which instructs Laravel to define a simple health check endpoint that may be invoked by third-party application health monitoring services or orchestration systems like Kubernetes. By default, this route is served at slash up with routing web directory commands health slash up. When HTTP requests are made to this
route Laravel 11 will also dispatch a diagnosing health event allowing you to perform additional health checks that are relevant to your application. Graceful encryption key rotation. Graceful encryption key rotation was contributed by Taylor Otwell. Since Laravel encrypts all cookies, including your application's session cookie, every request to a Laravel application relies on encryption. However, because of this, rotating your application's encryption key would log
all users out of your application. In addition, decrypting data that was encrypted by the previous encryption key becomes impossible. Laravel 11 allows you to find your application's previous encryption keys as a comma delimited list via the app previous keys environment variable. When encrypting values, Laravel
will always use the current encryption key, which is within the app key environment variable. When decrypting values, Laravel will first try the current key. If decryption fails using the current key, Laravel will try all previous keys until one of the keys is able to decrypt the value. This approach to graceful decryption allows users to keep using their application uninterrupted, even if your encryption key is rotated. For more information on encryption in Laravel, check out the encryption documentation. Automatic password rehashing was contributed
by Stephen Reese-Garter. Laravel's default password hashing algorithm is bcrypt. The work factor for bcrypt hashes can be adjusted via the config hashing.php configuration file or the bcrypt rounds environment variable. Typically, the bcrypt work factor should be increased over time as CPU slash GPU processing power increases. If you increase the bcrypt work factor for your application, Laravel will now gracefully and automatically rehash user passwords as users authenticate with your application. Prompt Validation.
Prompt validator integration was contributed by Andreas Marco Satori. Laravel Prompts is a PHP package for adding beautiful and user-friendly forms to your command line applications. With browser-like features including placeholder text and validation, Laravel Prompts supports input validation via closures. So name, text, label, validate, string length, etc.
However, this can become cumbersome when dealing with many inputs or complicated validation scenarios. Therefore, in Laravel 11, you may utilize the full power of Laravel's validator when validating prompt inputs. So name, text, name required, min 3, max 255. Cue interaction testing. Cue interaction testing was contributed by Taylor Otwell. Previously, attempting to test that a queue job was released, deleted, or manually failed was cumbersome and required the definition of custom queue fakes and styles.
However, in Laravel 11, you may easily test for these queue interactions using the with fake queue interactions method. So job, job handle, job assert released with fake queue interactions. New artisan commands. Class creation artisan commands were contributed by Taylor Otwell. New artisan commands have been added to allow the quick creation of classes, enums, interfaces, and traits.
phpartisan make class phpartisan make enum phpartisan make interface phpartisan make trait model casts improvements model cast improvements were contributed by nuno maduro laravel 11 supports defining your model's casts using a method instead of a property this allows for streamlined fluent cast definitions especially when using casts with arguments so protected function casts returns options for more information on attribute casting review the
the Eloquent documentation. The once function, the once helper was contributed by Taylor Otwell and Nuno Maduro. The once helper function executes the given callback and caches the result in memory for the duration of the request. Any subsequent calls to the once function with the same callback will return the previously cached result. So function random, return once. For more information on the once helper, check out the helper's documentation. Improved performance when testing with in-memory databases.
Improved in-memory database testing performance was contributed by Anders Jembo. Laravel 11 offers a significant speed boost when using the memory SQLite database during testing. To accomplish this, Laravel 11 now maintains a reference to PHP's PDO object and reuses it across connections, often cutting total test runtime in half. Improved support for MariaDB. Improved support for MariaDB was contributed by Jonas Stoudemeyer and Julius Kickbusch.
Laravel 11 includes improved support for MariaDB. In previous Laravel releases, you could use MariaDB via Laravel's MySQL driver. However, Laravel 11 now includes a dedicated MariaDB driver, which provides better defaults for this database system. For more information on Laravel's database drivers, check out the database documentation. Inspecting databases and improved schema configurations. Operations. Improved schema operations and database inspection was contributed by Hafez Devandari.
Laravel 11 provides additional database schema operation and inspection methods, including the native modifying, renaming, and dropping of columns. Furthermore, advanced spatial types, non-default schema types, and native schema methods for manipulating tables, views, columns, indexes, and foreign keys are provided. So use eliminate tables schema get tables, schema get views, get columns, get indexes, get foreign keys. Upgrade guy. Skipping the terms of table of content.
so upgrade into 11.0 from 10.x. Estimate upgrading 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 to help augment your application upgrades. Updating dependencies, likelihood of impact high, PHP 8.20 required, Laravel now requires PHP 8.20 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. Laravel framework to 11. Nuno Maduro collision to 0.1 or 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, Octane to 2.3 if installed, Passport to 12.0 if installed, Sanctum to 4.0 if installed, SparkStripe to 5.0 if installed, Telescope to 5.0 if installed, InertiaJS, Inertia Laravel to 1.0 if installed. If your application is using Laravel Cashier Stripe, Passport, Sanctum, SparkStripe, or Telescope, you will need to publish their migrations to your application.
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. So PHP Artisan Vendor Publish tag for all of those migrations. In addition, you should review the upgrade guides for each of these packages to ensure you are aware of any additional breaking changes. So Laravel Cashier, Stripe, Passport, Sanctum, Spark, Stripe, and Telescope. If you have manually installed the Laravel installer, you should update the installer via Composer.
So Laravel Installer 5.6, Composer Global Require. Finally, you may remove the Doctrine D-Val Composer Dependency if you have previously added it to your application, as Laravel is no longer dependent on this package. 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 upgrade to Laravel 11 attempt to migrate their application structure,
as Laravel 11 has been carefully tuned to also support the Laravel 10 application structure. Authentication. Password rehashing. 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 rehashed, typically this should not disrupt your application. However, you may disable this behavior by adding the rehash on login option to your application's hashing.php configuration file. Rehash on login. False. The user provider contract.
Likelihood of impact, low. The Illuminate Contracts Auth User Provider contract has received a new rehash password if required method. This method is responsible for rehashing 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 rehash password if required method to your implementation. A reference implementation can be found within the Illuminate Auth Equiloquent User Provider class. So public function, rehash password if required,
Authenticatable user dual force equals false. So 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 authenticatables 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. So public function, getAuthPasswordName,
return a password. The default user model included with Laravel receives this method automatically since the method is included with the IlluminateAuth authenticatable trait, the authentication exemption class, likelihood of impact, very low. The redirect to method of IlluminateAuth authentication exception class now requires an IlluminateHttpRequest instance as its first argument. If you are manually catching this exception and calling the redirect to method, you should update your code accordingly.
if instance of authentication exception, path redirect to. Cache, cache key prefixes likelihood of impact very low. Previously, the cache key prefix was defined for the DynamoDB memcached or redis cache stores, Laravel would append a colon, a semicolon to prefix. In Laravel 11, the cache key prefix does not receive a semicolon suffix. If you would like to maintain the previous prefixing behavior, you can manually add the semicolon, the colon suffix to your cache key prefix.
Collections. The enumerable contract. Likelihood of impact, low. The dump method of the eliminate support enumerable contract has been updated to accept a variadic arguments arc. If you are implementing this interface, you should update your implementation accordingly. Public function dump arcs. Database. SQLite 3.35.0+. Likelihood of impact, I. If your application
utilizing a SQLite database, SQLite 3.35.0 or greater is required. 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 model is defined in a cast relationship, it may conflict with the cast method now present on the base eloquent model class. 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. So schema create users table integer votes. Later, you run a migration
that changes the column to be nullable as well. So table integer votes nullable. Change. In Laravel 10, this migration would retain the unsigned default and common attributes on the column. However, in Laravel 10, excuse me, however, in Laravel 11, the migration must now also include all the attributes that were previously defined on the column. Otherwise, they will be dropped. Schema table, users, table integer, and then you include everything. Unsigned default,
comment, 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. Data and index, big increments, ID primary, change, drop in index, table care, poster code, unique, false, change. If you do not want to update all of your existing change migrations in your application to retain the column's existing attributes, you may simply squash your migrations. PHP artisan, schema,
Once your migrations have been squashed, Laravel will migrate the database using your application's schema file before running any pending migrations. 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 and float migration column types 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, so total double amount. The float column table 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 four byte single precision column or as an eight 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 databases documentation. So table float amount precision.
The unsigned decimal, unsigned double, and unsigned float 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 change the chain of the unsigned method onto the column's definitions. So table decimal unsigned, table double unsigned, table float unsigned. Dedicated MariahDB driver. Likelihood of impact, very low.
Instead of always utilizing the MySQL driver when connecting to MariahDB databases, Laravel 11 adds a dedicated database driver for MariahDB. If your application connects to a MariahDB database, you may update the connection configuration to the new MariahDB driver to benefit from MoriaDB-specific features in the future. So driver, MoriaDB. Currently, the new MoriaDB driver behaves like the current MySQL driver, with one exception.
The UUID schema builder method creates native UUID columns instead of CAR36 columns. If your existing migrations utilize the UUID schema builder method and you choose to use the new MoriaDB database driver, you should update your migrations and vacations of the UUID method to CAR to avoid breaking changes or unexpected behavior. So schema table, table car. Spatial types. Likelihood of impact, low. Spatial column types of database migrations have been rewritten to be consistent across all databases.
Therefore, you may remove point, line string, polygon, geometry collection, multipoint, multiline string, multipolygon, and multipolygon Z methods from your migrations and use geometry or geography methods instead. So table geography, table geometry. To explicitly restrict the type of the spatial reference system identifier for values stored in the column on MySQL, MyMariadb, and PostgresSQL, you may pass the subtype and SRID method to the method. So, table geometry, dimension, subtype, SRID.
The isGeometry and projection column modifiers of the Postgres grammar have been removed accordingly. Doctrine-deball removal. Likelihood of impact, low. The following list of Doctrine-deball-related classes and methods have been removed. Laravel is no longer dependent on this package, and registering custom doctrine types is no longer necessary for the proper creation and alteration of various column types that previously required custom types. So always use native schema operations if possible, use native schema operations if
possible, using native schema operations, is doctrine available, get doctrine connection, get doctrine schema manager, get doctrine column, register doctrine type, register doctrine type, PDO directory, timestamp type class, change column class, rename column class, grammar, doctrine table diff method. In addition, registering custom doctrine types via dbalt.types in your application's database configuration file is no longer required. If you were previously using doctrine dbalt to inspect your database
and its associated tables, you may use Laravel's new native schema methods, schema get tables, schema get columns, get indexes, get foreign keys, etc. instead. Deprecated schema methods, likelihood of impact, very low. The deprecated doctrine based schema get all tables, get all views, get all types methods have been removed in favor of new Laravel native schema get tables get views and get types methods when using Postgres and SQL Server none of the new schema methods will accept a three-part reference eg database.schema.table therefore you should use connection to declare the database
instead so schema connection database schema builder get column type method likelihood of impact very low schema get column type method now also always returns actual type of the given column, not the Doctrine-Depot equivalent type. Database connection interface, likelihood of impact, very low. The Illuminate database connection 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. So public function scalar. Dates, carbon three, likelihood of impact media. 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 upgraded to Carbon 3, be aware that DFIN methods now return floating point numbers and may
return negative values to indicate time direction, which is a significant change from Carbon 2. Review Carvin's change log for detailed information on how to handle these and other changes. Mail. The mailer contract. Likely of impact. Very low. The Illuminate Contracts mail mailer contract has received a new send now method. If your application or package is manually implementing this contract, you should add the new send now method to your implementation. Public function. Send now. Packages. Publishing service providers to the application. Likely of
impact. Very low. If you have written a Laravel package that manually publishes the service provider to the applications app providers directly and manually modifies the applications app.php configuration file to register the service provider you should update your package to utilize the new service provider add provider to bootstrap file method the add provider to bootstrap file method will automatically add the service provider you have published to the application's bootstrap providers.php file since the provider's array does not exist within the config app.php configuration
file in new laravel 11 applications so service provider add provider to bootstrap file queues The batch repository interface, likelihood of impact, very low, but the IlluminateBusBatch repository interface has received a new rollback method. If you are implementing this interface within your own package or application, you should add this new method to your implementation. Public function, rollback. 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 was set to true or the after commit 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. Rate limiting. Per second rate limiting. Likely of impact, medium. Likely of 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 global limit class constructor now accepts seconds instead of minutes. This class is
not documented and would not typically be used by your application. So new global limit. The limit class constructor now accepts seconds instead of minutes. All documented usage of this case is limited to static constructors such as limit per minute and limit per second. However, if you are instantiating this class manually, you should update your application to provide seconds to the classes and constructors. So new limit key attempts to times 60. The limit class's decay minutes property has been renamed to decay seconds and now contains
seconds instead of minutes. eliminate middleware throttles exceptions. Middleware throttles exceptions with Redis. Class instructors now accept seconds instead of minutes. So new throttle exception, two attempts, exceptions with Redis, attempts. Cashier Stripe. 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 cashierstripe's migrations to your application. phpartisan vendor publish tag cashiermigrations. Please review the complete cashierstripe upgrade guide for additional breaking changes. Sparkstripe, updating Sparkstripe, likelihood of impact high. Laravel 11 no longer supports Laravel Sparkstripe 4.x. Therefore, you should update Laravel's
application, Sparkstripe's dependency to 5.0 in your composer.json file. Sparkstripe 5.0 no longer automatically loads migrations from its own migrations directory. Instead, you should run following command to publish Spark Stripe's migration to your application. Vendor publish Spark Migrations. Laravel 11 supports... oh, next. Please review the complete Spark Stripe upgrade guide for additional breaking changes. Passport, updating Passport, likelihood of impact high.
Laravel 11 no longer supports Laravel Passport 11.x, therefore you should update your Laravel's 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 applications. Artisan Vendor Publish, Passport Migrations. In addition, the Passport Grant type is disabled by default. You may enable it by invoking the Enable Password Grant method and the Boot method of your application's app service provider.
Passport Enable Password Grant. Sanctum. Updating Sanctum likelihood of impact, high. Laravel 11 no longer supports Laravel Sanctum 3.x, therefore you should update your application's Laravel's 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. php artisan vendor publish, tag sanctum migrations. Then in your application sanctum.php configuration file,
you should update the references to the authenticate session, encrypt cookies, and validate csrf token middleware to the following. So change them to authenticate session class, encrypt cookies class and validate CSRF token class. Telescope. Updating Telescope. Likelihood of impact high. Laravel 11 no longer supports Laravel Telescope 4.x, therefore you should update your Laravel application structure to 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. php artisan vendor publish tag telescope migrations spot see once package like that of impact medium laravel 11 now provides its own once function to ensure that a given closure is only executed once therefore if your application has a dependency on the spot see once package you should remove it from your applications composer.json file to avoid conflicts miscellaneous we also encourage you to
view the changes in the laravel laravel github repository while many of these changes are not required you may wish to keep these files in sync with your application some of these changes will will be covered in the Upgrade Guide, but others, such as changes to configuration files or comments, will not be. You can easily view the changes with the GitHub Comparison Tool and choose which updates are important to you. So Contribution Guide. Table of Contents. Bug Reports. To encourage active collaboration,
Laravel strongly encourages pull requests, not just bug reports. Pull requests will only be reviewed when marked as ready for review, not in the draft state, and all tests for new features are passing. Lingering non-active pull requests left in the draft state will be closed after a few days. However, if you file a bug report, your issue should contain a title and clear description of the issue. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a bug report is to make it easy for yourself and others to replicate the bug and develop a fix. Remember, bug reports are created
in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the bug report will automatically see any activity or that others will jump to fix it. Creating a bug report serves to help yourself and others start on the path of fixing the problem. If you want to chip in, you can help out by fixing any bugs listed in our issue trackers. You must be authenticated with GitHub to view all of Laravel's issues. If you notice improper doc block, PHP stand, or IDE warnings while using Laravel, do not create a GitHub issue. Instead,
please submit a pull request to fix the problem. The Laravel source code is managed on GitHub and there are repositories for each of the Laravel projects. And it lists all of Laravel projects here. Support questions. Laravel's GitHub issue trackers are not intended to provide Laravel help or support. Instead, use one of the following channels. Discussions, Laravel Cast Forums, Laravel IO Forums, Stack Overflow, Discord, Lara Chat IRC. Core development discussion. You may propose new features or improvements of existing Laravel behavior in the Laravel Framework
Repository's GitHub discussion board. If you propose a new feature, please be willing to implement at least some of the code that will be needed to complete the feature. Informal discussion regarding bugs, new features, and implementation of existing features takes place in the internals channel of the Laravel Discord server. Taylor Otwell, the maintainer of Laravel, is typically present in the channel on weekdays from 8am to 5pm and sporadically present in the channel at other times. Which branch? All bug fixes should be sent to the latest version that supports bug fixes,
including 10.x. Bug fixes should never be sent to the master branch unless they fix features that exist only in the upcoming release. Mine are features that are fully backward compatible with with the current release may be sent to the latest stable branch, currently 11.x. Major new features or features with breaking changes should always be sent to the master branch, which contains the upcoming release. Compiled assets. If you are submitting a change that will affect a compiled file, such as most of the
files in Resources CSS or Resources JS or Laravel Repository, do not commit the compiled files. Due to their large size, they cannot realistically be reviewed by a maintainer. This could be exploited as a way to inject malicious code into Laravel. In order to defensively prevent this, all compiled files will be generated and committed by Laravel maintainers. Security Vulnerabilities. If you discover security vulnerability within Laravel, please send an email to taylorotwell at taylor at laravel dot com. All security vulnerabilities
will be promptly addressed. Coding Style. Laravel follows the PSR-2 coding standard and the PSR-4 auto loading standard. PHP doc. Below is an example of a valid Laravel documentation block. Note that the at param attribute is followed by two spaces, the argument type, two more spaces and finally the variable name. So PHP doc block, param string, at param closure, at throws exception, and then public function
find. When the at param or at return attributes are redundant due to the use of native types, they can be removed. So removing them completely from the PHP doc. However, when the native type is generic, please specify the generic type of the use of at param or at return attributes. So at return array, for example. Style CI. Don't worry. Style CI. Don't worry if your code styling isn't perfect.
Style CI will automatically merge any style fixes into the Laravel repository after pull requests are merged. This allows us to focus on the content of the contribution and not the code style. Code of Conduct. The Laravel Code of Conduct is derived from the Ruby Code of Conduct. Any violations of the Code of Conduct may be reported to Taylor Otwell, taylor at Laravel.com. Participants will be tolerant of opposing views. Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
When interpreting the words and actions of others, participants should always assume good intentions. Behavior that can be reasonably considered harassment will not be tolerated. Chapter 2, Getting Started. Installation. So 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 you can grow with you. We'll help you take your first step 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 for a hands-on tour of the framework
while we walk you through building your first Laravel application. 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 will help you learn the
ropes without becoming overwhelmed. If you're a senior developer, Laravel gives you robust tools for dependency injection, unit testing, queues, real-time events, and more. Laravel is fine-tuned for building professional web applications and ready-to-handle enterprise workloads. 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 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.
Who knows? Maybe you'll even become a Laravel contributor. Creating a Laravel project. Before creating your first Laravel project, make sure that your local machine has PHP and Composer installed. If you are developing it on Mac OS or Windows, PHP and Composer can be installed in minutes via Laravel herd. In addition, we recommend installing Node and NPM. After you have installed PHP and Composer, you may create a new Laravel project via Composer's create-project command. So composer create-project Laravel Laravel example app. Or you may create new Laravel projects by globally installing the Laravel installer
it via Composer. So after you globally require Laravel installer, Laravel new example app. Once the project has been created, start Laravel's local development server using Laravel Artisan's serve command, phpartisan serve. Once you've started the Artisan development server, your application will be accessible in your web browser at localhost 8000. Next, you're ready to start taking your next steps into the Laravel ecosystem. Of course, you may also want to configure a database. Note, if you would like a head start when developing your Laravel application,
consider using one of our starter kits. Laravel's starter kits provide back-end and front-end authentication scaffolding for your new Laravel application. Initial configuration. All 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 app.php file and its
documentation. It contains several options such as time zone and locale that you may wish to change according to your application. 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 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 be committed to your application's source control since each developer slash 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. For more information about the .emv file and environment-based configuration, check out the full configuration documentation. Databases and migrations. Now that you have created your first Laravel application, you probably want to store some data in a database. By default, your applications.emv configuration file specifies that Laravel will be interacting with a SQLite database. During the creation of the project, Laravel created a 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 MostCrest, you can update your .env configuration file to use the appropriate database. For example, if you wish to use MySQL, update your .env configuration's file's db variables like so. So MySQL host port database username and 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 using php artisan migrate.
If you are developing on Mac OS and need to install MySQL, Postgres, SQL, or Redis locally, consider using DB Engine. Directory Configuration. Laravel should always be served on 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. Docker Installation Using Sale. We want it to be as easy as possible to get started with Laravel, regardless of your preferred operating system.
there are a variety of options for developing and running a Laravel project on your local machine. While you may wish to explore these options at a later time, Laravel provides SAIL, a built-in solution for running your Laravel project using Docker. Docker is a tool for running applications and services in small, lightweight containers which do not interfere with your local machine's installed software or configuration. This means you don't have to worry about configuring or setting up complicated development tools such as web servers and databases on your local machine. To get started, you only need to install Docker Desktop.
Laravel SAIL is a lightweight command line interface for interacting with Laravel's default Docker configuration. SAIL provides a great starting point for building a Laravel application using PHP, MySQL, and Redis without requiring prior Docker experience. Already a Docker expert? Don't worry. Everything about SAIL can be customized using the docker-composed .yaml file included with Laravel. SAIL on macOS. If you're developing on a Mac,
and Docker Desktop is already installed, you can use a simple command in your terminal to create a new Laravel project. For example, to create a new Laravel application in a directory named ExampleApp, you may run the following command in your terminal. That's curl-s, Laravel.buildExampleApp, bash. Of course, you can change ExampleApp in this URL to anything you like. Just make sure the directory name only contains alphanumeric characters, dashes, and underscores. The Laravel applications directory will be created within a directory you execute the command from.
Sale installation may take several minutes, while Sale's application containers are built on your local machine. After the project has been created, you can navigate to the application directory and start Laravel Sale. Laravel Sale provides a simple command line interface for interacting with Laravel's default Docker configuration, CD Example App, Vendor Bin Sale Up. Once the application's Docker containers have started, you should run your application's database migrations, so Sale Artisan Migrate.
Ideally, you can access the application in your web browser at localhost. To continue learning more about SAIL, review its complete documentation. SAIL on Windows. Before you create a new Laravel project application on your Windows machine, make sure to install Docker Desktop. Next, you should ensure that Windows Subsystem for Linux 2, WSL 2, is installed and enabled. WSL allows you to run Linux binary executables natively on Windows 10.
on how to install and enable WSL2 can be found within Microsoft's developer environment configuration. After installing and enabling WSL2, you should ensure the Docker Desktop is configured to use the WSL2 backend. Next you are ready to create your first Laravel project. Launch Windows Terminal and begin a new terminal session for your WSL2 Linux operating system. Next you can use a simple terminal command to create a new Laravel project. For example, to create a new Laravel application in a directory named ExampleApp, you may run
the following command in your terminal. That's curl laravel.build example app. Of course you can change example dash app in this URL to anything you like. Just make sure the application name only contains alphanumeric characters dashes and underscores. The Laravel applications directory will be created within the directory you execute the command from. Self sale installation may take several minutes while sales application containers are built on your local machine. After the project has been created you can navigate to the application
directory and start Laravel sale. Laravel sale provides a simple command line interface for interacting with Laravel's default Docker configuration. See the example app bin sale up. Once the application Docker containers have started, you should run your application's database migration. So sale artisan migrate. Finally, you can access the application in your web browser and local hosts. Developing within WSL2. Of course, you will need to be able to modify the Laravel application
files that were created within your WSL2 installation. To accomplish this, we recommend using Microsoft's Visual Studio Code Editor and their first-party extension for remote development. Once these tools are installed, you may open any Laravel project by executing the code.command from your application's root directory using your Windows Terminal. Sale on Linux. If you're developing on Linux and Docker Compose is already installed, you can use a simple terminal command to create a new Laravel project. First, if you're using Docker Desktop for Linux, you should execute
the following command. If you are not using Docker Desktop for Linux, you may skip this step, so Docker context use default. Then, to create a new Laravel application in a directory named example-app, you may run the following command in your terminal, curl-s laravel.build.example-app. Bash. Of course, you can change example-app in this URL to anything you like, just make sure the application name only contains alphanumeric characters, dashes, and underscores. The Laravel's application directory will be created within the directory you execute the command from.
sale installation may take several minutes while sales application containers are built on your local machine after the projects have been created you can navigate to the application directory and start Laravel sale Laravel sale provides a simple command-line interface for interacting with Laravel's default docker configuration see the example app sale up once the application's docker containers have started you should run your applications database migrations that's sale artisan migrate finally you can access the application in your web browser at localhost
To continue learning more about Laravel's sale, review its complete documentation. So choosing your sales services. When creating a Laravel application via sale, you may use the with query string variable to choose which services should be configured in your new application's Docker Compose YAML file. Available services include MySQL, PostgreSQL, MariaDB, Redis, Memcached, Melisearch, TypeSense, Minio, Selenium, and MailPit. If you do not specify which services you would like configured, a default stack of MySQL,
Melasearch, MailPit, and Selenium will be configured. You may instruct SAIL to install a default dev container by adding the dev container parameter to the URL. So that's curl-s and then example-app dev container. IDEA Support. IDE Support. You are free to use any code editor you wish when developing Laravel applications. However, PHP Storm offers extensive support for Laravel and its ecosystem, including Laravel Pint. In addition, the community-maintained Laravel IDEA PHP Storm plugin offers a variety of
helpful IDE augmentations, including code generation, eloquent syntax completion, validation rule completion, and more. Next steps. Now that you have created your Laravel project, you may be wondering what to learn next. First, we strongly recommend becoming familiar with how Laravel works by reading the following documentation. Request lifecycle, configuration, direct structure, front end, service container, facades. How you want to use Laravel will also dictate the next steps on your journey. There are a variety of ways to use Laravel and we'll explore two primary use cases for
framework below. New to Laravel? Check out Laravel Bootcamp for a hands-on tour of the framework while we walk you through building your first Laravel application. Laravel the full stack framework. Laravel may serve as a full stack framework. By full stack framework, we mean that you are going to use Laravel to route requests to your application and render your front end via blade tempets or single page application hybrid technology like inertia. This is the most common way to use the Laravel framework and in our opinion the most productive way to use Laravel. If this is how you plan to use Laravel, you may want to check out our documentation
on front-end development, routing, views, or the eloquent ORM. In addition, you might be interested in learning about community packages like Livewire and Inertia. These packages allow you to use Laravel as a full-stack framework while enjoying many of the UI benefits provided by single-page JavaScript applications. If you are using Laravel as a full-stack framework, we also strongly encourage you to learn how to compile your application CSS and JavaScript using Vite. If you want to get a head start building your application, check out one of our
official application starter kits. Laravel the API backend. Laravel may also serve as an API backend to your JavaScript single page app configuration or mobile application. For example, you might use Laravel as an API backend for your Next.js application. In this context, you may use Laravel to provide authentication and data storage retrieval for your application, while also taking advantage of Laravel's powerful services such as queues, emails, notifications, and more. If this is how you plan to use Laravel, you may want to check out our
documentation on routing, Laravel Sanctum, and the Eloquent ORM. Configuration. Introduction. All the configuration files for the Laravel framework are stored in the config directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you. These configuration files allow you to configure things like your database connection information, your mail server information, as well as various other core configuration values, such as your application time zone and
encryption key. The about command. Lairdell can display an overview of your application's configuration, drivers, and environment via the about artisan command. So php artisan about. If you're only interested in a particular section of the application overview output, you may filter for that section using the dash dash only option. So dash dash only dash environment. Or to explore specific configuration files, values, and detail, you may use the config colon show artisan command. So colon show database. 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 .env PHP library. In a fresh library, 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 within 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.
Any variable in your .env file can be overwritten by external environment variables such as server level or system level environment variables. Environment file security. Your .env file should not be committed to your application's source control since each developer server using your application should 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. Encrypted environment files can be placed in source control safely. So additional environment files. Before loading your application's environment variables, Laravel determines if an app.env underscore environment variable has been externally provided or if the dash dash ENV CLI argument has been specified. If so, Laravel will attempt to load a .env.app file if it does not exist, the default .env
file will be loaded. Environment variable types. All variables in your .env files are typically parsed as strings. So some reserved values have been created to allow you to return a wider range of types from the emv function. So emv value true, false list here for the .env versus the emv underscore value. 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. So
So app underscore name equals my application in double quotes. Retrieving environment configuration. All the variables listed in the .env file will be loaded into the dollar sign underscore env php super global with 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. So debug is env parentheses.
The second value passed to the env function is the default value. So first value is appdebug, second one is false. This value will be termed if no environment variable exists for the given key. Determining the current environment. So the current application environment is determined via the app underscore env variable from your .env file. You may access this value via the environment method on the app facade, so illuminate support
facade app dollar sign environment equals app colon colon environment you may also pass arguments to the environment method to determine if the environment matches is a given value the method will return true if the environment matches any of the given valuables so if app environment local if that environment local or staging encrypting environment files unencrypted environment files should never be stored in source control however lariable allows you to encrypt your environment
files so that you may safely be added to your source control with the rest of your application. Encryption. To encrypt an environment file you may use the env colon encrypt command. So, php artisan env colon encrypt. Running the environment env colon encrypt command will encrypt your .env file and place the encrypted contents in a .env.encrypted file. The decryption key is presented in the output of the command and should be stored in a secure password manager. If If you would like to provide your own encryption key,
you may use the dash dash key option when invoking the command. So dash dash key equals your key. 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-256CBC cipher, which requires a 32 character key. You are free to use any cipher supported by Laravel's encryptor by passing the dash dash 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
should be encrypted by providing the environment name via the dash dash env options. Dash dash env equals staging. Decryption. To decrypt an environment file, you may use the env colon decrypt command. This command requires a decryption key which Laravel will retrieve from the Laravel underscore env underscore encryption underscore key environment variable. So artisan env colon decrypt. Or the key may be provided directly to the command via the dash dash key.
So dash dash key equals your key. When the env decrypt command is invoked, Laravel would decrypt the contents of the .env.encrypted file and place the decrypted context in the .env file. The dash dash cipher option would be provided to the env decrypt command in order to use a custom encryption cipher, that's dash dash key, and then dash dash cipher. If your application has multiple environment variables, 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 dash dash env options, dash dash env equals staging. In order to overwrite an existing environment file, you may provide the dash dash force option to the env decrypt command, so env decrypt dash dash force. Accessing configuration values. You may easily access your configuration values using the config facade or global config lowercase 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. So config colon colon gets or config function. Set configuration values at runtime, you may invoke the config facade set method or pass an array to the config function. So config set or config as an array for app.timezone. 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. So config colon colon string integer float boolean array. Configuration cache. 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 the configuration options for your application into a single file which can be quickly loaded by
by the framework. You should typically run the phpartisan config cache command as part of your production and 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 applications.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
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. The config clear command may be used to purge the cached configuration, so 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 n function from within your configuration files. Once Once the configuration has been cached, the .env file will not be loaded, therefore the
.env function will only return external system-level environment variables. Configuration publishing. Most of Laravel's configuration files are already published in your application's config directory. However, certain configuration files like cores.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. So PHP Artisan config publish or dash dash all. Debug mode. The debug option in your config app.php configuration file determines how much information about an error is actually displayed to the user. By default this option is set to respect the value of the app debug environment variable which is stored in your .env file. For local development, you should always 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 applications
on users. Maintenance mode. When your application is in maintenance mode, a custom view will be displayed for all your 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 HTTP exception instance will be thrown with a status code of 503. To enable maintenance mode, execute the down Artisan commands, so phpartisan down. If you
If you would like the refresh HTTP header to be sent with all maintenance mode and 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, so dash dash refresh equals 15. You may also provide a retry option to the down command, which will be set as the retry after HTTP headers value, although browsers generally ignore this header, so dash dash retry equals 60. 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. So dash dash secret equals your secret. 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. If you would like Laravel to generate the secret token for you, you may use the with dash secret option. This secret will be displayed to you once the application is in maintenance mode. When accessing this hidden route, you will then be directed to the slash route of the
application. Once the cookie has been issued to your browser, you will be able to browse the application normally as it was not in maintenance mode. Note, your maintenance mode seeker should typically consist of alpha numeric characters and optionally dashes. You should avoid using characters that have special meaning in URLs such as question mark or ampersand. 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 app.php file of your application to cache, then select a cache store that is accessible by all of your servers. This ensures the maintenance mode status is consistently maintained across
every server, so maintenance, driver cache, store, database. 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 within 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 template in the 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 dependency have loaded. You may pre-render a template of your choice using the down commands render option. phpartisan down dash dash render equals errors. Redirect and maintenance mode requests. While in maintenance mode, Laravel will display the maintenance mode view for all of your 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 slash
URL. So dash dash redirect equals your parameter. Disabling maintenance mode. To disable maintenance mode, you may use the up command, php artisan up. You may customize the default maintenance mode template by defining your own template at 503.blade.php. Maintenance mode and queues. While your application is in maintenance mode, no queue jobs will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode. Alternatives to maintenance mode. Since maintenance mode requires your application to have several seconds
of downtime, consider alternatives like Laravel Vapor and Envoyer to accomplish zero downtime deployment with Laravel. Okay, directory structure. Table of contents for the directory structure. Introduction. The default Laravel application structure is intended to provide a great starting point for both large and small applications, but you are free to organize your application however you like. Laravel imposes almost no restrictions on where any given class is located, as long as
composer can auto-load the class. Note, new to Laravel, check out the Laravel Bootcamp for a hands-on tour of the framework while we walk you through building your first Laravel application. The root directory. The app directory. App directory contains the core code of your application. We'll explore this directory in more detail soon. However, almost all the classes in your application will be in this directory. Bootstrap directory contains the app.php file, which bootstraps the framework. This directory also houses a cache directory, which contains framework-generated files for performance optimization, such as the route and services
caching files. Config directory, as the name implies, contains all of your application's configuration files. It's a great idea to read through all these files and familiarize yourself with all the options available to you. Database directory contains your database migrations, model factories, and seeds. If you wish, you may also use this directory to hold a SQLite database. Public directory contains the index.php file, which is the entry point for all requests entering your application and configures auto-loading. This directory also houses your assets such
as images, JavaScript, and CSS. Resources directory contains your views as well as your raw, uncompiled assets, CSS, or JavaScript. Routes directory contains all of the route definitions for your application. By default, two route files are included with Laravel, web.php, and console.php. The web.php file contains routes that Laravel places in the web middleware group, which provides session state, CSRF protection, and cookie encryption. If your application does not offer a stateless
RESTful API, then all of your routes will most likely be defined in the web.php file. The console.php file is where you may define all of your closure-based console commands. Each closure is bound to a command instance, allowing a simple approach to interacting with each command's I.O. methods. Even though this file does not define HTTP routes, it defines console-based entry points routes within your application. You may also schedule tasks in their console.php file. Optionally, you may install additional route files for API routes,
api.php and broadcasting channels, channels.php via the install API, install broadcasting, artisan commands. The api.php file contains routes that are intended to be stateless, so requests entering the application through these routes are intended to be authenticated via tokens and will not have access to session state. The channels.php file is where you may register all the event broadcasting channels that your application supports. The storage directory
contains your logs, compiled blade, templates, file based sessions, file cache, and other files generated by the framework. This directory is segregated into app, framework, and logs directories. The app directory may be used to store any files generated by your application. The framework directory is used to store framework generated files and caches. Finally, the logs directory contains your application's log files. The storage app public directory may be used to store user generated files, such as profile avatars, that should be publicly accessible. You should
create a symbolic link at public storage, which points to this directory. You may create this link using phpartisan storage link artisan command. The test directory contains your automated tests. Example, PEST or PHP unit tests and feature tests are provided out of the box. Each test class should be suffocated with the word test. You may run your tests using the bin pest or bin php unit commands, or Or if you would like more detailed and beautiful representation for your test results, you
may run your tests using the phpartisan testartisan command. The vendor directory contains your composer dependencies. The app directory. The majority of your application is hosted in the app directory. By default, this directory is namespaced under app and is autoloaded by composer using the PSR4 autoloading standard. By default, the app directory contains the HTTP, models, and providers directories. However, over time, a variety of other directories will be generated inside the app directory as you use the makeartisan commands to generate classes.
For example, the app console directory will not exist until you execute the makecommandartisan command to generate a command class. Both the console and HTTP directories are further explained in their respective sections below. But think of the console and HTTP directories as providing an API into the core of your application. The HTTP protocol and CLI are both mechanisms to interact with your application. but do not actually contain application logic. In other words, there are two ways of issuing
commands to your application. The console directory contains all of your Artisan commands, while the HTTP directory contains your controllers, middleware, and requests. Note, many of the classes in the app directory can be generated by Artisan via commands. To review the available commands, run the phpArtisanListMake command in your terminal. The broadcasts in directory contains all of the broadcast channel classes for your application. These classes are generated using the make channel command. This directory does not exist by default, but will be created for you when you create your first channel. To learn more about channels,
check out the documentation on Event Broadcasting. The console directory contains all of the custom artisan commands for your application. These commands may be generated using the make command command. The directory does not exist by default, but will be created to you by the event generate and make event artisan commands. The events directory houses event classes. Events may be used to alert other parts of your application that a given action has occurred, providing a great deal of flexibility and decoupling. The exceptions directory contains all of the custom exceptions for your application.
These exceptions may be generated using the make exception command. The HTTP directory contains your controllers, middleware, and form requests. Almost all of the logic to handle requests entering your application will be placed in this directory. The jobs directory does not exist by default, but will be created for you if you execute the make job artisan command. The jobs directory houses the queueable jobs for your application. Jobs may be queued by your application or run synchronously within the current request lifecycle.
Jobs that run synchronously during the current request are sometimes referred to as commands since they are an implementation of the command pattern. The listeners directory. This directory does not exist by default but will be created for you if you execute the event generate or make listener artisan commands. The listeners directory contains the classes that handle your events. event, listeners receive an event instance and perform logic in response to the event being fired.
For example, a user registered event might be handled by a send welcome email listener. The mail directory does not exist by default but will be created for you if you execute the make mail artisan command. The mail directory contains all of your classes that represent emails sent by your application. Mail objects allow you to encapsulate all of the logic of building an email in a single, simple class that may be sent using the mail send method. The models directory contains all of your eloquent model classes. The Eloquent ORM included with Laravel provides a beautiful, simple active record implementation
for working with your database. Each database table has a corresponding model which is used to interact with that table. Models allow you to query for data in your tables as well as insert new records into the table. The Notifications directory does not exist by default, but will be created for you if you execute the Make Notification Artisan command. The Notifications directory contains all of the transactional notifications that are sent by your application, such as simple notifications about events that happen within your application,
Laravel's notification feature abstracts sending notifications over a variety of drivers such as email, Slack, SMS, or stored in a database. The policies directory does not exist by default but will be created for you if you execute the make policy artisan command. The policies directory contains the authorization policy classes for your application. Policies are used to determine if a user can perform a given action against a resource. The providers directory contains all the service providers for your application. Service providers bootstrap your application by binding services in the service container,
registering events, or performing any other tasks to prepare your application for incoming requests. In a fresh Laravel application, this directory will already contain the app's service provider. You are free to add your own providers to this directory as needed. The rules directory. This directory does not exist by default, but will be created for you if you execute the make rule artisan command. This rules directory contains the custom validation rule object for your application. Rules are used to encapsulate complicated validation logic in a simple object.
For more information, check out the validation documentation. Front End Introduction. Laravel is a backend framework that provides all the features you need to build modern web applications, such as routing, validation, caching, queues, file storage, and more. However, we believe it's important to offer developers a beautiful full-stack experience, including powerful approaches for building your application's front end. There are two primary ways to tackle front-end development when building an application with Laravel and which approach you choose is determined by whether you would like to build your front-end
by leveraging PHP or by using JavaScript frameworks such as Vue and React. We'll discuss both of these options below so that you can make informed decisions regarding the best approach to front-end development for your application. Using PHP. PHP and Blade in the past, most PHP applications rendered HTML to the browser using simple HTML templates interspersed with PHP echo statements. which rendered data that was retrieved from a database during the request.
In Laravel, this approach to rendering HTML can still be achieved using views and Blade. Blade is an extremely lightweight templating language that provides convenient short syntax for displaying data, iterating over data, and more. For example, at for each, hello, and then in double brackets, dollar sign user, arrow name. When building applications in this fashion, form submissions, and other page interactions typically receive an entirely
new HTML document from the server and the entire page is re-rendered by the browser. Even today, many applications may be perfectly suited to having their frontends constructed in this way using simple blade templates. Growing Expectations However, as user expectations regarding web applications have matured, many developers have found the need to build more dynamic frontends with interactions that feel more polished. In light of this, some developers choose to begin building their applications front-end using JavaScript frameworks such as Vue and React.
Others preferring to stick with the back-end language they are comfortable with have developed solutions that allow the construction of modern web application UIs while still primarily utilizing their back-end language of choice. For example, in the Rails ecosystem, this has spurred the creation of libraries such as Turbo, Hotwire, and Stimulus. Within the Laravel ecosystem, the need to create modern dynamic front ends by primarily using PHP has led to the creation of Laravel Livewire in Alpine.js. Livewire.
Laravel Livewire is a framework for building Laravel powered front ends that feel dynamic, modern, and alive, just like front ends built with modern JavaScript frameworks like Vue and React. react. When using Livewire, you will create Livewire components that render a discrete portion of your UI and expose methods and data that can be invoked and interacted with from your application's front end. For example, a simple counter component might look like
the following. You have public count, public function, public render, and the corresponding template for the counter will be written like so. Button wire click, increment, and and then an h1 with the double bracket dollar sign count. As you can see, Livewire enables you to write new HTML attributes such as wire, colon, click that connect your Laravel applications front end and back end. In addition, you can render your component's current state using simple blade expressions.
For many, Livewire has revolutionized front end development with Laravel, allowing them to stay within the comfort of Laravel while constructing modern dynamic web applications. Typically, developers using Livewire will also utilize Alpine.js to sprinkle JavaScript into their front-end, while only where it is needed, such as in order to render a dialog window. If you're new to Laravel, we recommend getting familiar with the basic usage of views and blade. Then consult the official Laravel Livewire documentation to learn how to take your application to the
next level with interactive Livewire components. Starter Kits If you would like to build your front-end using PHP and Livewire, you can leverage our Breeze or Jetstream starter kits to jumpstart your application's development. these starter kits scaffold your applications back-end and front-end authentication flow using Blade and Tailwind so that you can simply start building your next big idea. Using Vue slash React Although it's possible to build modern front-ends 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 a pinnet view-vew-react framework such as Nuxt and Next. However, data hydration authentication remain complicated
and cumbersome problems to solve when pairing a backend framework like Laravel with these front-end 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 productive or enjoyable way to develop applications. Inertia. Thankfully, Laravel offers the best of both worlds. Inertia bridges the gap between your Laravel application and your modern Vue or React front
end, allowing you to build full-fledged modern front ends 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 view slash react without crippling the capabilities of either tool. After installing inertia into your label application, you will write routes and controllers like normal. However, instead of returning a relate template from your controller, you'll return an inertia page. So return inertia render.
An inertia page corresponds to a view or react component, typically stored within the resources.js pages directory of your application. This data given to the page via the inertia render method will be used to hydrate the props of the page component. So in your view template, you have props of the user. As you can see, Inertia allows you to leverage the full power of view or react when building your front end, while providing a lightweight bridge between your Laravel powered backend and your JavaScript
powered front end. 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. And when deploying your application via Laravel Forge, it's a breeze to ensure that that Inertia's server-side rendering process is always running. Starter kits. If you would like to build your front-end using Inertia and Vue slash React, you can leverage our Breeze or Jetstream starter kit to jumpstart your application's development. Both of these starter kits scaffold your application's
front-end and back-end authentication flow using Inertia, Vue slash React, Tailwind, and Vite so that you can start building your next big idea. Bundling assets. Regardless of whether you choose to develop your front-end using Blade and Livewire or Vue slash 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 front-end with Vue or React, you will also need to bundle your components into browser-ready JavaScript assets. By default, Laravel utilizes Vite to bundle your assets.
Vite provides lightning-fast build times and near-instantaneous hot module replacement during local development. In all new Laravel applications, including those using our starter kits, you will find a Vite.config.js file that loads our lightweight 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. The simplest way to start a kit to jumpstart your application by providing front-end and back-end authentication scaffolding.
Note, for more detailed documentation on utilizing Vite with Laravel, please see our dedicated documentation on bundling and compiling your assets. Quick water break. Starter kits. Introduction.
To give you a head start building your new layer of 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. Laravel Breeze is a minimal simple implementation of all of Laravel's authentication features,
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 style with table and CSS. Additionally, Breeze provides scaffolding options based on liveware or inertia with the choice of using Vue or React for the inertia-based scaffolding. Laravel Bootcamp. If you're new to Laravel, feel free to jump into the Laravel Bootcamp.
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. Installation. First, you should create a new Laravel application. If you create your application using the Laravel installer, 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 require laravel breeze dash dash 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 authentication views, routes, controllers, and other resources to your application. Laravel Breeze publishes all of its code to your application so you have full control and visibility over its features and implementation. The Breeze install command will prompt you for your preferred front-end stack and testing framework.
So php artisan-breeze install, artisan-migrate, npm install, npm run dev. Breeze and Blade. The The default Breeze stack is the Blade stack, which utilizes simple blade templates to render your application's front end. The Blade stack may be installed by invoking the Breeze install command with no other additional arguments and selecting the Blade front end stack. After Breeze's scaffolding is installed, you should also compile your application's front end assets. phpartisan, Breeze install, migrate, mbminstall, mbmrundev.
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. To learn more about compiling your applications, CSS and JavaScript, check out Laravel's Vite documentation. Breeze and Livewire. Laravel Breeze also offers Livewire 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 select Livewire Frontend Stack when executing the Breeze Install Artisan command. After Breeze's scaffolding is installed, you should run your database migration. So Breeze Install, Artisan Migrate. Breeze and React View. Laravel Breeze also offers React and View scaffolding via an Inertia frontend implementation. Inertia allows you to build modern single-page React and View
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 compilation. To use an inertia stack, you may select the Vue or React front end stacks when executing the Breeze install artisan command. When selecting the Vue or React front end stack, the Breeze installer will also prompt you to determine if you would like inertia SSR or TypeScript support. After Breeze's scaffolding is installed, you should
also compile your application's front end assets. So that's Breeze install, artisan migrate, install, npm run dev. Next, you may navigate your application slash login or slash register URLs in your web browser. All of Breeze's routes are defined within this routes off.php file. Breeze and Next.js slash API. There are Breeze can also scaffold an authentication API that is ready to authenticate modern JavaScript applications such as those powered by Next, Nuxt, and others to get started to select the API stack as your desired stack when executing the
Breeze install artisan command. php artisan Breeze install. php artisan migrate. During During an installation, Breeze will add a frontend URL environment variable to your applications.env file. This URL should be the URL of your JavaScript application. This will typically be localhost 3000 during local development. In addition, you should ensure that your app URL is set to localhost 8000, which is the default URL used by the serveartisan command. Next JS reference implementation. Finally, you are ready to pair the backend with the frontend of your choice.
A next reference implementation of the Breeze frontend is available on GitHub. This frontend is maintained by Laravel and contains the same user interface as the traditional blade and inertia stacks provided by Breeze. 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 front end technology stacks. For those brand new to Laravel, we recommend learning the ropes with Laravel Breeze before guiding you 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 Synctum and optional team management. Jetstream is designed using Tailwind CSS and offers your choice of live wire or inertia driven development driven front end scaffolding. Complete documentation for installing Laravel Jetstream can be found within the official
Jetstream documentation. Deployment. Introduction. When you're ready to deploy your Laravel development application to production, there are some important things you can do to make sure your application is running as efficiently as possible. And this document will cover some great starting points for making sure your Laravel application is deployed properly. The Laravel framework has a few system requirements. You should ensure each web
server has the following minimum PHP version and extensions. So PHP 8.2, C-type, CURL, DOM, file info, filter, hash, mbstring, open SSL, PCRE, PDO, session, tokenizer, and XML PHP extensions. 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 the 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. Please ensure, like the configuration below, your web server directs all requests to your application's public index.php file. You should You should never attempt to move the index.php file to your project's root, as serving the application from the project rule will expose many sensitive configuration files to the public internet. Franken.php may also be used to serve your Laravel application.
Franken.php is a modern web application server written in Go. To serve a Laravel PHP application using Franken.php, you may simply invoke its php-server command, Franken.php-server. To take advantage of more powerful features supported by FrankenPHP, such as its Laravel Octane integration, HTTP3, modern compression, or the ability to package Laravel applications as standalone binaries, please consult FrankenPHP's Laravel documentation. 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 optimized artisan command that will cache all of these files. This command should typically be invoked as part of your application's deployment process, so phpArtisanOptimized. The OptimizeClear method may be used to remove all the cached files generated by the Optimize command. phpOptimizedClear. In the following documentation, we will discuss each of the granular optimization commands that are executed by the Optimize command. Caching configuration.
When deploying your application to production, you should make sure that you run the config cacheArtisan command during your deployment process. 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 file system when loading your configuration values. If you execute the config cache command during your deployment process, you should be sure that you are only calling the end function from your configuration files. Once the configuration has been cached, the .env file will not be loaded in all calls, so
the .env function or .env variables will return null. Caching events. applications auto-discovered event to listener mappings during your deployment process. This can be accomplished by invoking the event cache artisan command during deployment. PHP artisan event cache. 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. PHP artisan route cache. This command reduces all of your route registrations into a single
method call when a cache file, improving the performance of route registration when registering hundreds of routes. Caching views. When deploying your application to production, you should make sure that you run the view cache artisan command during your deployment process. This command compiles all of your blade views so they are not compiled on demand, improving the performance of each request that returns a view. Debug mode. The debug option in your config app.php configuration file determines how much information about an error is actually deployed, 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 applications.env file. In your production environment, warning, this value should always be false. If the apt-to-be debug variable is set to true in your production, you risk exposing sensitive configuration values to your applications and users. 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 7 or slash 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 slash app file. When HTTP requests are made to this route, Laravel will also dispatch Eliminate Foundation
Events Diagnosing Health event, allowing you to perform additional health checks relevant to your application. Within a listener 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. Easy deployment with Forge slash Vapor. Laravel Forge. If you aren't quite ready to manage your own server configuration or aren't comfortable configuring all the various services needed to run a robust Laravel application, Laravel Forge is a wonderful
alternative. Laravel Forge can create servers on various infrastructure providers such as Digital Ocean, Linode, AWS, and more. In addition, Forge installs and manages all the tools needed to build robust Laravel applications such as Nginx, MySQL, Redis, Memcached, Beanstalk, and more. Want a full guide to deploying with Laravel Forge? Check out the Laravel Bootcamp and the Forge video series available on Laracast. Laravel Vapor. If you would like a totally serverless auto-scaling development platform tuned for Laravel, check out Laravel Vapor. Laravel Vapor is a serverless
deployment platform for Laravel powered by AWS. Launch your Laravel infrastructure on vapor and fall in love with the scalable simplicity of serverless. Laravel vapor is fine-tuned by Laravel's creators to work seamlessly with the framework so you can keep writing your Laravel applications exactly like you're used to. Chapter 3. Architecture Concepts. The request lifecycle. Introduction. When using any tool in the real world, you feel more confident if you understand how that tool works. Application development is no different.
When you understand how your development tools function, you feel more comfortable and confident using them. this document is to give you a good high-level overview of how the Laravel framework works. By getting to know the overall framework better, everything feels less magical, and you will be more confident building your applications. If you don't understand all of the terms right away, don't lose heart. Just try to get a basic grasp of what is going on, and your knowledge will grow as you explore other sections of the documentation. Lifecycle Overview The entry point for all of your requests
to a Laravel application is the publicindex.php file. All requests are directed to this file by your web server, Apache Nginx configuration. The index.php file does not contain much code, rather it is a starting point for loading the rest of the framework. The index.php file loads the composer generated auto-loaded definition and then retrieves an instance of Laravel application from bootstrap app.php. The first action taken by Laravel itself is to create an instance of the application service container. HTTP console kernels.
Next the incoming request is sent to either the HTTP kernel or the console kernel using handle requests or handle command methods of the application instance. Depending on the type of request entering the application, these two kernels serve as the central location through which all requests flow. For now, let's just focus on the HTTP kernel, which is an instance of eliminate foundation HTTP kernel. The HTTP kernel defines an array of bootstrappers that will be run before the request is executed. These bootstrappers configure error handling, configure logging,
detect the application environment, and perform other tasks that you need to be done before the the request is actually handled. Typically, these classes handle internal Laravel configuration that you do not need to worry about. The HTTP kernel is also responsible for passing the request through the application's middleware stack. These middleware handle reading and writing the HTTP session, determining if the application is in maintenance mode, verifying the CSRF token, and more. We'll talk about these soon. The method signature for the HTTP method's handle method is quite simple. It receives
a request and returns a response. Thinking if the kernel is being a big black box that represents your entire application, feed it HTTP requests and it will return HTTP responses. Service Providers. One of the most important kernel bootstrapping applications is loading the service providers for your application. Service providers are responsible for bootstrapping all the framework's various components, such as the database, queue, validation, and routing
components. Laravel will iterate through that list of providers and instantiate each of them. After instantiating the providers, the register method will be called on all of the Then, once all the providers have been registered, the boot method will be called on each provider. This is so service providers may depend on every container binding being registered and available by the time a boot method is executed. Essentially, every major feature offered by Laravel is bootstrapped and configured by a service provider. Since they bootstrap and configure so many features offered by the framework, service
providers are the most important aspect of the entire Laravel bootstrap process. While the framework internally uses dozens of service providers, you also have the option to create your own. You can find a list of the user-defined or third-party service providers that your application is using in the bootstrap.providers.php file. Once the application has been bootstrapped and all service providers have been registered, the request will be handled off to the router for dispatching. The router will dispatch the request to a route or controller as well as run any route-specific middleware.
Middleware provides a convenient mechanism for filtering or examining HTTP requests entering your application. For example, Laravel includes a middleware that verifies that the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. Some middleware are assigned to all routes within the application, like prevent requests during maintenance, while some are only assigned to specific routes or route groups. You can learn more about middleware by reading the complete middleware
documentation. If the request passes through all the matched routes assigned to middleware, the route or controller method will be executed and the response returned by the route or controller method will be sent back through the route's chain of middleware. Finishing up, once the route or controller method returns a response, the response will travel back outward through the route's middleware, giving the application a chance to modify or examine the outgoing response. Finally, once the response travels back through the middleware,
the HTTP kernel's handle method returns the response object to the handle request of the application instance. And this method calls the send method on the return response. The send method sends the response content to the user's web browser. We've now completed our journey through the entire Laravel request lifecycle. Focus on service providers. Service providers are the key to bootstrapping a Laravel application. The application instance is created, the service providers are registered, and the request is handed to the bootstrapped application.
It's really that simple. Having a firm grasp of how a Laravel application is built and bootstrapped via service providers is very valuable. Your application's user-defined service providers are stored in the app provider's directory. By default, the app's service provider is fairly empty. This provider is a great place to add your application's own bootstrapping and service container bindings. For large applications, you may wish to create several service providers, each with more granular bootstrapping for several specific services used by your application.
Service container, introduction. The Laravel service container is a powerful tool from managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this, class dependencies are injected into the class via the constructor or in some cases, setter methods. Let's look at a simple example. So public function construct, you have show string and protected user repository. So in this
example, the user controller needs to retrieve users from a data source. So we will inject a service that is able to retrieve users. In this context, our user repository, most likely uses Eloquent to retrieve user information from the database. However, since this repository is injected, we are able to easily swap it out with another implementation. We are also able to easily mock or create a dummy implementation of the user repository when testing our application. A deep understanding of the Laravel service container
is essential to building powerful large application as well as contributing to the level core itself. Zero configuration resolution. As a class, if a class has no dependencies or only depends on the other concrete classes, not interfaces, the container does not need to be instructed on how to resolve that class. For example, you may place the following code in your routes webpad.php file, route get die. In this example, hitting your application slash route will automatically resolve the service class
and inject it into your router's handler. This is game-changing. It means you can develop your application and take advantage of dependency injection without worrying about bloated configuration files. Thankfully, many of the classes you will be writing when building a Laravel application automatically receive their dependencies via the container, including controllers, event listeners, middleware, and more. Additionally, you may type hint dependencies in the handle method of queued jobs. Once you taste the power of automatic and zero configuration dependency injection, it feels impossible to develop without it.
When to utilize the container. Thanks to zero configuration resolution, you will often type in dependencies on routes, controllers, event listeners, and elsewhere without ever manually interacting with the container within the container. For example, you might type in the HTTP request object in your route definition so that you can easily manage the recurrent request. Even though we never have to implement or interact with the container to write this code, it is managing the injection of these dependencies behind the scenes. So HTTP request, route get function, and then inject request.
In many cases, thanks to automatic dependency injection and facades, you can build Laravel applications without ever manually binding or resolving anything from the container. So when would you ever manually interact with a container? Let's examine two situations. First, if you write a class that implements an interface and you wish to type in that interface on a route or class constructor, you must tell the container how to resolve that interface. Secondly, if you're writing a Laravel package that you plan to share with other Laravel developers, you may need to bind your package's services into the container.
Binding. Binding basics. Simple bindings. Almost all of your service container bindings will be registered within service providers. So most of these examples will demonstrate using the container in that context. Within a service provider, you always have access to the container via the this app property. We can register a binding using the bind method, passing the class or interface name that we wish to register along with the closure that returns an instance of that class. So bind transistor class and then you inject function application. Note that we receive the
the container itself as an argument to the resolver. We can then use the container to resolve some dependencies of the object we are building. As mentioned, you will typically be interacting with the container within service providers. However, if you would like to interact with the container outside of a service provider, you may do so with the app facade. So, app, colon, colon, bind, inject transistor class, function, inject application. You may
You may use the bind if method to register a container binding only if a binding has not already been registered for the given type. So this app, bind if, transistor class function application app. Note, there is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects since it can automatically resolve these objects using reflection. Binding a singleton. The singleton method binds a class or interface using the container that should only be resolved one time.
Once a singleton binding is resolved, the same object instance will be returned on the subsequent calls into the container. So use app services, this app singleton, transistor class function, application app, return new transistor, app make podcast parser. You may use the singleton if method to register a single container binding only if a binding has not already been registered for the given type. So this app singleton if transistor class return new transistor.
Binding scope singletons. The scoped method binds a class or interface into the container that should only be resolved one time within a given Laravel request or jobs lifecycle. While this method is similar to the singleton method, instances registered using the scoped method will be flushed whenever the Laravel application starts a new lifecycle, such as when a Laravel Octane worker processes a new request or when a Laravel queue worker processes a new job. So this app scoped return new transistor. Binding instances.
You may also bind an existing object instance into the container using the instance method. This given instance will always be returned on subsequent calls into the container. So this app instance. Binding instances interfaces to implementations. A very powerful feature of the service container is its ability to bind an interface to a given implementation. For example, let's assume we have an event pusher interface and a Redis event pusher implementation. Once we have coded our Redis Event Pusher implementation of this interface, we can register it with a service container like so.
So this app bind Event Pusher class with Redis Event Pusher class. This statement tells the container that it should inject the Redis Event Pusher when a class needs an implementation of the Event Pusher. Now we can type in the Event Pusher interface in the constructor of a class that is resolved by the container. Remember, controllers, event listeners, middleware, and various other types of classes within Laravel applications are always resolved using the container.
public function construct protected event pusher dollar sign pusher. Contextual binding. Sometimes you may have two classes that utilize the same interface, but you may wish to inject different implementations unto each class. For example, two controllers may depend on different implementations of the file system contract. Laravel provides a simple, fluent interface for defining this behavior. So you can use the needs method for file system class.
Primitives. Sometimes you may have a class that receives some injected classes, but also needs an injected primitive value, such as an integer. You may easily use contextual binding to inject any value your class may need. So this app when user controller needs variable name give value. Sometimes a class may depend on an array of a tagged instance. Using the give tag method, you may easily inject all of the container bindings with that tag. So So this app win, export aggregator, needs and give tag.
If you need to inject a value from one of your application's configuration files, you may use the give config method. So give config method for this app win. Binding typed variatics. Occasionally, you may have a class that receives an array of typed objects using your variatic constructor argument. Using contextual binding, you may resolve this dependency by providing the give method with a closure that returns an array of resolved filter instances.
So needs filter class give with a function to return app make null filter, app make profanity filter, etc. For convenience, you may also just provide an array of class names to be resolved by the container whenever firewall needs filter instances. So this app when firewall class needs filter class give null filter, profanity filter, too long filter, etc. Variatic tag dependency. Sometimes a class may have a variatic dependency that is type hinted as a given class report dot dot dot dollar sign reports.
Using the needs and give tag methods, you may easily inject all the container bindings with that tag for the given dependency. So this app, when needs report class, give tagged reports. Tagging. Occasionally, you may need to resolve all of a certain category of binding. For example, perhaps you are building a report analyzer that receives an array of many different report interface implementations. After registering the report implementations, you can assign them a tag using the tag method.
So this app bind CPU report, this app bind, this app tag CPU report. Once the services have been tagged, you may easily resolve them all via containers tag method. This app bind and return new report analyzer app tagged. Extending bindings. The extend method allows the modification of resolve services. For example, when a service is resolved, you may run additional code to decorate or configure the service. The extend method accepts two arguments.
the service class you're extending, and a closure that should return the modified service. The closure receives the service being resolved and the container instance. The make method. You may use the make method to resolve a class instance from the container. The make method accepts the name of the class or interface you wish to resolve. Use app services transistor, transistor this app make transistor. If some of your class's dependencies are not resolved via the container, you may inject them by passing them as an associative
array into the make with method. For example, when you manually pass the ID constructor argument required by the transistor service. So use app services transistor, transistor equals this app make with transistor class. The bound method may be used to determine if a class or interface has been explicitly bound in the container. So if this app bound with transistor, you, if you are outside of a service provider in a location of your code that does not have access to the app variable, you may use the app facade or the app function
helper to resolve a class instance from the container. If you would like to have the Laravel container instance itself injected into a class that is being resolved by the container, you may type in the illuminate container container class on your class's constructor. That's public function construct, protected container, dollar sign container. Automatic injection. Alternatively and importantly, you may type in the dependency in the constructor of a class that is resolved by the container including controllers, event listeners, middlewares
and more. Additionally, you may type in dependencies and the handle method of queued jobs. In practice, this is how most of your objects should be resolved by the container. For example, you may type in a repository defined by your application in a controller's constructor. The repository will automatically be resolved and injected into the class. So PHP, public functions show string, user, this user's find or fail, protective function,
construct protected user repository users. Method invocation and injection. Sometimes you may wish to invoke a method on an object instance while allowing the container to automatically inject that method's dependencies. For example, given the following class of class user report, you may invoke the generated method via the container like so. So report app call new user report generate. The call method accepts any PHP callable. The container's call method may even be used to invoke
a closure while automatically injecting its dependencies. So result app call function, user repository, dollar sign repository. Container events. The service container fires an event each time it resolves an object. You may listen to this event using the resolving method. So this app resolving, transistor class, this app resolving with a function of mixed object and an application. As you can see, the object being resolved by that will be passed to the callback, allowing you to set any additional properties on the object before it is given
to its consumer. PSR-11, Laravel's service container implements the PSR-11 interface. Therefore, you may type hint the PSR-11 container interface to obtain an instance of the Laravel container. Use app services transistor, route get function, service container, get transistor class. An exception is thrown if the given identifier can't be resolved. The exception will be an instance of PSR container not found exception interface if the identifier was never bound.
If the identifier was bound but was unable to be resolved, an instance of PSR containers, container exception interface will be thrown. Quick water break.
Thank you.
Service providers. Introduction. Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services, are bootstrapped via service providers. But what do we mean by bootstrapped? In general, we mean registering things, including registration service container bindings, event listeners, middleware, and even routes.
Service providers are the central place to configure your application. Laravel uses dozens of service providers internally to bootstrap its core services such as the mailer, queue, cache, and others. Many of these providers are deferred providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed. All user-defined service providers are registered in the bootstrap-providers.php file. In the following documentation, you will learn how to write your own service providers and register them with your Laravel application.
If you would like to learn more about Laravel Handles requests and works internally, check out our documentation on the Laravel request lifecycle. Writing Service Providers All service providers extend the Illumini Support Service Provider class. Most service providers contain a register and a boot method. Within the register method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or other pieces of functionality within the register container.
The Artisan CLI can generate a new provider via the Make Provider command. Laravel will automatically register your new provider in your application's bootstrap providers.php file. phpArtisanMakeProvider, MakeServiceProvider. The Register Method. As mentioned previously, within the Register Method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the Register Method. Otherwise, you may accidentally use a service that is provided by a service provider which
has not loaded yet. Let's take a look at a basic service provider. Within any of your service provider methods, you always have access to the app property which provides access to the service container. The service provider only defines a register method and uses that method to define an implementation of app services risk connection in the service container. If you're not yet familiar with Laravel's service container, check out its documentation. The bindings and singletons property. If your service provider registers
many simple bindings, you may wish to use the bindings and singletons property instead of manually registering each container binding. When the service provider is loaded by the framework, it will automatically check for these properties and register their bindings. The boot method. So what if we need to register a view composer within your service provider? This should be
done within the boot method. This method is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework. Boot method dependency injection. You may type in dependencies for your service provider's boot method. The service container will automatically inject any dependencies you need. All service providers are registered in the bootstrap-providers.php configuration file. This file returns an array that contains the class name of your application's service providers. When you invoke
the Make Provider Artists in Demand, Laravel will automatically add the generated provider to the BootstrapProviders.php file. However, if you have manually created the provider class, you should manually add the provider class to the array. If your provider is only registering binding in the service container, you may choose to defer its registration until one of the registered bindings is actually needed. Deferring the loading of such a provider will improve the performance of your application, since it is not loaded from the file system on every system.
Laravel compiles and stores a list of all of the services were supplied by deferred service providers along with the name of its service provider class. Then, only when you attempt to resolve one of these services does Laravel load the service provider. To defer the loading of a provider, implement the deferral provider interface and define a provider method. The provides method should return the service container bindings registered by the provider. Facades. Introduction. Throughout the Laravel documentation, you will see examples of code that interacts with Laravel's features via facades.
Facades provide a static interface to classes that are available in the application's service container. Laravel ships with many facades, which provide access to almost all of Laravel's features. Laravel's facades serves as static proxies to underlying classes in the service container, providing the benefit of a terse expressive syntax while maintaining more testability and flexibility than traditional static methods. It's perfectly fine if you don't totally understand how facades work. Just go with the flow and continue learning about Laravel.
All of Laravel's facades are defined in the Illuminate Support Facades namespace so we can easily access a facade like so. So facades cache or facades route, then you can do route dot dot or colon colon git return cache colon colon git. Throughout the Laravel documentation, many of the examples will use facades to demonstrate various features of the framework. Helper functions. To complement facade, Laravel offers a variety of global helper functions that make it even easier to interact with common Laravel features.
Some of the common helper functions you may interact with are view, response, URL, config, and more. Each helper function offered by Laravel is documented with their corresponding feature, however a complete list is available within the dedicated helper documentation. For example, instead of using the eliminate support facade's response facade to generate a JSON response, we may simply use the response function. helper functions are globally available, you do not need to import any classes in order
to use them. So instead of returning response colon colon JSON within the facade, you can return response function JSON. When do you utilize facades? Facades have many benefits. They provide a terse memorable syntax that allows you to use Laravel's features without remembering long class names that must be injected or configured manually. Furthermore, of their unique usage of PHP's dynamic methods, they are easy to test.
However, some care must be taken when using facades. The primary danger of facades is class scope creep. Since facades are so easy to use and do not require injection, it can be easy to let your classes continue to grow and use many facades in a single class. Using dependency injection, this potential is mitigated by the visual feedback a large constructor gives you that your class is growing too large. So when using facades, pay special attention to the size of your class so that its scope of responsibility stays narrow. If your class is getting too large, consider splitting it into
multiple smaller classes. Facades versus dependency injection. One of the primary benefits of dependency injection is the ability to swap implementations of the injected class. This is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub. Typically, it would not be possible to mock or stub a truly static class method. However, However, since facades use dynamic methods to proxy method calls to object resolved from the service container, we actually can test facades just as we would test an injected
class instance. For example, given the following route, route get return cache get, using Laravel's facade testing methods, we can write the following tests to verify that the cache get method was called with the argument we expected. So response this get cache and response assert C value. you should receive, response this get, response assert see. Facades versus helper functions. In addition to facades, Lairvelt provides, includes a variety of helper functions which
can perform common tasks like generating views, firing events, dispatching jobs, or sending HTTP responses. Many of these helper functions perform the same function as a corresponding facade. For example, this facade call and helper call are equivalent. So return view profile is the same as facades view make profile. There is absolutely no practical difference between facades and helper functions. When using helper functions, you may still test them exactly as you would the corresponding facade.
For example, given the following route, route colon colon get cache return cache key, the cache helper is going to call the get method on the class underlying the cache facade. So even though we are using the helper function, we can write the following test to verify that the method was called with the argument we expected, which would be response this get cache response a search. C, cache should receive, get. How facades work. In a Laravel application, a facade is a class that provides access to an object from the container.
The machinery that makes this work is the facade class. Laravel's facades and any custom facades you create will extend the base facade class. The facade base class makes use of the call static magic method to defer calls from your facade to an object resolved from the container. In the example below, a call is made to the Laravel cache system. By glancing at this code one might assume that the static get method is being called on the cache class. So public function show user equals cache get returned view profile. Notice that the near the top of the file
we are importing the cache facade. This facade serves as a proxy for access in the underlying implementation of the cache factory interface. Any calls we make using the facade will be past the underlying instance of Laravel's cache service. If we look at the facade's cache class, you'll see that there's no static method get. So, protected static function, getFaçadeAccessor. Instead, the cache facade extends the base facade class and defines the method getFaçadeAccessor.
This method's job is to return the name of a service container binding. When a user references any static method on the cache facade, Laraful resolves the cache binding from the service container and runs the requested method, in this case, get against that object. So, real-time facades. Using real-time facades, you may treat any class in your application as if it was a facade. To illustrate how this can be used, let's first examine some code that does not use real-time facades. For example, let's assume our podcast model has a publish method.
However, in order to publish the podcast, we need to inject a publisher instance. So public function publish, and then inject publisher instance. Injecting a publisher implementation into the method allows us to easily test the method in isolation since we can mock the injected publisher. However, it requires us to always pass a publisher instance each time we call the publish method. Using real-time facades, we can maintain the same testability while not being required to explicitly pass a publisher instance.
To generate a real-time facade, prefix the namespace of the imported class with facades. So importing, you can use app contracts publisher. Instead you'll use facades app contracts publisher. So now the publisher publish this, you have publisher colon colon publish. When the real-time facade is used, the publisher implementation will be resolved out of the service container using the portion of the interface or class name that appears after
the facade's prefix. When testing, we can use the airbills built-in facade testing helpers to mock this method call. So, publisher colon colon should receive publish. So, public function test podcast can be published. Podcasts, podcast factory create. Publisher colon should receive, publish once with podcast. Facade class reference.
Below you will find every facade and its underlying class. This is useful tool for quickly digging into the API documentation for a given facade route. The service container binding key is also included where applicable. So here's a list of the facades. App, artisan, auth, auth instance, blade, broadcast, broadcast instance, bus, cache, cache instance, config, cookie, crypt, date, DB, DB instance, event, exceptions, exceptions, file, gate, hash,
HTTP, and lane, log, mail, notification, password, password instance, pipeline instance, process, queue, queue instance, queue base class, rate limiter, redirect, Redis, Redis instance, request, response, response instance, route, schedule, schema, session, session instance, storage, storage instance, URL, validator, validator instance, view, view instance, and Vite.
Okay, before we hit chapter four, I'm going to take a quick break, get some water, and head to the bathroom.
Thank you.
so
Thank you.
I'm sorry.
I'm going to go ahead and put it in the middle of the room.
I'm going to go to the next video.
All right. So, we are back.
Chapter four, the basics. Basic routing. The most basic Laravel routes except a URI and a closure providing a very simple and expressive method of defining routes and behavior without complicated routing configuration files. One second.
So route, get, return, hello world. All Laravel routes are defining route files which are located in the routes directory. These files are automatically loaded by Laravel using the configuration specified in your application's bootstrap app.php file. The web.php file defines routes that are for your web interface. These routes are assigned the web middleware group which provides features like session state and CSRF protection.
So for most applications, you'll begin by defining routes in your routes web.php file. The routes defined in web.php may be accessed by entering the defined routes URL in your browser. For example, you may access the following route by navigating to example.com slash user in your browser. That's route get user returns user controller class index.
your application also offers a stateless API, you may enable API routing using the install API artisan command, phpartisan install API. The install API command installs Laravel Sanctum, which provides a robust yet simple API token authentication guard, which can be used to authenticate third-party API consumers, SPAs, or mobile applications. In addition, the install API command creates the routes API PHP file. The routes in routesapi.php are stateless
and are assigned to the API middleware group. Additionally, the slash API URL prefix is automatically applied to these routes, so you do not need to manually apply it to every route in the file. You may change the prefix by modifying your application's bootstrap app.php file with routing, API, API prefix. This router allows you to register routes that respond to any HTTP verb. Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the match method,
or you may even register a route that responds to all HTTP verbs using the any method. So when finding multiple routes that share the same URL, routes using the get, post, put, patch, delete, and option methods should be defined before routes using the any, match, and redirect methods. This data, this ensures the incoming request is matched with the correct route. Dependency injection. You may type hint any dependencies required by your route in your route's callback signature.
The declared dependencies will automatically be resolved and injected into the callback by the Laravel service container. For example, you may type in the HTTP request class to have the current HTTP request automatically injected into your route callback. CSRF protection. Remember, any HTML forms pointing to post, put, patch, or delete routes that are defined in the web routes file should include a CSRF token field, otherwise the request will be rejected. You can read more about
CSRF protection and the CSRF documentation. So in a form method, you can have the at CSRF method in blade. Redirect routes. If you are defining a route that redirects to another URI, you may use the route redirect method. This method provides a convenient shortcut so that you do not have to define a full route or controller for performing a simple redirect. So route redirect here to there. By default, route redirect returns a 302 status code. You may customize the status code using the optional third parameter, route redirect here,
there, colon, 301. Or may use the route permanent redirect method to return a 301 status code. View routes. If your route only needs to return a view, you may use the route view method. Like the redirect method, this method provides a simple shortcut so that you do not have to define a full route or controller. The view method accepts the URI as its first argument and a view name as its
second argument. In addition, you may provide an array of data to pass to the view as an optional third argument. Router, view, welcome, router, view, welcome, name, Taylor. When using route parameters and view routes, the following parameters are reserved by Laravel and cannot be used. That's view, data, status, and headers. Listing your routes. The route list artisan command can easily provide an overview of all the routes that are defined by your application. By default, the route
middleware that are assigned to each route will not be displayed in the route list output. However, you can instruct Laravel to display the route middleware and middleware group names by adding the "-v," option to the command. So, route list "-v." You may also instruct Laravel to only show routes that begin with a UVM URI, so "-path equals API." In addition, you may instruct Laravel to hide any routes that are defined by third-party packages by providing the "-accept-vendor," option when executing the route list command.
PHP Artisan Route List – – only – vendor. Routing Customization. By default, your application's routes are configured and loaded by the app.php file. However, sometimes you may want to define an entirely new file to contain a subset of your application's routes. To accomplish this, you may provide a then closure to the with routing method. Within this closure, you may register any additional routes that are necessary for your application.
So with routing, you can provide additional routes there. Or you may even take complete control over route registration by providing a using closure to the with routing method. When this argument is passed, no HTTP routes will be registered by the framework and you are responsible for manually registering all routes. Route parameters. Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user's ID from the URL. you may do so by defining route parameters.
You may define as many route parameters as required by your route. Route parameters are also encased within braces and should consist of alphabetic characters, underscores, or underscores are also acceptable within route parameter names. Route parameters are injected into route callbacks slash controllers based on their order. The names of the route callback controller arguments do not matter. If your route has dependencies, would like the Laravel service container to automatically inject into your routes callback,
you should list your route parameters after your dependencies. So route get user ID function request parameter string ID return user dot dollar sign ID. Optional parameters. Occasionally you may need to specify a route parameter that may not always be present in the URI. You may do so by placing a question mark after the parameter name. So route get slash user slash parentheses name with a question mark at the end of name. Make sure to give the route's
corresponding variable a default value. You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained. So route get username function where name and then a to z a dash z plus. For convenience some commonly used regular expression patterns have helper methods that allow you to quickly add pattern constraints to your routes.
If the incoming request does not match the route pattern constraints, a 404 HTTP response will be returned. If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern method. You should define these patterns in the boot method of your application's App Service Provider class. Public function boot route pattern ID 0 to 9 plus. Once the pattern is defined, it is automatically applied to all routes using that parameter name.
Route get user ID function string ID, for example. Encoded forward slashes. The Laravel routing component allows all characters except slash to be present within route parameter values. You must explicitly allow slash to be part of your placeholder using a where condition regular expression. So where search comma period star. forward slashes are only supported within the last route segment. Named routes. Named routes allow
the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name method onto the route definition. So route get user profile function name profile. You may also specify route names for controller actions. So user profile controller colon colon class comma show name profile. Warning route names should always be unique.
Generating URLs to name routes. Once you have assigned a name to a given route, you may use the route's name when generating URLs or to redirects via Lairwell's route and redirect helper functions. So generating URLs could be $URL equals route profile, generating redirects, redirect route profile. If the named route defines parameters, you may pass the parameters as the second argument to the route function. The given parameters will automatically be inserted into the generated URL in their correct position.
If you pass additional parameters in the array, those key value pairs will automatically be added to the generated URL's query string. So passing an array as a second parameter will add user slash one slash profile question mark photos equals yes. Sometimes you may wish to specify request-wide default values for URL parameters such as the current locale to accomplish this so you may use the URL colon colon defaults method. Inspecting the current route. If you would like to determine if the current
request was routed to a given named route, you may use the named method on a route instance. For example, you may check the current route name from a route middleware. Route groups. Route groups allow you to share attributes such as middlewares across a large number of routes without needing to define those attributes on each individual route. Nested groups attempt to intelligently merge attributes with their parent group. Middleware and where conditions are merged while names and
prefixes are appended. Namespace delimiters and slashes and URI prefixes are automatically added where appropriate. Middleware. To assign middleware to all routes within a group, you may use the middleware method before defining the group. Middlewares are executed in the order they are listed in the array. So route, colon, colon, middleware, and then you can pass them as a parameter, first or second. Controllers. If a group of groups are utilizing the same controller, you may use the controller method to define the common controller for all the routes within the
group. Then when defining the routes, you may only need to provide the controller method that they invoke. So, subdomain routing. Route groups may also be used to handle subdomain routing. Subdomains may be assigned to route parameters just like route URIs, allowing you to capture a portion of the subdomain for usage in your route or controller. The subdomain may be specified by calling the domain method before defining the group. Route prefixes. The prefix method may be used to prefix Prefix each route in the group within a given URI.
For example, you may want to prefix all route URIs within the group with admin. Route prefix admin. Route name prefixes. The name method may be used to prefix each route name in the group with a given string. For example, you may want to prefix the names of all the routes in the group with admin. The given string is prefixed to the route name exactly as it is specified. So we will be sure to provide the trailing period character in the prefix.
route colon colon name admin period route model binding when injecting a model id to a route or controller action you will often query the database to retrieve the model that corresponds to that id laravel route model binding provides a convenient way to automatically inject the model and directly into your routes for example instead of injecting user's id you can inject the entire user model instance that matches the given id implicit binding laravel automatically resolves eloquent
models to find in routes or controllers actions whose type hinted variable names match a route segment name. For example, use app models users route get users user function user which is injected return user email. Since the user variable is type hinted as the app slash models user in the function eloquent model and the variable name matches the user URI segment. Laravel will
automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated. Of course, implicit binding is also possible when using controller methods. Again, note the user URI segment matches the user variable in the controller, which contains an app models user type hint. So route git, which is the definition, has users slash user, where the
controller method definition shows the user as the type hinted function. Soft deleted models. Typically implicit model binding will not retrieve models that have been soft deleted. However, you may instruct the implicit binding to retrieve these models by chaining the with trashed method onto routes definition. So route get at the end, you can append with trashed function. Customizing the key. Sometimes you may wish to resolve eloquent models using a column other than ID. To do so, you may specify the column in the route parameter definition.
So route git slash post slash bracket post colon slug. If you would like model binding to always use a database column other than ID when retrieving a given model class, you may override the git root key name method on the eloquent model. So public function git root key name return slug, for example. When implicitly binding multiple eloquent models in a single route definition, you may wish to scope the second eloquent model such that it must be a child of the previous eloquent
model. For example, consider this route definition that retrieves a blog post by slug for a specific user. Use app slash model slash post route get user post colon slug. When using 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 user model has a relationship named
posts, the plural form of the route parameter name, which can be used to retrieve the post model. Capitalized. If you wish, you may instruct Laravel to scope child bindings, even when a custom key is not provided. To do so, you may invoke the scope bindings method when defining your route. So route colon colon git. At the end of that, you can append scope bindings. or you may instruct an entire group of route definitions to use scope bindings.
So if you have route scope bindings, group function and put your routes in there. Similarly, you may explicitly instruct Laravel to not scope bindings by invoking the without scope bindings method. So we're pending that on to the end of your route. Customizing missing model behavior. Typically, a 404-HTP response will be generated if an implicitly bound model is not found. However, you may customize this behavior by calling the
missing method when defining your route. The missing method accepts a closure that will be invoked if an implicitly bound model cannot be found. Implicit enum binding. PHP 8.1 introduced support for enums. To complement this feature, Laravel allows you to type in a backed enum on your route definition and Laravel will only invoke the route if that route segment
corresponds to a valid enum value. Otherwise, a 404-HTP response will be returned automatically. For example, given the following enum of category, string, case fruits, case people, you may define a route that will only be invoked if the category route segment is fruits or people. Otherwise, there will return a 404-HTP response. So, route get categories category, you can input, implicitly call that function with an enum. Explicit binding. You're not
required to use Laravel's implicit convention-based model resolution in order to use model binding. You can also explicitly define how route parameters correspond to models. To register an explicit binding, use the router's model method to specify the class for a given parameter. You should define your explicit model bindings at the beginning of the boot method of your app's service provider. Next, define a route that contains a user parameter. So route colon colon get users slash
Since we have bound all user parameters to the app models user model in the bootstrap file, an instance of that class will be injected into the route. So for example, a request to user slash one will automatically inject the user instance from the database, which has an ID of one. If a matching model instance is not found in the database, a 404 HTTP response will be automatically generated. Customizing the resolution logic.
If you wish to define your own model binding resolution logic, you may use the route colon colon bind method. The closure you pass to the bind method will receive the value of the URI segment and should return the instance of the class that should be injected into the route. Again, this customization should take place in the boot method of your application's app service provider. Public function boot route colon colon bind user return user. Alternatively, you may override the resolve route binding method on your eloquent model.
This method will receive the value of the URI segment and should return the instance of the class that should be injected into the route. If a route is utilizing implicit binding scoping, the resolve child route binding method will be used to resolve the child binding of the parent model. Fallback routes. Using the route fallback method, you may define a route that will be executed when no other route matches the incoming request.
Typically, unhandled requests will automatically render a 404 page via your application's exception handler. However, since you would typically define the fallback route within your routes.web.php file, all middleware in the web middleware group will apply to the route. You are free to add additional middleware to this group as needed. So route, colon, colon, fallback function as a group route. Rate limiting. Laravel includes powerful and customizable rate limiting services that you may utilize
to restrict the amount of traffic for a given route or group of routes. To get started, you should define rate limiter configurations that meet your application's needs. Rate limiters may be defined within the boot method of your application's App Service Provider class. Rate limiters are defined using the rate limiters' facades for method. The for method accepts a rate limiter name and a closure that returns the limit configuration that should apply to routes that are assigned to the rate limiter. Limit configuration are
instances of the IlluminateCashRateLimitingLimit class. The class contains helpful builder methods so that you can quickly define your limit. The rate limiter name may be any string you wish. So, rate limiter for, pass a global function request, passing the request to return limit colon colon per minute 1000. If the incoming request exceeds the specified rate limit, in this case 1000, a response with 429 HTTP status code will automatically be returned by
If you would like to define your own response, it should be returned by a rate limit. You may use the response method. RateLimiter colon colon four returns a response of a customer response. Since RateLimiter callbacks receive the incoming HTTP request instance, you may build the appropriate RateLimiter rate limit dynamically based on the incoming request or authenticated user. Segmenting Rate Limits
you may wish to segment rate limits by some arbitrary value. For example, you may wish to allow users to access a given route 100 times per minute per ID address. To accomplish this, you may use the BY method when building your rate limit. So, return request to user vip for limit none, limit per minute by request. To illustrate this feature using another example, we can limit access to the route to 100 times per minute per authenticated user ID or 10
times per minute per IP address for guests. So in the return of the rate limiter 4, you can say limit per minute 100 by request user ID or limit per minute 10 by request IP. Multiple rate limits. If needed, you may return an array of rate limits for a given rate limiter configuration. Each rate limit will be evaluated for the route based on the order that they are placed within the array. Rate limiter 4, login, rate limit per minute 500, limit per minute 3 by
request input email. Attaching rate limiters to routes. Rate limiters may be attached to routes or route groups using the throttle middleware. The throttle middleware accepts the name of the rate limiter you wish to assign to the route. By default, the throttle middleware is mapped to the middleware throttle request class. However, if you are using Redis as your application's cache driver, you may wish to instruct Laravel to use Redis to manage rate limiting. To do so,
you should use the throttle with Redis method in your application's app.php file. This method maps the throttle middleware to the throttle request within Redis middleware class. Form Method Spooning. HTML forms do not support put, patch, or delete actions, so when defining put, patch, or delete routes that are called from an HTML form, you will need to add a hidden underscore method field to the form. The value sent with the underscore method field will be used as the HTTP request method,
So form action example method post and put type hidden name underscore method with a value of put. For convenience, you may use the at method blade directive to generate the underscore method input field. So instead of using all that, you can use at method put. Accessing the current route. You may use the current, current route name, and current route action methods on the route facade to access information about the route handling the incoming request. You may refer to the API documentation for both the underlying class of the route facade
and route instance to review all of the methods that are available on the router and route classes. Cross-origin resource sharing. Laravel can automatically respond to CORS options HTTP requests with values that you configure. The options request will automatically be handled by the handle CORS middleware that is automatically included in your application's global middleware stack. Sometimes you may need to customize the CORS configuration values for your application.
You may do so by publishing the CORS configuration file using the config publish artisan command php artisan config publish CORS. This command will place a CORS.php configuration file within your application's config directory. For more information on CORS and CORS headers, please consult the MDM web documentation on CORS. Route Caching. When deploying your application to production, you should take advantage of Laravel's route
Cache. Using the Route Cache will drastically decrease the amount of time it takes to register all of your application's routes. To generate a Route Cache, execute the Route Cache Artisan command, phpartisan route cache. After running this command, your cached routes will be loaded on every request. Remember, if you add any new routes, you will need to generate a fresh Route Cache. Because of this, you should only run the Route Cache command during your project's deployment. and use the route clear command to clear the route cache.
Okay, before we start with middleware, I'm going to take a quick break.
Thank you.
Alright. Middleware. Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes 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 beside 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 middlewares are typically located in your application's middleware directory.
a new middleware, use the make middleware artisan command, php artisan make middleware. The command will place a new ensure token is valid 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 URL. So for example, public function
handle if request input token does not equal my secret token return redirect home that's in the class ensure token is valid middleware as you can see the given token does not match our secret token the middleware will return an http redirection to redirect 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 so return
dollar sign next in parentheses 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. All middleware are resolved via the service container, so you may type hint any dependencies you need within a middleware's constructor. Middleware and responses. Of course, middleware can perform tasks before or after passing the
the request deeper into the application. For example, the following middleware would perform some tasks before the request is handled by the application. The middleware object provided to them with middleware 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 global parameters. End of list of the global middleware. If you would like to add a middleware to the beginning of the list, you should use the pre-pend method. Manually managing Laravel's default global middleware. If you would like to manage Laravel's global middleware stack manually, you may provide
Laravel's default stack of global middleware to the use method. Then you may adjust the default middleware stack as necessary. So middleware use and then add your middleware there as a parameter. Assigning middleware to routes. If you would like to assign middleware to specific routes, you may invoke the middleware method when defining the route. So route get an appending middleware and passing in the middleware as a parameter there. You may assign
multiple middlewares to the route by passing an array of middleware names to the middleware method. 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 without middleware method. You may also exclude a given set of
middleware from an entire group of route definitions. The without middleware method can only remove route middleware and does not apply to global middleware. Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this by using the append to group method within your application's bootstrap app.php. So with middleware as a function, you can middleware append to group with a group name and then pass in the middleware as an array. Middleware groups may be assigned to routes
and controller actions using the same syntax as individual middleware. Laravel's included predefined web and API middleware groups that contain common middleware you may want to include and apply to your web API routes. Remember, Laravel automatically applies these middleware groups to the corresponding web.php and api.php files. the Web Middleware group, the API Middleware group.
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 convening alternatives to the append to group method. So Middleware Web Append, and then a middleware, Middleware API Prepend, and then a middleware. You may even replace one of Laravel's default middleware group entries with a custom middleware of your own. Or you may remove a middleware entirely.
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 within their default middleware, allowing you to customize them as necessary. So with middleware, middleware group of web, and then you can pass all of them in and remove the ones that you need. Same thing with the group of API.
Note, by default, the web and API middleware groups are automatically applied to your application's corresponding web.php and api.php files by the bootstrap app.php file. 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. Once the middleware alias has been defined in your application's app.php file, you may
use the alias when assigning the middleware to routes. For convenience, some of Laravel's built-in middleware are aliased by default. For example, the auth middleware is an alias for the authenticate middleware. Below is a list of the default middleware aliases. So we have auth. Auth.basic, auth.session, cache.headers, can, guest, password.confirm,
cognitive, signed, subscribed, throttle, verified. 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 using the priority method in your application's bootstrap app.php file. 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 ensure user has role
middleware that receives a role name as an additional argument. Additional middleware parameters will be passed to the middleware after the next argument. Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a colon. So middleware role colon editor. Multiple parameters can be delimited by comma. So role colon editor, comma publisher. Terminable middleware.
Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. If you define a terminate method on your middleware and your web server is using fast CGI, the terminate method will automatically be called after the response is sent to the browser. So the terminate method should receive both the request and the response. And once you've 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. 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 singleton method. Typically, this should be done in the register method of your app service provider. So public function register this app singleton terminating middleware class. CSRF protection. 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, CSRF attacks, 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 slash user slash email route that accepts a post request that changes the authenticated user's email address. Most likely this route requests and 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 slash user slash email route and submits the malicious user's own email address. If the malicious website automatically submits the form when this page is loaded, the malicious user only needs to alert 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, preventing CSRF requests. Layerville automatically generates a CSRF token for each active user session managed by the application. This token is used to verify that the authenticated user is the person actually making the request 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 session or via the CSRF token helper function. 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 at CSRF blade directive to
generate the hidden token input field, at CSRF in this form. The validate CSRF token 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 group tokens match, we know that the authenticated user is the one initiating the request. If you are building an SBA that is utilizing Laravel as an API backend, you should consult the Laravel Sanctum documentation.
For information, authenticating with your API and protecting against CSRF vulnerabilities. Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their weblook system, you will need to exclude your Stripe weblook handler route from CSRF protection, since Stripe will not know what CSRF token to send to your routes. Typically, you should place these kind of routes outside the web middleware group that Laravel applies to all routes in the route's web.php file.
However, you may also exclude specific routes by providing their URIs to the validate CSRF tokens method in your application's app.php file. For convenience, the CSRF middleware is automatically disabled for all routes when running tests. In addition to checking for the CSRF route token as a POST parameter, the validate CSRF CSRF token middleware, which is included in the web middleware group by default, will also check
for the XCSRF token request header. You could, for example, store the token in an HTML meta tag. 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. XCSRF 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 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 XSRF token header on same origin requests. Note, by default,
the app, the resources.js bootstrap.js file includes the Axios HTTP library, which will automatically send the xxsrt token header for you. Controllers. 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 requests handling logic into a single class.
For example, a user controller class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the HTTP controllers directory. Writing controllers, 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 HTTP controllers directory. 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. So once you have written a controller class and method, you may define a route to the controller method like so. When an incoming request matches a specified route URI, the show method on the user controller class will be invoked and the route parameter 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. 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 double underscore invoke method within the controller. 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. So route post server provision server colon colon class. You may generate an invocable controller by using the dash dash invocable option of the make controller artisan command. Note controller stubs may be customized using stub publishing. So middleware may be assigned to the controller's routes in your route files.
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 action. So public static function middleware, return auth new middleware. And this extends controller with implements hasMiddleware.
You may also define controller middleware as closures, which provides a convenient way to define inline middleware without writing an entire middleware class. Public static function middleware array return function return request. 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 those 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 commands, dash dash resource option to quickly create a controller to handle these actions. This command will generate a controller at photocontroller.php in our controllers HTTP directory.
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. So in route colon colon resource photos with a parentheses of photo controller colon colon class. The 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 colon list artisan command.
You may even register many resource commands, resource controllers at once by passing an array to the resources method. So route, colon, colon, resources, and then an array specifying specific controllers. Actions handled by resource controllers. Resource controllers have git, git with index, git with create, post with store, git with show, git with edit, put patch with update, and delete with destroy.
Missing middleware, 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. Soft deleted models. Typically, implicit model binding will not retrieve models
that have been soft deleted. You will instead return a 404 HTTP response. However, you can instruct the framework to allow soft deleted models by invoking the with trashed method when defining your resource route. So use HTTP controllers, float controller, route resource,
photos, photo controller, clone clone class, and then append with trashed. Calling with trashed with no arguments will allow soft to lead in models for the show, edit, and update resource routes. You may specify a subset of these routes by passing an array to the with trashed method. So with trashed and with an array of specifically show. Specifying the resource model. If you are using route model binding and would like
the resource controller's methods to type hint a model instance, you may use the dash-dash model option when generating the controller. You may provide the dash-dash request option when generating a resource controller to instruct Artisan to generate form request classes for the controller storage and update methods. So PHP artisan make controller, photo controller,
dash dash model equals photo dash dash resource dash dash requests. When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions. Route resource and then you could pass in accept, create, or update, destroy, or only index or show. 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 API resource method to automatically exclude these two routes. You may register many API resource controllers at once by passing an array to the API resources method. So route colon colon API resources, and then passing an array there. To quickly generate an API resource controller does not include the create or edit methods, use the dash dash API switch when executing the make controller command.
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. So photos, dot comments in your route resource. This route will register a nested resource that may be accessed with URIs like the following. So slash photo slash photo as a route binding,
comments slash and comment as a route binding. Scoping nested resources. Laravel's implicit model binding feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the scope method when defining your nested resource, you may enable automatic scoping as well as instruct Laravel which field the child resources should be retrieved by. For more information on how to accomplish this, please
see the documentation on scoping resourcing routes. 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 and URI segments, you may choose to use shallow nesting. So route resource, photos.comments, comment controller shallow. This route definition will define the routes, git index, git create,
post store, git show, git edit, put patch update, delete, destroy. So 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. So route resource create photos.build. By default, RouteResource will create the route parameters for your resource routes based on the singleized 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. So RouteResource users and then with the parameters array users admin user. The example above generates the following URI for the resources show route. slash user slash parentheses admin underscore user. Scoping resource routes.
Laravel's scoped implicit model binding 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. This route will register a scoped nested resource that may be accessed with URIs like the following
slash photos slash photo comments comment colon 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 parents 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. So localizing resource URIs. By default, RouteResource will recreate resource URIs using
English verbs and plural rules. If you need to localize the create and edit action verbs, you may use the Route colon colon resource verbs method. This may be done at the beginning of the boot method within your application's app service provider. So Laravel's Pluralizer supports several different languages which you may configure based on your needs. Once the verbs and pluralization language have been customized, a resource
route registration such as Publication Controller Class will produce the following URIs. And this is within Spanish Publicación. Publicación slash crear, Publicación slash editar. Supplementing resource controllers. If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before you call to the route resource method. Otherwise, the routes defined by the resource method may unintentionally
take precedence over the supplemental routes. So route get photos popular is above route resource photos. Note, remember to keep your controllers focused. If you find yourself routinely needing methods outside of the typical set of resource actions, consider splitting your controller into two smaller controllers. Singleton resource controllers. Sometimes your application will have resources that may only have a single instance. For example, a user's
profile can be edited or updated, but a user may not have more than one profile. Likewise, an image may have a single thumbnail. These resources are called a single resource, meaning one and only one instance of the resource may exist. In these scenarios, you may register Singleton Resource Controller. So route Singleton Profile, Profile Controller class. This Singleton Resource definition above will register the following routes. As you can see, the 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. So you just have git show, git edit, or put-update. Singleton Resources may also be nested within a standard resource. So route singleton photos dot thumbnail can pass in a thumbnail controller class. In this example, the photos resource would receive all the standard resource routes. However the thumbnail resource would be a singleton resource with the following routes.
It would have git show, git edit, and put patch as an update action. Creatable singleton resources. Occasionally you may want to define creation and storage routes for a singleton resource. To accomplish this, you may invoke the createable method when registering the singleton resource route. So route singleton photos dot thumbnail thumbnail controller class, createable. In this example, the following routes will be registered.
As you can see, a delete route will also be registered for createable singleton resources. So git create, post store, git show, git edit, put patch update, delete destroy. If you would like Laravel to register the delete route for a singleton resource but not register the creation or storage routes, you may utilize the destroyable method. So that's pending to the singleton. API singleton resources. The API singleton method may be used to register a singleton resource that will be manipulated
via an API, thus rendering the create and edit routes unnecessarily. Route API singleton, profile, profile controller, class. Of course, API singleton resources may also be creatable, which will register store and destroy routes for the resource. Dependency Injection and Controllers. The Laravel service container is used to resolve all Laravel controllers. As a result, you are able to type in any dependencies your controller may need in
its constructor. The declared dependencies will automatically be resolved and injected into the controller instance. Method Injection. In addition to constructor injection, you may also type in dependencies on your controller's methods. A common use case for method injection is injecting the IlluminateHTPRequest instance into your controller methods. For example, public function store and then you can reject the redirect response method. 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, route put user with a parentheses ID, user controller class update, you may still type in the illuminate HTTP request and access your ID parameter by defining your controller method as follows. So in the controller of the user controller, you can add the redirect response to return the user's page.
HTTP requests. Introduction. Laravel's HTTP slash request class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as to retrieve the input cookies and files that were submitted with the request. Interacting with the request. Accessing the request. To obtain an instance of the current HTTP request via dependency injection, you should type in the eliminate HTTP request class in your route closure or controller method.
The incoming request instance will automatically be injected by the Laravel service container. As mentioned, you may also type in the HTTP request class on a route closure. The service container will automatically inject incoming requests into the closure when it is executed. So 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 was defined like so, route put user with parentheses ID,
passing user controller class with update, you may still type in the HTTP request and access your ID route parameter by defining your controller method as follows. Controller extends controller, passing in the request to the update function, returning the redirect response HTTP method. Request, path, host, and method. The Illuminate HTTP request instance provides a variety of
methods for examining the incoming HTTP requests and extends the Symfony Component HTTP Foundation request class. We will discuss a few of the most important methods below. Retrieving the request path. The path method returns the request path information. So if the incoming request is targeted at example.com slash foo slash bar the path method will return foo slash bar so your dollar sign uri equals request arrow path inspecting the request path route the is method
allows you to verify that the incoming incoming request path matches a given pattern so you may use the you may use the asterisk character as a wild card when utilizing this method so if request is admin slash asterisk. Using the route is method, you may determine if the incoming request has matched a named route. So if request slash route is is admin dot asterisk. Retrieving the
request URL. To retrieve the full URL for the incoming request, you may use the URL or full URL methods. The URL method will return the URL without the query string, while the full URL method includes the query string. If you would like to append query string data to the current URL, you may call the full URL with query method. This method merges the given array of query string variables with the current query string. So if you recall request full URL with query, and in the
array you said type is phone. If you would like to get the current URL with a given query string parameter, you may utilize the full URL without query method. Retrieving the request host. You may retrieve the host of the incoming request via the host, HTTP host, and scheme and HTTP host methods. That's from the request object. So retrieving
the request method, the method method will return the HTTP reverb for the request. So You may use the isMethod method to verify that the HTTP verb matches a given string. So method equals request method. Request headers. You may retrieve a request header from the 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. The hasHeader method may be used to determine if the request contains a given header. For convenience, the bearer token 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. Request IP Addresses. The IP method may be used to retrieve the IP address of the client that made the request to your application. So IP address equals request IP.
If you would like to retrieve an array of IP addresses, including all of the client IP that were forwarded by proxies, you may use the IPs method, so IPS. The original client IP address will be at the end of the array. In general, IP addresses should be considered untrusted, user-controlled input and be used for informational purposes only. Content negotiation. Laravel provides several methods for inspecting the incoming requests
requested content types via the accept header. First, the get acceptable content types method will return an array containing all of the content types accepted by the request, so get acceptable content types. 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. 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. 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. PSR-7 requests. The PSR-7 standard 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 would 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. Once you have installed these libraries, that's composer require Symfony par HTTP message bridge and composer require nyholm slash PCLF PSR 7, you may obtain a PSR 7 request by type hinting the request interface on your wrap closure or controller method.
So that type in is use psr server request interface and then passing that into the function. If you return a psr7 response note instance from a router controller, it will automatically be converted back to a Laravel response instance and be displayed by the framework. Input. Retrieving input and retrieving all input data. You may retrieve all the input requests input data as an array using the all method. This method may be used regardless of whether
the incoming request is from HTML form or is an XHR request. So input request all. Using the collect method you may retrieve all the incoming request input data as a collection. The collect method also allows you to retrieve a subset of the incoming request input as a collection. So collect users each function string user and you can break that down. 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. So name equals request input, and you can grab the name value. 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.
When working with forms that contain array inputs, use dot notation to access the arrays. You may call the input method without any arguments to retrieve all the input values as an associative array. 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. So, request query, grab the value name.
If the requested query string value data is not present, the second argument to this method will also be returned. You may call the query method without any arguments in order to return all of the query string values as an associative array. 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 slash JSON. You may even use dot syntax to retrieve values
that are nested within JSON arrays or objects. Retrieving stringable input values. Instead of retrieving the inputs, the request input data as a primitive string, you may use the string method to retrieve the request data as an instance of a luminance support stringable. 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 one, one in quotations, true, true as a string, on as a string, and yes as a string. All other values will return false. So that would be the parameter archived is request Boolean with the parameter archived. Retrieving date input values. For convenience, input values containing dates and 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. The second and third arguments accepted by the date method may be used to specify the dates format and time zone respectively. If the input field is present but has an invalid format, an invalid argument exception will be thrown. Therefore, it is recommended that you validate the input before invoking the date method. Input values that correspond to PHP enums 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. So status request enum, status, and then status class as the second argument. Retrieving input dynamic properties. You may also access users input using dynamic properties on the IlluminateHttpRequest instance.
For example, if one of your application's forms contains a name field, you may access the value of the field like so, 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. Retrieving a portion of the input field. 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.
So input is request only username, password, or accept credit card. Warning, the only method returns all the key value pairs that you request. However, it will not return key value pairs that are not present on the request. 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. So if request has name. When given an array, the has method will determine if all the specified values are present.
has name or email. The hasAny method returns true if any of the specified values are present, so hasAny name or email. The when has method will execute the given closure if a value is present on the request, when has name. A second closure may be passed to the when has method that will be executed if the specified value is not present on the request, so when has name, and the second parameter is not. If you would like to define if a value is present on the request
and is not an empty string, you may use the filled method. If request filled name. The anyfilled method returns true if any of the specified values is not an empty string. So the whenfilled method will execute the given closure if a value is present on the request and is not an empty string. So when filled name. A second closure may be passed to the whenfilled method that will be executed if the specified value is not filled. So when
field name and if it's not, here's the second function. To determine if a given key is absent from the request, you may use the missing and when missing method. So if request missing name, request when missing, the second function is when it's missing or when it's not missing. Merging additional input. Sometimes you may need to manually merge additional input into the request 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. The merge if missing method may be used to merge input into the request if the corresponding keys do not already exist within the request input data. So request merge if missing votes. Old input. Laravel allows you to keep input from one request during the next request. This feature is particularly useful for pre-populating forms after detecting validation errors. However, if you are using Laravel's included validation features, 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. Flashing Input to the Session. The Flash method on the IlluminateHTB request class will flash the current input to the session so that it is available during the user's next request to the application. So request flash. You may also use the Flash Only and Flash Accept 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. Flash only the username or email or flash except the password. Flashing input when 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 with input method. Return redirect form with input, return redirect routes. Retrieving old input.
If you approve flashed input from the previous request, invoke the old method on an instance of HTTP request, the old method will pull the previously flashed input data from this session. So username request old username. Laravel also provides a global old helper. If you are displaying old input within a blade template, 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.
So in your field in blade, if you have an input, the value can be a parameter of old with the, or the function, the helper of old with a parameter of username. Cookies. Retrieving cookies from requests. All cookies were 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 IlluminateHttp request instance.
So value, request, cookie, name. Input, trimming, and normalization. By default, Laravel includes the trim strings and convert empty strings to null 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 strings 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. So in that middleware remove, you can remove, convert empty strings to null and trim strings. If you would like to disable string trimming and empty string conversion for a subset of requests to your application, you may use the trim strings and empty strings to null middleware methods within your application's app.php file. Both methods accept an array of closures which should return true or false to indicate whether
input normalization should be skipped. So middleware convert empty strings to null except function which route. Files, retrieving uploaded files. You may retrieve uploaded files from an HTTP request instance using the file method or using dynamic properties. The file method returns an instance of the HTTP uploaded file class which extends the PHP SPL file info class and provides a variety of methods for interacting with the file. So file request file photo, file
request photo. You may determine if a file is present on the request using the has file method. In addition to checking if the file is present, you may verify that there were no problems uploading the file via the isValid method. The uploaded file class also contains methods for accessing the file's fully qualified path
and its extension. The extension method will attempt to guess the file's extension based on its contents. This extension may be different from the extension that was supplied by the client. path request photo path, extension request photo extension. Other file methods. There are a variety of other methods available on uploaded file instances. Check out the API documentation for the class for more information regarding these methods. Storing uploaded files. To store an uploaded file you will typically use one of your configured file systems. The uploaded file class
is a store method that will move an uploaded file to one of your disks, which may be a location on on your local file system or a cloud storage location like Amazon S3. The store method accepts the path where the file should be stored relative to the file system's configured root directory. This path should not contain a file name since a unique ID will automatically be generated to serve as the file name. The store method also accepts an optional second argument for the name of the disk that should be used to store the file.
The method will return the path of the file relative to the disk's route. So path request photo store images, path request photos, store images, and then S3. If you do not want a file name to be automatically generated, you may use the store as method, which accepts the path, file name, and disk name as its arguments. Configuring trusted proxies. When running your applications behind a load balancer that terminates TLSSLSSLS certificates,
you may notice your application sometimes does not generate HTTPS links when using the URL helper. this is because your application is being forwarded traffic from your load balancer on port 80 and does not know it should generate secure links. To solve this, you may enable the trust proxies middleware that is included in your Laravel application, which allows you to quickly customize the load balancers or proxies that should be trusted by your application. Your trusted proxies should be specified using the trust proxies middleware method in your application's
app.php file. In addition to configuring the trusted proxies, you may also configure the proxy headers that should be trusted. So trust proxies and then you can pass an array of headers. If you're using AWS, note, if you're using AWS Elastic Load Balancing, the headers value should be request header x forwarded AWS ELB. If your load balancer uses the standard forwarded header from RFC 7239, the headers value should be request header forwarded. For information
on the constants that may be used in the headers value, check out Symfony's documentation on trusting proxies. Trusting all proxies. If you are using Amazon AWS or another cloud load balancer provider, you may not know the IP addresses of your actual balancers. In this case, you may use asterisk to trust all proxies. Configuring trusted hosts. By default, Laravel will respond to all requests it receives regardless of the content of the HTTP request's host header.
In addition, the host header's value will be used when generating absolute URLs to your application during a web request. Typically, you should configure your web server such as Nginx or Apache to only send requests to your application that match a given host name. However, if you do not have the ability to customize your web server directly and need to instruct Laravel to only respond to certain host names, you may do so by enabling the Trust Host Middleware for your application. To enable the Trust Host Middleware, you should invoke the Trust Host Middleware method in your application's app.php
file. Using the app method of this method, you may specify the host names that your application should respond to. So incoming requests with other host headers will be rejected. So middleware function hosts, middleware trusts hosts at Laravel.test, for example. By default, requests coming from subdomains of the application's URL are also automatically trusted. If you would like to disable this behavior, you may use the subdomains argument.
So with middleware, middleware trust hosts at Laravel.test, subdomains, false. HTTP responses.
Thank you.
HTTP responses. Creating responses, strings and arrays. All routes and controllers should return a response to be sent back to the user's browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response, so route
git return hello world. In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response, so route git slash can return an array of one, two, and three. Note, did you know you can also return eloquent collections from your routes or controllers? They will automatically can be converted to JSON, give it a shot. Response objects. You won't just be returning simple strings or arrays from your route actions.
Instead, you will be returning full HTTP response instances or views. Returning a full response instance allows you to customize the response's HTTP status code and headers. A response instance inherits from the Symfony component HTTP foundation response class, which provides a variety of methods for building HTTP responses. By default, requests coming from subduing, oh.
Eloquent models and collections. You may also return eloquent ORM models and collections directly from your routes and controllers. When you do, Laravel will automatically convert the models and collections to JSON responses while respecting the models hidden attributes. So route git user, passing in user, return user. Attaching headers to responses. in mind that most response headers are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response
before sending it back to the user. Response content with a header, and you can add those headers as parameters there. Or you may use the with headers method to specify an array of headers to be added to the response instead of the method. Cache control middleware. Laravel includes a cache dot headers middleware, which may be used to quickly set the cache control header for a group of routes. Directives should be provided using the snake case equivalent of the corresponding cache control directive and should be separated by
a semicolon. If ETag is specified in the list of directives, an empty five hash of the response content will automatically be set as the ETag identifier. Attaching cookies to responses. You may attach a cookie to an outgoing HTTP response instance using the cookie method. you should pass the name, value, and the number of minutes the cookie should be considered valid to this method. The cookie method also accepts a few more arguments which are used less frequently.
Generally, these arguments have the same purpose and meaning as the arguments that will be given to PHP's native setCookie method. If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the cookie facade to queue cookies for attachment to the response when it is sent. The queue method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser. Generating cookie instances. If you would
like to generate a Symfony component HTTP foundation cookie instance that can be attached to a response instance at a later time, you may use the global cookie helper. The cookie will not be sent back to the client unless it is attached to a response instance. So cookie equals cookie, name, value, and minutes added in, return response, hello world, cookie. Expiring cookies early. You may remove a cookie by expiring it via the without cookie method of
an outgoing response. So return response, hello world, without cookie, name. If you do not yet have an instance of the outgoing response, you may use the cookie facade's expire method to expire a cookie. So cookie colon colon expire name. Cookies and encryption. By default, thanks to the the Illuminate Cookie Middleware Encrypt Cookies Middleware. All cookies generated by Laravel are encrypted and signed so they can't be modified or read by the client. If you would
like to disable encryption for a subset of cookies generated by your application, you may use the Encrypt Cookies method in your application's BootstrapApp.php. Redirects. Redirect responses are instances of the HTTP redirect response class and contain the proper headers needed to redirect the user to the URL. There are several ways to generate a redirect response header or redirect response instance. The simplest method is
to use the global redirect helper. So route git dashboard return redirect. 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 this session, make sure the route calling the back function is using the web middleware group. So route post user profile function. Validate the request. Return back with input. Redirecting to
named routes. So 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 redirect response to a named route, you may use the route method. Return redirect route. If your route has parameters, you may pass them as the second
argument in the route method. Return redirect route profile. 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, so the ID will be extracted automatically. For a route the following URI, profile ID, you can 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, or you can override the get route key method on your eloquent model. Redirect into controller actions. You may also generate redirects to controller actions. To do so, pass the controller and action name to the action method. So return redirect action and then pass in a controller. If the controller route requires parameters, you may pass them as a second argument to the action method. 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 redirect response without any additional URL encoding and validation or verification. So return redirect away to some website. Redirecting with flash session data. Redirecting to a new URL and flashing data to the session 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 redirect response instance and flash data
to the session in a single fluent method chain. So return redirect dashboard with status. After the user is redirected, you may display the flash message from the session. For example, using blade syntax, if session has status parameter, then show the session with status brand. Redirecting with input. You may use the with input method provided by the redirect response instance to flash the current request 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 during the next request to repopulate the form, so return back with input. 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 contract's routing response factory contract is returned. This contract provides several helpful methods for generating responses.
So view responses. If you need control over the responses status and headers, but also need to return a view as the responses content, you should use the view method. So return response view. 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. 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. If you would like to create a JSONP resource, you may use the JSON method in combination with the with callback method. So return response JSON with the parameters as an array with callback with the request input. File downloads. The download method may be used to generate response that forces the user's browser to download the file at the given path. The download method accepts a file name as the second argument to the method, which will determine the file name 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. Warning, Symphony HTTP Foundation, which manages file downloads, requires the file being downloaded to have an ASCII file name. Stream 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 string download method in this scenario. This method accepts a callback file name
and an optional array of headers as its argument. File responses. The file method may be used to display a file such as an image or PDF directly in a 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 its second argument. Response macros. If you would like to define a custom response that you can reuse 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, such as the app provider's app service provider service provider. So response colon macro in the boot method. 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 response factory implementation or the response helper. So return response caps with a parameter
of food. Views. 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 replace 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 in language. A simple view might
look something like this. You have the HTML of a body with an h1 of hello, and then passing in the name parameter using double curly brackets. Since this view is stored at resources views greeting.blade.php, we may return it using the global view helper like so. So route git slash, and then you return the function with a return of view, passing in the greeting view name.
Then in the second parameter, an array with the name is James. Note, looking for more information on how to write blade templates, check out the full blade documentation to get started. Writing views in React slash view. Instead of writing their front end 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, a library that makes it a
cinch to tie your React slash Vue front end to your Laravel back end without the typical complexities of building an SBA. Our Breeze and Jetstream starter kits give you a great starting point for your next Laravel application powered by Inertia. In addition, the Laravel Bootcamp provides a full demonstration of building a Laravel application powered by Inertia,
including examples in Vue and React. Creating and rendering views. You may create a view by placing a file with the .blade.php extension in your application's resources slash views directory, or by using the make colon view greeting. The blade.php extension informs the framework the file contains a blade template. Blade templates contain HTML as well as blade directives that
allowing you to easily echo values, create if statements, iterate over data, and more. Once you've created a view, you may return it from one of your application's routes or controllers using the global view helper. So, route git slash return view of green. Views may also be returned using the view facade. So, return view colon colon make green. As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources view 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. Nested view directories. Views may also be nested within subdirectories of the resources slash views directory. Dot notation may be used to reference nested views. For example, if your view is stored at resources slash views slash admin slash profile dot blade dot php, you may return it from one of your applications route slash controllers like so. So return view admin.profile.
Warning, this view directory name should not contain the dot character. Creating the first available view. Using the view facades 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. So return view first, custom.admin. Determine if a view exists. to determine if a view exists, you may use the view facade. The exist method will return true
if the view exists. Passing data to views. As you saw in the previous examples, you may pass an array of data to the views to make that data available to the view. 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 continue chaining methods before returning the view. So return view greeting with name is Vittoria, with occupation comma astronaut. Sharing data with all views. Occasionally you may need to share data with all views that are rendered by your application. You may do so
using the viewFacadesShare 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 provider's app service provider class or generate a separate service provider to house them. ViewComposers. ViewComposers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered,
A View Composer can help you organize that logic into a single location. View Composers may prove particularly useful if the same view is returned by multiple routes or controllers within your application and always needs a particular piece of data. Typically, View Composers will be registered within one of your application's service providers. In this example, we'll assume that the app provider's app service provider will house this logic.
We use the ViewFacadesComposer method to register the ViewComposer. Laravel does not include a default directory for class-based ViewComposers, so you are free to organize them however you wish. For example, you could create an app ViewComposers directory to house all of your application's ViewComposers. In the class app service provider, in your boot function, you can have facades, backslash
view colon colon composer and then pass in the view there. Now that we have registered the composer, the compose method of the app view composers profile composer class will be executed each time the profile view is being rendered. So let's take a look at an example of the composer class. So in the composer class, you have public function of construct with protected user repository of users. And then we combine data to the view public function
compose view view with count. As you can see, all view composers are resolved via the service container, so you may type in any dependencies you need within a composer's constructor. So, in this example, public function construct protected user repository users. Attaching a composer to multiple views. You may attach a view composer to multiple views at once by passing an array of views as the first argument of the composer method. The composer method also
accepts the asterisk character as a wildcard, allowing you to attach a composer to all views. View Creators. The creators are very similar to View Composers, however they are executed immediately after the view is instantiated instead of waiting until the view is about to render. To register a View Creator, use the Creator method. So View Creator, profile, passing in the Profile Creator class. Optimizing Views. By default, Blade template views are
compiled on demand. When a request is executed, that renders a view. Laravel will determine if a compiled version of the view exists. If the file exists, Laravel will then determine if the uncompiled view has been modified more recently than the compiled view. If the compiled view either does not exist or the uncompiled view has been modified, Laravel will recompile the view. Compiling views during the request may have a small negative impact on performance. So,
Laravel provides the view cache artisan command to precompile all the views utilized by your application. For increased performance, you may wish to run this command as part of your deployment process, which is php artisan view cache. You may use the view clear command to clear the view cache. Blade templates. 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 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, data may be passed to the blade view using the view helpers second argument. Route.get slash return view greeting, pass in those name. Supercharging blade with Livewire. Want to take your blade templates to the next level and build dynamic interfaces with ease? Check out Laravel Livewire. Livewire allows you to write blade components that are augmented with dynamic functionality
that would typically only be possible via front-end frameworks like React or Vue, providing a great approach to building modern reactive front-ends without the complexities, client-side rendering, or build steps of many JavaScript frameworks. You may display data that is passed to your blade views by wrapping the variable in curly braces. For example, given the following route, return view welcome, name Samantha, you may display
the contents of the name variable like so, hello comma bracket bracket dollar sign name bracket bracket. Note, Blade's double bracket echo statements are automatically sent through PHP's HTML special cares function to present XSS attacks. You are not limited to displaying the contents of the variables passed to the view, but 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.
So the current Unix time is double brackets time parentheses. HTML entity encoding. By default, Blade and Laravel E function will double encode HTML entities. If you would like to disable double encoding, call the Blade colon colon without double encoding method from the boot method of your app service provider. By default, blade double bracket statements are automatically sent through PHP's HTML
special cars function to present XSS attacks. If you do not want your data to be escaped, you may use the following syntax, hello, and then only single bracket with two exclamation points on each side, dollar name. Be very careful when echoing content that is supplied by users of your application. You should typically use the escape double curly brace syntax to prevent XSS attacks
when displaying user-supplied data. 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 at symbol to inform the blade rendering engine and expression should remain untouched. For example, if you have an H1 of Laravel, you can say hello, comma, at, double brackets, name, closing double brackets.
In this example, the at symbol will be removed by Blade. However, the double curly brackets, name expression will remain untouched by the Blade engine, allowing it to be rendered by your JavaScript framework. The at symbol may also be used to escape Blade directives. So if you have two at, so at if for a blade template, the HTML output would show as at if. 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, script var app, and then you can pass in PHP echo JSON in code. However, instead of manually calling JSON in code, you may use the 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. So var app equals double curly brackets illuminate support JS from array. The latest versions of the layer of the application skeleton include a JS facade, which provides convenient access to the functionality within your blade templates. So script var app equals from array.
Warning, you should only use the JS from method to render existing variables as JSON. The blade templating is based on regular expressions and attempts to pass a complex expression to the directive may cause unexpected failures. The at verbatim directive. If you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the at verbatim directive so that you do not have to prefix each blade echo statement with an at symbol. So at verbatim, anything that is displayed in there
is echoed out. Blade directives. In addition to template inheritance and displaying data, blade also provides convenient shortcuts for common PHP control structures such as conditional loops, statements. These shortcuts provide a very clean, terse way of working with PHP control structures while also remaining familiar to their PHP counterparts. You may construct if statements using the at if, at else if, at else, and at and if directives. These directives
function identically to their PHP counterparts. So you have at if, count records, is equal to one, I have one record, at else if, etc. For convenience, Blade also provides an at unless directive. In addition to the conditional directives already discussed, the at is set and at empty directives may be used as convenient shortcuts for their respective PHP functions.
Authentication directives. The at auth and at guest directives may be used to quickly determine if the current user is authenticated or is a guest. If needed, you may specify the authentication guard that should be checked when using the at auth or at guest directive. So at auth, admin, or at guest, admin. Environment directives. You may check if the application is running in the production environment using the at production directive. So at production could
be production-specific content. Or you may determine if the application is running in a specific environment using the at env directive. So at env staging, the application is running in staging. Section directives. You may determine if a template inheritance section has content using the at has section directive. So at has section navigation. And then anything in that block is displayed. You may use the section missing directive to determine if a section does not have content. So at section missing navigation, anything in that block is displayed.
Session directives. The at session directive may be used to determine if a session value exists. So If the session value exists, the template contents within the at session and at end session's directives will be evaluated. Within the at session directives contents, you may echo the valued variable to display the session value. So at session status. Switch statements. Switch statements can be structured using the at switch, at case, at break, at default, and at end switch directives.
Loops. In addition to conditional statements, Blade provides simple directives for working with PHP's loop structures. again, each of these directive functions identically to their PHP counterparts. So at for, for each, for else, empty, while. While iterating through a for each loop, note you may use 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 or at break directive. So at for each, user says user, if user type equals one, at continue or if the user number equals five at break that for each loop. You may also include the continuation or break condition within directive declaration at for each users as user continue the loop variable while iterating through a for each loop. A loop variable will be available
inside of your loop. The 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. So at for each users as user at if loop first. This is the first iteration. If you are in a nested loop, you may access the parent loops loop, dollar sign loop variable via the parent property. So at for
each users as user at for each nested in their user post as post if dollar sign loop parent first. This is the first iteration of the parent loop. The dollar sign loop variable also contains a variety of other useful properties. So a loop index, loop iteration, loop remaining, loop count, loop first, loop last, loop even, loop odd, loop depth, nesting level of the current loop,
and loop parent. Conditional classes and styles. The at 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. So at PHP is active equals false. Then in the at class method in the span, you can add specific
variables. Likewise, the at style directive may be used to conditionally add inline CSS styles to your HTML element. So span of at style with the array of background color red. For convenience, you may also use the at check directive to easily indicate if a given HTML checkbox input is checked. This directive will echo checked if the provided condition evaluates the true. Likewise, the at selected directive may be used to indicate if a given
select option should be selected. So option value at selected, old version equal version. Additionally, the at disabled directive may be used to indicate if a given element should be disabled. So at disabled if errors is not empty. Moreover, the at read only directive may be used to indicate if a given element should be read only. In addition, the at required
directive may be used to indicate if a given element should be required, including subviews. While you're free to use the at include directive, note Blade components and provide similar functionality and offer several benefits over the at include directive such as data and attribute binding. So blades attribute 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. 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. So at include view.name status of complete. If you attempt to at include a view which does not exist, there though we'll throw an error. If you would like to include a view that may or may
not be present, you should use the at include if directive. If you would like to include a view if a given Boolean expression evaluates the true or false, you may use the at include when and at include unless directives. To include the first view that exists from a direct given array of views, you may also use the include first directive, so at include first. Warning, you should avoid using the underscore, underscore, D-I-R, underscore, underscore, and
underscore, underscore, file, underscore, underscore, constants in your related views, since they will refer to the location of the cached compiled view. Rendering views for collections. You may combine loops and includes into one line with blades each directive. So at each view.name and then pass in jobs as a 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 at each
directive. This argument determines the view that will be rendered if the given array is empty. So at each view.name passing in the jobs variable as a job and then view.empty. Warning, views rendered via at each, do not inherit the variables from the parent view. If the child view requires these variables, you should use the for each and include directives instead. The at once directive. The at 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 different piece of JavaScript into the page's header using stacks. For example, if you are rendering a given component within a loop, you may wish to only push the JavaScript to the header the first time the component is rendered. Since the at once directive is often used in conjunction with the at push or at prepend directives, the at push once and at prepend once directives are
available for your convenience. In some situations, it's useful to embed PHP code into your view, so raw PHP. You can use the blade at PHP directive to execute a block of plain PHP within your template. So at PHP, dollar sign counter equals one. Or if you only need to use use PHP to import in class, you may use the at use directive. So at use app models flight. A second argument may be provided to the at use directive to alias the imported class. So at
use app models flight, aliases as flight model. 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. So that's double curly brackets with a dash dash on each end. this comment will not be present in the rendered HTML. Components. Components and slots provide similar benefits to sections, layouts, and includes. However, some may find the mental
model of components and slots easier to understand. There are two approaches to writing components, class-based components and anonymous components. To create a class-based component, you may use the make colon component artisan command. To illustrate how to use components, we will create a simple alert component. The make colon component command will place the component in the app view components
directory. So PHP artisan make component alerts. The make component command will also create a view template for the component. The view will be placed in the resources views components directory. When writing components for your own application, components are automatically discovered within the app view components directory and resources views components directory so no further component registration is typically required. You may also create components
within sub-directories so php artisan make component forms slash input. The command above will create an input component in the app view components forms directory and the view will be placed in the resources views components forms directory. If you would like to create an anonymous component which is a component with only a blade template and no class you may use the dash dash view flag when invoking the make component command. The command above will create a blade file
at form slash input dot blade dot php which can be rendered as a component via x dash forms dot input as a html tag. Manually registering package components. 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, you will need to manually register component class and its html tag alias. You should typically register your components in the boot method of your package's service provider. So public function boot blade component package alert, passing the alert class. Once your component has been registered, it may be rendered using its tag alias. So x dash package dash alert as an html string. Alternatively, you may use the component namespace method to auto load component classes
by convention. For example, a nightshade package might have calendar and color picker components that reside within the package views components namespace. This will allow the usage of package components by their vendor namespace using the package-name colon colon syntax. So x-nightshade state, colon colon calendars, for example, as an HTML tag.
Blade will automatically detect a class that's linked to this component by Pascal casing the component name. Subdirectories are also supported using dot notation. To display a component, you may use a blade component tag within one of your blade templates. Blade component tags start with the string x dash followed by the kebab case name of the component class. So x-alert or x-user-profile, again as an HTML tag.
If the component class is nested deeper within the app view components directory, you may use the dot character to indicate directory nesting. For example, if we assume a component is located at components input slash buttons dot php, We may render it like x-inputs.button.
If you would like to conditionally render your component, you may define a shouldRender method on your component class. If the shouldRender method returns false, the component will not be rendered. Passing Data to Components. You may pass data to blade components using HTML attributes. Hard-coded, permitted 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 colon character as a prefix.
So in your HTML tag, x-alert type equals error while colon message equals dollar sign message as a PHP attribute. 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. So in this class alert for the component, you could have public function with a construct
that has a string of type and a string of message, and then when you're passing it to the view, it is automatically there. When your component is rendered, you may display the contents of your component's public variables by echoing the variables by name. So alert dash double curly brackets dollar sign type or curly brackets double sign dollar sign message. Casing. Component constructor arguments should be specified using camel case while kebab case should be used when referencing
the argument names in your HTML attributes. For example, given the following component constructor public string alert type as camel case, the alert type argument may be provided to the component like so. When it's in the component, it is alert dash type equals danger. 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. So x dash profile colon user ID colon name is short attribute syntax, but it's equivalent to colon user ID equals dollar sign user ID in camel syntax. Escaping attribute rendering. Since some JavaScript frameworks such as AlpineJS also include colon dash prefix attributes, you may use a double colon dot colon colon prefix to inform blade that the attribute is not a PHP expression.
For example, given the following component, x dash button colon colon class equals danger is the leading. The following HTML will be rendered by blade. Component methods in addition to public variables being available to your component template. Any public methods on this component may be invoked. For example, imagine a component that has an isSelected method.
Public function isSelected string option. You may execute this method from your component template by invoking the variable matching the name of the method. So option is selected value with a question mark selected colon empty. 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 only return a closure from your component's
render method. This closure will receive a data array as its only argument. This array will contain several elements that provide information about the component. The component name is equal to the name used in the HTML tag after the x-prefix. So x-alert or component name will be alert. The attributes element will contain all the attributes that
were present on the HTML tag. The slot element is in support slash HTML string instance with the contents of the component's slot. The closure should return a string. If the return string corresponds to an existing view, that view will be rendered. Otherwise, the return string will be evaluated as an inline blade view. Additional dependencies. If your component requires dependencies from Laravel's service container, you may list them before any of
the component's data attributes, and they will automatically be injected by the container. So create the public instance, component instance, and your public function constructor. You have public alert creator, as assigned to $score, $creator, public string, $type, public string, $message. Hiding attributes slash 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 accept array property on your component. 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, x-alert type equals error colon message equals dollar sign message class equals mt-4. All 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. So div double curly brackets, $attributes has the component context. Using directives such as at env within component tags is not supported at this time. For example, x-alert colon live equals at env production will not be compile. Default slash merged attributes. Sometimes you may wish 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 bags merge method. This method is particularly useful for defining a set of default CSS classes that should always be applied to a component. So in a div, you have double curly bracket for attributes merge, and you can in that array pass in classes to be merged
to that attribute bag. If we assume this component is utilized like so, x-alert type equals error, colon message equals dollar sign message, class equals mb4, the final render HTML of the component will appear like the following. It will have the class that we defined previously, as well as the mb-4 that was passed into the component. 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, so div of attributes class. If you need to merge other attributes into your component, you can change the merge method,
chain the merge method onto the class method. So button of attributes class, you can merge the type is button. Note, if you need to conditionally compile classes on other HTML elements that shouldn't receive merged attributes, you can use the at class directive. 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 button attributes merge type button slot. 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. So x dash button type is submit. The rendered HTML of the button component in this
example would be button type equals submit. If you would like an attribute other than class to have its default value and injected values joined together, you may use the prepens 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. Retrieving and filtering attributes. You may filter attributes using the filter method. This
This method accepts a closure which should return true if you wish to retain the attribute in the attribute bag. So attributes filter with the function string of value, string of key, that key is equal to foo. For convenience, you may use the where starts with method to retrieve all attributes whose keys begin with a key string. Conversely, the where doesn't start with method may be used to exclude all attributes whose keys begin with a given string.
Using the first method, you may render the first attribute in a given attribute bag. 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. If an array is passed to the has method, this method will determine if all of the given attributes are present on the component. The has any method may be used to determine if any of the given attributes are present
on the component. You may retrieve a specific attribute's value using the get method. So $attributes, get class. 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. That's data, render, resolve, view, should render, view, with attributes, with name. Slots.
You 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. So this is alert.blade.php with a div of class alert and alert-danger has a double curly bracket $slot. You may pass content to the slot by injecting content into the component.
So in your blade file, you can have x-alert as a tag, open and closing tag, and then anything in that tag will be injected into the slot. 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. So if we have span class of alert-title, we can have double brackets, dollar sign title
and dollar sign slot, you may define the content of the named slot using the x-slot tag. Any content not within an explicit x-slot tag will pass the component in the dollar sign slot variable. So in your component x-alert, you can have x-slot colon title, and passing in that title as a string.
You may invoke a slot's isEmpty method to determine if the slot contains content. So span classAlertTitle $title if slot is empty, this is default content if the slot is empty, at else slot. Additionally, the hasActualContent method may be used to determine if the slot contains any actual content that is not in HTML comment. If $slot has actual content, the scope has non-comment content.
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 format alert method defined on its component class.
So x-alert, x-slot, colon title, $ component method, format alert, server error, slot attributes. By blade components, you may assign additional attributes to slots such as CSS class names. So x-slot, heading, classes, font-bold. To interact with slot attributes, you may access the attributes properties of the slots variables.
For more information on how to interact with attributes, please consult the documentation on component attributes. So $attributes arrow class border, $heading attributes class text large, for example. Inline component views. For very small components, it may feel cumbersome to manage both the component class and the components view template. For this reason, you may return the components markup directly from the render method.
So public function render string return blade. Generating inline view components. create a component that renders an inline view, you may use the inline option when executing the make component command. PHP artisan make component alert dash dash inline. Dynamic components. Sometimes you may need to render a component, but not know which component should be rendered until runtime. In this situation, you may use Laravel's built-in dynamic dash component component
to render the component based on a runtime value or variable. For example, dollar sign component name equals secondary dash button, x dash dynamic dash component with colon component equals dollar sign component name. 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 with within the app view components directory and resources slash view slash 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 Laravel knows where to find the component. You should typically register your components
in the boot method of your package's service provider. Once your component has been registered, They may be rendered using its tag alias, x-package-alert. Auto-loading package components. Alternatively, you may use the component namespace method to auto-load component classes by convention. For example, a nightshade package might have calendar and color picker components that
reside within the package views components namespace. This will allow the usage of package components by their vendor namespace using the package-name colon colon syntax, x dash night shape, colon colon calendar, x dash night shape, colon colon color pitter. Blade will automatically detect class that's linked to this component by Pascal casing the component name. Subdirectories are also supported using dot notation.
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 slash alert dot blade dot
PHP, you may simply render it like so x dash alert, you may also use the dot character to indicate if a component is nested deeper inside the components directory. For example, assuming the component is defined at resources views components slash inputs slash button dot blade.php, you may render it like so, x dash inputs dot button. 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, accordion dot blade dot php, accordion slash item dot blade.php. The directory structure allows you to render the accordion component and its item like x-accordion and nested in x-accordion.item. 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 like the other accordion-related templates. Thankfully, Blade allows you to place an index.blade.php file within a components template directory. When an index.blade.php template exists for the component, it will be rendered as the root node of the component. So we can continue to use these same blade syntax in the given example.
However, we will adjust our directory structure like so. So accordion slash index.blade.php, accordion slash item.data properties and attributes. Since anonymous components do not have an associated class, you may wonder how you may differing differentiate which data should be passed the component as variables and which attributes should be passed in the components attribute bag. You may specify which attributes should be considered data variables using the
at props directive at the top of your components blades template. All other attributes on the component will be available via the components attribute bag. If you wish to give a data variable a default name, you may specify the variable's name as the array key and the default value as the array value. So at props, an array of type is info and then message. Given the component definition above, we may render the component like so, x dash alert type equals error colon message,
That's a prop as message. Sometimes you may want to access data from a parent component inside a child component. In these cases, you may use the at aware directive. For example, imagine we are building a complex menu component consisting of a parent x-menu and a child x-menu.item. X menu color purple, x menu.item, a bunch of those. The x-menu component may have an implementation like the following.
So in the XMenu component, at props, color is gray with the ul of attributes merge with some classes and then a slot. Because the color prop was only passed into the parent XMenu, it won't be available inside XMenu.item. However, if we use the aware directive, at aware, we can make it available using the XMenu item as well. So at aware, color is gray.
Warning, the aware directive cannot access parent data that is not explicitly passed to the parent component via HTML attributes. Default props, at props values that are not explicitly passed to the parent component can only be accessed by the at aware directive. 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 anonymous component path 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.
When component paths are registered within a specified prefix as in the example above, they may be rendered in the 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, x-panel. Prefix namespaces may be provided as the second argument to the anonymous component path method.
So blade colon colon anonymous component path and passing in the component there. 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. X dash dashboard colon colon panel. Building layouts. 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 and then use it throughout our application. Defining the layout component. For example, imagine we are building a to-do list application. We might define a layout component that looks like the following. An HTML head with a title and then body of to-dos and we'll pass in a slot. Applying the layout component. Once
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. So tasks.blade.php has an 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 slots syntax discussed in the component documentation. So x-slot colon title. Now that we have defined our layout and task list views, we just need to return the task view from a route. So route colon colon get tasks and return the view tasks and passing the task parameter is task
colon colon all from the model. Layouts using template inheritance, 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. 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.
So head, title, app, name, section, at section, sidebar, and then at yield content. As you can see, this file contains typical HTML markup. However, take note of the at section and at yield directives. The at section directive, as the name implies, defines a section of content, while the at 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. Extending the layout.
When defining a child view, use the at extends blade directive to specify which layout the child view should inherit. Views which extend a blade layout may inject content into the layout sections using at section directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using at yield.
So, at section title, page title, at section sidebar, at section content. In this example, the sidebar section is utilizing the at at parent directive to append rather than overriding content to the layout sidebar. The at parent directive will be replaced by the content of the layout when the view is rendered.
Contrary to the previous example, the sidebar section ends with at end section instead of at show. The at end section directive will only define a section while at show will define and immediately yield the section. The at yield directive also accepts a default value as its second parameter. This value will be rendered if the section being yielded is undefined.
at yield content default content. Form. 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 token protection middleware can validate the request. You may use the at CSRF blade directive to generate the token field. So form method post, action is profile, CSRF as an at directive. Method field. Since HTML forms can't make put patch or delete requests, you will need to add a hidden underscore
method field to spoof these HTTP verbs. The at method blade directive can create this field for you. So at method put. Validation errors. The at error directive may also be used to quickly check if validation error messages exist for a given attribute. Within an at error directive, you may echo the dollar sign message variable to display the error message. So create.blade.php
key is invalid and then you have at error title with dollar sign message. Since the error directive compiles to an if statement, you may use the at else directive to render content when there is not an error for an attribute. You may pass the name of a specific error bag as the second parameter to the error directive to retrieve validation. Error messages
on pages containing multiple forms. So label of email address input is invalid at an error and then error email login. And you can display the message as a prop. 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. So at push scripts, then you can have the script source there. If you
like to at push content. If a given Boolean expression evaluates to true, you may use the push if directive. You may push to a stack as many times as needed. To render the complex stack contents, pass the name of the stack to the at stack directive. So in the head of the contents, you can pass at stack scripts. If you would like to prepend content onto the beginning of a stack, you should use the at prepend directive.
Service injection. The at inject directive may be used to retrieve a service from the Laravel service container. This first argument passed to at inject is the name of the variable the service will be placed into, while the second argument is the class or interface name of the service you wish to resolve. So at inject metrics app slash services slash metric service. Rendering inline blade templates. Sometimes you may need to transform a raw
blade template string into valid HTML. You may accomplish this using the render method provided by the blade facade. The render method accepts the blade template string and an optional array of data to provide to the template. Laravel renders inline blade templates by writing them to the storage framework views directory. If you would like Laravel to remove these temporary files after rendering the blade template, you may provide the delete cached view argument
to the method. Rendering blade fragments. When using front end frameworks such as Turbo and HTMX, you may occasionally need to only return a portion of a blade template within your HTTP response. Blade fragments allow you to do just that. To get started, place a portion of your blade template within at fragment and at end fragment directives. Then when rendering the view that utilizes this template, you may invoke the fragment method to specify that only the
specified fragment should be included in the outgoing HTTP response. So return view dashboard, passing in the props of users is called .users, fragment user list. The fragment if method allows you to conditionally return a fragment of a view based on a given condition. Otherwise, the entire view will be returned. So fragment if request has header, then you can pass in that user list. The fragments and fragments if methods allow you to return multiple view fragments in the
response. The fragments will be concatenated together. The fragments will be concatenated together. View dashboard users fragments, view dashboard users users fragments if $request has header. Extending blade. Blade allows you to define your own custom directives using the directive method. When the blade compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains. The following example creates an
atDateTimeVar directive, which formats a given $Var, which should be an instance of date time. As you can see, we will chain the format method onto whatever expression is passed into the directive. So in this example, the final PHP generated by this directive will be phpEcho $Var format. After updating the logic of a blade directive, you will need to delete all the cached
blade views. The cached blade views may be removed using the view colon clear artisan command. Custom echo handlers. If you attempt to echo an object using blade, the object's $__2string method will be invoked. The $__2string method is one of PHP's built-in magic methods. However, sometimes you may not have control over the two-string method of a given class, such as when the class that you are interacting with belongs to a third party. In these cases, blade allows you to
register a custom echo handler for that particular type of object. To accomplish this, you should invoke Blade's stringable method. The stringable method accepts a closure. This closure should type in the type of object that is responsible for rendering. Typically, the stringable method should be invoked within the boot method of your application's app service provider class. Once your custom echo handler has been defined, you may simply echo the object in your Blade
template. So cost is dollar score, money. Custom if statements. Providing a custom directive is sometimes more complex than necessary when defining simple custom conditional statements. For that reason, Blade provides a blade, colon, colon, if method, which allows you to quickly define custom conditional directives using closures. For example, let's define a custom conditional that checks the configured default disk for the application. We may do this in the
the boot method of our app service provider. Once the custom conditional has been defined, you can use it within your templates. So at disk local or at else disk S3. Asset bundling, VIT. Actually, before I start that, I'm going to take a quick break.
I'm sorry.
so
Thank you.
so
Thank you.
so
Thank you.
I'm going to go ahead and put it in the middle of the room.
Thank you.
so
Thank you.
I'm going to make a little bit more of a little bit more.
Thank you.
All right, let's continue diving deeper. Those who are still still joining, we are close to about close close to a third of the way through a little bit a little bit over a third, not not half, but not not a quarter. We're diving deeper and we're going into
mail. So, introduction. Sending email doesn't have to be complicated. Laravel provides a clean, simple email API powered by the popular Symfony mailer component. Laravel and Symfony mailer provide drivers for sending email via SMTP, Mailgun, Postmark, Resend, Amazon SES, and Send
mail allowing you to quickly get started sending mail through a local or cloud-based service of your choice configuration laravel's email services may be configured via your application's config mail.php configuration file each mailer configured within this file may have its own unique configuration and even its own unique transport allowing your application to use different email services to send certain email messages for example your application might use postmark
to send transactional emails while using Amazon SES to send bulk emails. Within your mail configuration file, you will find a mailers configuration array. This array contains a sample configuration entry for each of the major mail drivers and transports supported by Laravel while the default configuration value determines which mailer will be used by default when your application needs to send an email message. If you would like to display the integer
value that was passed to the trans choice function, you may use the build... Oops, that was... One minute I already read. The API-based drivers for driver transport prerequisites. The API-based drivers such as Mailgun, Postmark, Resend, and MailerSend are often simpler and faster than sending mail via SMTP servers.
Whenever possible, we recommend that you use one of these drivers, Mailgun driver. To use the Mailgun driver, install Symfony's Mailgun mailer transport via Composer. So Composer require Symfony Mailgun mailer Symfony HTTP client. Next, set the default option in your application's config mail.php configuration file to mailgun and add the following configuration array to your array of mailers. So mailgun transport client timeout. After configuring your application's default
mailer, add the following options to your config services.php configuration file. Mailgun, domain, secret, endpoint, and scheme. And if you are not using the United States mailgun region, you may define your region's endpoint in the services configuration file. Postmark driver. To use the postmark driver, install Symfony's postmark mailer transport via composer. Next, set the default option in your application's mail.php configuration file to postmark.
And after configuring your application's default mailer, ensure that your config services configuration file contains the following options. So postmark token. If you would like to specify the postmark message stream, that should be used by a given mailer, you may add the message stream ID configuration option to the mailers configuration array. This configuration array can be found in your application's config mail.php configuration file.
Postmark Transport Message Stream ID. This way you are able to set up multiple most Postmark mailers with different message streams. Resend driver. To use the Resend driver, install Resend's PHP SDK via Composer. Next, set the default option in your application's configuration file to Resend, and after configuring your application's default mailer, ensure that your config services.php configuration file contains the following options. Resend key.
SES driver. To use the Amazon SES driver, you must first install the Amazon AWS SDK for PHP. You may install this library via the Composer Package Manager. Composer require AWS SDK PHP. Next, set the default option in your config mailer PHP file to SES and verify that your config services PHP configuration file contains the following options. SES key secret region.
To utilize AWS temporary credentials via session token, you may add a token key to your application's SES configuration. To interact with SES's subscription management features, you may return the x-SESListManagement options header in the array returned by the headers method of a mail message. So public function headers return new headers.
If you would like to define additional options that Laravel should pass to the AWS SDK send email method when sending an email, you may define an options array within your SES configuration. Mailer send driver. Mailer send, a transactional email and SMS service, maintains their own API-based mail driver for Laravel. The package containing the driver may be installed via the composer package manager, composer required, mail or send, Laravel driver.
Once the package is installed, add the mailersend API key environment variable to your applications.env file. In addition, the mail mailer environment variable should be defined as mailersend. Finally add mailersend to the mailers array in your applications mail.php configuration file. To learn more about mailersend, including how to use hosted templates, consult the mailersend driver documentation. Failover configuration.
and external service you have configured to send your application's mail may be down. In these cases, it can be useful to determine one or more backup mail delivery configurations that will be used in case your primary delivery driver is down. To accomplish this, you should define a mailer within your application's mail configuration file that uses a failover transport. The configuration array for your application's failover mailers should contain an array of mailers that reference the order in which configured mailers should be chosen for delivery.
So mailers, failover, transport, and mailers. Once your failover mailer has been defined, you should set this mailer as the default mailer used by your application by specifying its name as the mailer as the value of the default configuration key within your application's mail configuration file. So default, env, mail, mailer, failover. Round robin configuration. The round robin transport allows you to distribute your mailing workload across multiple servers. To
To get started, to find a mailer within your application's mailed configuration file that uses the round-robin transport. The configuration array for your application's round-robin mailer should contain an array of mailers that reference which configured mailers should be used for delivery. Once your round-robin mailer has been defined, you should set this mailer as the default
mailer used by your application by specifying its name as the value of the default configuration key within your application's mail configuration file. The round robin transport selects a random mailer from the list of configured mailers and then switches to the next available mailer for each subsequent email. In contrast to failover transport, which helps to achieve high availability, the round robin transport provides load balancing.
When building Laravel applications, each type of email sent by your application is represented as a mailable class. These classes are stored in the app slash mail directory. Don't worry if you don't see this directory in an application since it will be generated for you when you create your first mailable class using the make mail artisan command. 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, the content, the 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 that will be used to generate the message content. Configuring the sender. 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 mail on your messages envelope. And if you would like, you may also specify a reply to address. So 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
no other from address is specified within the mailable class. In addition, you may define a global reply to address within your mail.php configuration file. Configuring the view within a mailable class's content method, you may define the view or which template should be confused when rendering the email's contents. Since each email typically uses a blade template to render its contents, you have the full power and convenience of
the blade template engine when building your HTML's email. Note, you may wish to create a resources views email directory to house all of your email templates. However, you are free to place them wherever you wish within your resources views directory. Plain text emails. If you would like to define a plain text version of your email, you may specify the plain text template when creating the messages context, content definition. Like the view parameter, the text parameter should be
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. So return new content, view, and text. For clarity, the HTML parameter may be used as an alias of the view parameter. Return new content, HTML, text. View data via public properties. Typically, you'll 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 classes constructor and set that data to public properties defined on the class. 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. So having the public order on the construct can add the order price to the template. Via the width 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 definitions width parameter. Typically, you will still pass data via the mailable class as constructor. However, you should set the data to protected or private property so
the data is not automatically made available to the template. 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... So you may access it like you would access any other data in your blade template. So price order price attachments to add attachments to any email you will add attachments to the array
returned by the messages attachment method first you may add an attachment by providing a file path to the from path method provided by the attachment class when attaching files to a message you may also specify the display name and or mine type for the attachment using the as and with mine method attaching files from disks if you have stored a file on one of your file system disks you may
may attach it to the email using the from storage attachment method. Of course, you may also specify the attachments name and MIME type. The from storage disk method may be used if you need to specify a storage disk other than your default disk. Raw data attachments. The from data attachment method may be used to attach a raw string of bytes as an attachment.
For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The fromData method accepts a closure which resolves the raw data bytes as well as the name that the attachment should be assigned. So attachment fromData with MIME application types. Inline attachments. Embedding inline attachments into your emails is typically cumbersome. However, Laravel provides a convenient way to attach images to your emails.
To embed an inline image, use the embed method on the $message variable within your email template. Laravel automatically makes the $message variable available to all of your email templates, so you don't need to worry about passing it in manually. So here's an image, image source, $message, embed path to image. Warning, the $message variable is not available in plain text message templates, since plain text messages do not utilize inline attachments. Embedding raw data attachments.
If you already have a raw image data string you wish to embed into an email template, you may call the embedData method on the message variable. When calling the embedData method, you will need to provide a file name that should be assigned to the embedded image. Attachment objects. While attaching files to messages via simple string pass is often sufficient, in many cases the attachable entities within your application are presented by classes. For example, if your application is attaching a photo to a message, your application may also have a photo model that
that represents that photo. When that is the case, wouldn't it be convenient to simply pass the photo model to the attach method? Attachable objects allow you to do just that. To get started, implement the contract's mail attachable interface on the object that will be attachable to messages. The interface dictates that your class defines a two-mail attachment method that returns a mail attachment instance.
Once you have defined your attachable object, you may return an instance of that object from the attachments method when building an email message. Of course, attachment data may be stored on a remote file storage service such as Amazon S3. So, Laravel also allows you to generate attachment instances from data that is stored on one of your application's file system disks. In addition, you may create attachment instances via data that you have in memory.
To accomplish this, provide a closure to the from data method. The closure should return the raw data that represents the attachment. Laravel also provides additional methods that you may use to customize your attachments. For example, you may use the as and with mime methods to customize the file's name and mime type. Headers. Sometimes you may need to attach additional headers to the outgoing message. For instance, you may need to set a custom message ID or other arbitrary text
headers. To accomplish this, define a headers method on your mailable. The headers method should return and illuminate mail mailables headers instance. This class accepts message ID, references, and text parameters. Of course, you may provide only the parameters you need for your particular message. 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. If your application is using the Mailgun driver, you may consult Mailgun's documentation for more information on tags and metadata. Likewise, the Postmark documentation may also be consulted for more information on their support for tags and metadata. If your application is using Amazon SES to send emails, you should use the metadata method to attach SES tags to the message.
Customizing the Symphony message. Laravel's mail capabilities are powered by Symphony Mailer. Laravel allows you to register custom callbacks that will be invoked with the Symphony 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. Markdown mailables.
Markdown mailable messages allow you to take advantage of the pre-built templates and components of 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, generating Markdown mailables. To generate a mailable with the corresponding Markdown template, you may use the dash dash markdown option of the make mail artisan command. Then, when configuring the mailable content definition within its content method, use
the markdown parameter instead of the view parameter. So return new content, markdown mail.orders.shit. 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. For example, xmail message, xmail button, xmail message.
Note, do not use excess indentation when writing markdown emails. Per markdown standards, markdown parsers will render indented content as code blocks. Button component. The button component renders a centered button link. The component accepts two arguments, a URL and an optional color. Supported colors are primary, success, and error. You may add as many button components to a message as you wish. 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. 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. 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 lairvelt-mail
asset tags. Vendor publish tag equals lairvelt-mail. This command will publish the markdown mail components to the resources views vendors mail directory. The mail directory will contain an HTML and a test directory, each containing their respective representations of every available component. You are free to customize these components however you like.
the CSS. After exporting the components, the 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 representation 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. Sending mail. To send a message, use the to method on the mail facade. The to method accepts an email address, a user instance, or a collection
of users. If you pass an object or a collection of objects, the mailable mailer will automatically use their email and name properties when determining the email's recipients. So make sure these attributes are available on your objects. Once you have specified your recipients, you may pass an instance of your mailable class to the send method. You are not limited to just specifying the two recipients when sending a message. You are free to set two CC and
BCC recipients by chaining their respective methods together. Looping over recipients. Occasionally we need to send a mailable to a list of recipients by iterating over an array of recipients or email addresses. However, since the two method appends email addresses to the mailable's list of recipients, each iteration through the loop will send another email to every recipient. Therefore you should always recreate the mailable instance for each recipient.
each as recipient, sending mail via a specific mailer. By default, Laravel will send email using the mailer configured as the default mailer in your application's mail configuration file. However, you may use the mailer method to send a message using a specific mailer configuration. Queuing mail. Since sending email messages can negatively impact the response time of your
application, many developers choose to queue email messages for background sending. Laravel makes this easy using its built-in unified queue API. To queue a mail message, use the queue method on the mail facade after specifying the message's recipients. So mail to, and then you can just add queue. This method will automatically take care of pushing a job onto the queue so the message is sent in the background. You will need to configure your queues before using this feature.
Delayed message queuing. If you wish to delay the delivery of a queued email message, you may use the later method. As its first argument, the later method accepts a date time instance indicating when the message should be sent. Mail to request user later. Pushing to specific queues. Since all mailable classes generated using the make mail command to make use of the queueable trait,
you may call the onqueue and onconnection methods on any mailable class instance, allowing you to specify the connection and queue name for the message. Queuing by default. If you have mailable classes that you want to always be queued, you may implement the should queue contract on the class. Now, even if you call the send message, send method when mailing, the mailable will still be queued since it implements the contract. When queued mailables are dispatched within database transactions, they may be processed by the queue before
the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your mailable depends on these models, unexpected errors can occur when the job that sends the queued mailable is processed. If your queue's connections after commit configuration option is set to false, you may still indicate that a particular
queued mailable should be dispatched after all open database transactions have been committed by calling the after commit method when sending the mail message. Alternatively, you may call the after commit method from your mailable's constructor. Rendering mailables. Sometimes you may wish to capture the HTML content of a mailable without sending it. To accomplish this, you may call the render method of the mailable. This method will return the evaluated HTML
content of the mailable as a string. Previewing mailables in the browser. When designing a mailable's template, it is convenient to quickly preview the rendered mailable in your browser, like a typical blade template. For this reason, Laravel allows you to return any mailable directly from the route closure or controller. When a mailable is returned, it will be rendered and displayed in the browser, allowing you to quickly preview its design without needing to send it to an actual email address. So route dash route git mailable, then you can return a new app mail and
voice page mailable. Localizing mailables. Laravel allows you to send mailables in a locale other than the request's current locale and will even remember this locale if the mail is queued. To accomplish this, the mail facade offers a locale method to set the desired language. The application will change into this locale when the mailables template is being evaluated and then and then revert back to the previous locale when evaluation is complete. So mail to request user locale, send new order shipped.
User preferred locale. Sometimes applications store each other's preferred locale. By implementing the has locale preference contract on one or more of your models, you may instruct Laravel to use this stored locale when sending mail. Once you have implemented the interface, Laravel will automatically use the preferred locale when sending messages and notifications to the model. Therefore, there's no need to call the locale method using this interface. Testing. Testing mailable content.
Laravel provides a variety of methods for inspecting your mailable structure. In addition, Laravel provides several convenient methods for testing that your mailable content contains the content that you expect. These methods are assert C in HTML, assert don't C in HTML, Assert see in order in HTML, assert see in text, assert don't see in text, assert see in order in text, assert has attachment, assert has attached data, assert has attachment from storage, and
assert has attachment from storage disk. As you might expect, the HTML assertions assert that the HTML version of your mailable contains a given string, while the text assertions assert that the plain text version of your mailable contains a given string. Testing mailable sending. We suggest testing the content of your mailables separately from your tests that assert that a given mailable was sent to a specific user.
Typically the content of mailables is not relevant to the code you are testing and it is sufficient to simply assert that Laravel was instructed to send a given mailable. You may use the mail facades fake method to prevent mail from being sent. After calling the mail facades fake method, you may then assert that mailables were instructed to be sent to users and even inspect the data the mailables receive. If you are queuing mailables for delivery in the background, you should use the assert
queued method instead of assert sent. You may pass a closure to the assert sent, assert not sent, assert queued, or assert not queued methods in order to assert that a mailable was sent that passes a given truth test. If at least one mailable was sent that passes the given truth test, then the assertion will be successful. When calling the mail facades assertion methods, the mailable instance accepted by the provided closure exposes helpful methods for examining the mailable.
The mailable instance also includes several helpful methods for examining the attachments on a mailable. So return mail as attachment, attachment from path, as attachment, attachment from storage or from data. You may have noticed that there are two methods for asserting the mail was not sent, assert not sent and assert not queued. may wish to assert that no mail was sent or queued. To accomplish this, you may use the assert nothing outgoing and assert not outgoing methods. Mail and local development. When developing
an application that sends email, you probably don't want to actually send email to live email addresses. Laravel provides several ways to disable the actual sending of emails during development. First, log driver. Instead of sending your emails, the log mail driver will write all email messages to your log files for inspection. Typically, this driver would only be used during local development. For more information on configuring your application per environment, check out the configuration documentation.
Hilo Mailtrap Mail Pit. Alternatively, you may use a service like Hilo or Mailtrap and the SMTP driver to send your email messages to a dummy mailbox where you may view them in a true email client. This approach has the benefit of allowing you to actually inspect the final emails in Mail Traps message viewer. If you are using Laravel sale, you may preview your messages using MailPit. When sale is running, you may access the MailPit interface at localhost 8025.
Using a global to address. Finally, you may specify a global to address by invoking the always to method offered by the mail facade. Typically, this method should be called from the boot method of one of your application service providers. So if this app is environment local, always to specific email address. Events. Laravel dispatches to events while sending mail messages. The message sending event is dispatched prior to a message being sent, while the message sent
event is dispatched after a message has been sent. Remember, these events are dispatched when the mail is being sent, not when it is queued. You may create event listeners for these events within your application. Custom transports. Laravel includes a variety of mail transports. However, However you may wish to write your own transports to deliver email via other services that Laravel does not support out of the box. To get started, define a class that extends the abstract transport class, then implement
the do send and to string methods on your transport. Once you've defined your custom transport, you may register it via the extend method provided by the mail facade. Typically, this should be done within the boot method of your application's app service provider, service provider. A config argument will be passed to the closure provided to the extend method. This argument will contain the configuration array defined for the mailer in the application's
mail.php configuration file. Once your custom transport has been defined and registered, you may create a mailer definition within your application's mail.php configuration that utilizes the new transport. So MailChimp, transport, you can have MailChimp, additional Symfody transports. Laravel includes support for some existing Symfony-maintained mail transports like Mailgun and Postmark. However, you may wish to extend Laravel with support for additional Symfony-maintained
transports. You can do so by requiring the necessary Symfony mailer via Composer and entering and registering the transport with Laravel. For example, you may install and register the Brevo, formerly Sendinblue Symfony mailer. Once the Brevo mailer package has been installed, you may add an entry for your Brevo API credentials to your application's services configuration file. Next, you may use the mail facades extend method to register the transport with Laravel. Typically, this should be done within the boot
method of the service provider. Once your transport has been registered, you may create a mailable mailer definition within your application's config mail.php configuration file that utilizes the new transport. Next up notifications.
Thank you.
So we're still in digging deeper notifications.
Introduction. In addition to support for sending email, Laravel provides support for sending notifications across a variety of delivery channels, including email, SMS, via Vonage, formerly known as Nexmo, and Slack. In addition, a variety of community-built notification channels have been created to send notifications over dozens of different channels. Notifications may also be stored in a database so that they may be displayed in your web interface.
Typically, notifications should be short, informational messages that notify users of something that occurred in your application. For example, if you are writing a billing application, you might send an invoice paid notification to your users via the email and SMS channels. In Laravel, each notification is represented by a single class that is typically stored in the app notifications directory. Don't worry, if you don't see this directory in your application, it will be created for you when
you run the make notification artisan command. This command will place a fresh notification class in your app notifications directory. Each notification class contains a via method and a variable number of message building methods such as a to mail or to database that convert the notification to a message tailor for that particular channel. Sending notifications, Using the notifiable trait, notifications may be sent in two ways, using the notify method of the notifiable trait or using the notification facade. The notifiable trait is included on your
application's app slash model slash user model by default. The notify method that is provided by this trait expects to receive a notification instance. So class user extends use notifiable. Note, remember, you may use the notifiable trait on any of your models. You are not limited to only including it on your user model. Alternatively, you may send notifications via the notification
facade. This approach is useful when you need to send a notification to multiple notification notifiable entities such as a collection of users. To send notifications using the facade, pass all the notifiable entities and notification instance to the send method. You can also send notifications immediately using the send now method. This method will send the notification immediately even if the notification implements the should queue interface. Specify and delivering channels. Every notification class has a via method that determines on which channels
a notification will be delivered. Notifications may be sent on the email, database, broadcasts, Vonage, and Slack channels. Note, if you would like to use other delivery channels such as Telegram or Pusher, check out the community-driven Laravel notification channel's website. The via method receives a notifiable instance which will be an instance of the class to which the notification is being sent. You may use Notifiable to determine which channels the notification should be delivered on. So Object Notifiable, Return Notifiable, Preferr, SMS,
could be Vonage, Mail, or Database. Queuing Notifications. Before queuing notifications, you should configure your queue and start a worker. Sending notifications can take time, especially if the channel needs to make an external API call to deliver the notification. To speed up your application's response time, let your notification be queued by adding the Should Queue interface and queuable trait to your class. The interface and trait are already imported for all notifications generated using the Make Notification command, so you may immediately
add them to your notification class. Once the Should Queue interface has been added to your notification, you may send the notification like normal. Laravel will detect the Should Queue interface on the class and automatically queue the delivery of the notification. When queuing notifications, a queue job will be created for each participant or each recipient and channel combination. For example, six jobs will be dispatched to the queue if your notification
has three recipients and two channels. Delaying notifications. If you would like to delay the delivery of the notification, you may chain the delay method onto your notification institution. You may pass an array to the delay method to specify the delay amount for specific channels. Alternatively, you may define a with delay method on the notification class itself. The with delay method should return an array of channel names and delay values. Customizing the notification queue connection.
By default, queued notifications will be queued using your application's default queue connection. If you would like to specify a different connection that should be used for a particular notification, you may call the onConnection method from your notifications constructor. Or if you would like to specify a specific queue connection that should be used for each notification channel supported by the notification, you may define a viaConnections method on your notification.
This method should return an array of channel name or queue connection name pairs. If you would like to specify a specific queue that should be used for each notification channel supported by the notification, you may define a via queues method on your notification. This method should return an array of channel name queue pairs. Queue notifications may
define middleware just like queue jobs. To get started, define a middleware method on your notification class. The middleware method will receive notifiable and channel variables which allow you to customize the return middleware based on the notifications destination. So return match channel, email, new rate limited, slack, new rate limited.
Cue notifications and database transactions. When queued notifications are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you made to your models,
you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your notification depends on these models, unexpected errors can occur when the job that sends the queued notification is processed. If your queued notification's after commit configuration option is set to false, you may still indicate that a particular queued notification should be dispatched after all
open database transactions have been committed by calling the after commit method when sending the notification. User notify. Alternatively, you may call the after commit method from your notifications constructor. Note, to learn more about working around these issues, please review the documentation regarding queue jobs and database transactions. Determining if a queue notification should be sent after a queue notification has been dispatched for the queue by background processing, it will typically be accepted by a queue worker and sent to its intended
recipient. However, if you would like to make the final determination on whether the queue notification should be sent after it is being processed by a queue worker, you may define a should send method on the notification class. If this method returns false, the notification will not be sent. On-demand notifications. Sometimes you may need to send a notification to someone who is not stored as a user of your application. Using the notification facades route method, you may specify ad hoc notification information before sending the notification. If you would
like to provide the recipient's name when sending an on-demand notification to the mail route, you may provide an array that contains the email addresses as the key and the name as the value of the first element in the array. Using the routes method, you may provide ad hoc routing information for multiple notification channels at once. So notification routes, mail to array, bondage to number. Mail notifications, formatting mail messages. If a notification supports being
sent as an email, you should define a to mail method on the notification class. This method will receive a notifiable entity and should return and illuminate notifications messages mail message instance. The mail message class contains a few simple methods to help you build transactional email messages. Mail messages may contain lines of text as well as a call to action.
Let's take a look at an example to mail method. So return new mail message, greeting, line, line if, line or action, and then line. Note, we are using this invoice ID in our to mail method. So URL, URL slash invoice, this invoice ID. You may pass any data your notification needs to generate its message into the notifications constructor. In this example, we register a
greeting, a line of text, a call to action, and then another line of text. These methods provided by the mail message object make it simple and fast to format small transactional emails. The mail channel will then translate the message components into a beautiful, responsive HTML email template with a plain text counterpart. Here's an example of an email generated by
the mail channel. It's a picture. When sending mail notifications, be sure to set the name configuration object in your app.php configuration file. This value will be used in the header and footer of your mail notification messages. Error messages. Some notifications inform users of errors such as a failed invoice payment. You may indicate that a mail message is regarding
an error by calling the error method when building your message. When using the error method on a mail message, the call to action button will be red instead of black. Other mail notification formatting options. Instead of defining the lines of text in the notification class, you may use the view method to specify a custom template that should be used
to render the notification email. You may specify a plain text view for the mail message by passing the view name as the second element of an array that is given to the view method. So return new mail message view, mail.invoice.paid, invoice, and then data, this invoice. Or if your message only has a plain text view, you may utilize the text method. Customizing the sender. By default,
the email's sender from address is defined in the mail.php configuration file. However, you may specify the from address for a specific notification using the from method. So return new mail message in this mail notification from so-and-so. Customizing the recipient. When sending notifications via the mail channel, the notification system will automatically look for an email property on your notifiable entity. You may customize which email address is used to deliver
the notification by defining a route notification for email method on the notifiable entity. Customizing the subject. By default, the email subject is the class name of the notification formatted to title case. So if your notification class is named invoice paid, the email subject will be invoice space paid. If you would like to specify a different subject for the message, you may call the subject method when building your message.
Customizing the mailer. By default, the email notification will be sent using the default mailer defined in the mail.php configuration file. However, you may specify a different mailer at runtime by calling the mailer method when building your message. Customizing the templates. You can modify the HTML plain and plain text template used by mail notification by publishing the notification package's resources.
After running this command, the mail notification templates will be located in Views Render Notifications directory. php artisan vendor publish dash dash tag equals Laravel dash notifications. Attachments To add attachments to an email notification, use the attach method while building your message. The attach method accepts the absolute path to the file as its first argument. Note, the attach method offered by notification mail messages also accepts attachable objects.
Please consult the comprehensive attachable object documentation to learn more. When attaching files to a message, you may also specify the display name and or mime type by passing an array as the second argument to the attach message. Unlike attaching files and mailable objects, you may not attach a file directly from a storage disk using attach from storage.
You would rather use the attach method with an absolute path to the file on the storage disk. Alternatively, you could return a mailable from the to mail method. When necessary, multiple files may be attached to a message using the attach many method. Raw data attachments. The attach data method may be used to attach a raw string of bytes as an attachment. When calling the attachData method, you should provide the file name that should be assigned
to the attachment. Adding tags and metadata. Some third-party email providers such as Mailgun and PostSpark support message tags and metadata, which may be used to group and track emails sent by your application. You may add tags and metadata to an email message via the tag and metadata methods.
If your application is using the Mailgun driver, you may consult Mailgun's documentation for more information on tags and metadata. Likewise, the Postmark documentation may also be consulted for more information on their support for tags and metadata. If your application is using Amazon SES to send emails, you should use the metadata method to attach SES tags to the message. Customizing the Symfony message. With Symphony Message method of the MailMessage class allows you to register a closure which
will be invoked with the Symphony Message instance before sending the message. This gives you an opportunity to deeply customize the message before it is delivered. Using Mailables If needed, you may return a full mailable object from your notifications to mail method when returning a mailable instead of a mail message. You will need to specify the message recipient using the mailable objects to method. Mailable is an on-demand notification.
If you are sending an on-demand notification, the notifiable instance given to the to mail method will be an instance of notification slash anonymous not notifiable, which offers a route notification for method that may be used to retrieve the email address the on-demand notification should be sent to. Revenue mail notifications. When designing a mail notification template, it is convenient
to quickly preview the rendered mail message in your browser like a typical blade template. For this reason, LayerVille allows you to return any mail message generated by mail notification directly from a route closure or controller. When a mail message is returned, it will be rendered and displayed in the browser, allowing you to quickly preview its design without needing to send it to an actual email address. Markdown mail notifications. Markdown mail notifications allow you to take advantage of the pre-built templates of mail notifications
while giving you more freedom to write longer, customized messages since the messages are written in Markdown. Laravel is able to render beautiful, responsible HTML templates for the messages while also automatically generating a plain text counterpart. So generating the message. To generate a notification with the corresponding Markdown template, you may use the dash dash markdown option of the make notification artisan command. Unlike or like all other mail notifications,
notifications that use markdown templates should have defined a to mail method on their notification class. However, instead of using the line and action methods to construct a notification, use the markdown method to specify the name of the markdown template that should be used. An array of data you wish to make available to the template may be passed as the method's second argument. Writing the message. Markdown mail notifications use a combination of blade components and markdown syntax, which allows you to easily construct notifications while
leveraging Laravel's pre-crafted notification components. This is really similar to what we read for the mail. We have a button component. The color button renders a centered button link. The component accepts two arguments, a URL and an optional color. Supported colors are primary green and red. You may add as many button components to a notification as you wish. Panel component. The panel component renders the given block of text in a panel that has slightly
different background color than the rest of the notification. This allows you to draw attention to a given block of text. 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. Customizing the components, you may export all of the Markdown notification components to your own application for customization.
To export the components, use the vendor dash vendor colon publish artisan command to publish the Laravel mail asset tags. So artisan vendor publish dash dash tag equals Laravel dash mail. This command will publish the Markdown mail components in the resources views vendors mail directory. The mail directory will contain an HTML and a text directory, each containing their respective representations of every available component. You are free to customize these
components however you like. Customizing the CSS. After exporting the components, the resources views vendors mail HTML themes directory will contain default.css file. You may customize the CSS in this file and your styles will automatically be inline within the HTML representations of your markdown notifications. 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 the mail configuration files to match the name of your new theme. To customize the theme for an individual notification, you may call the theme method while building the notification's mail message. The theme method accepts the name of the theme that should be used when sending the notification. So return new mail message, theme, subject, markdown. Database notifications. Prerequisites.
The database notification channel stores the notification information in a database table. This table will contain information such as the notification type as well as a JSON data structure that describes the notification. You can query the table to display the notifications in your application's user interface, but before you can do that, you will need to create a database table to hold your notifications. You may use the make notifications table command to generate
a migration with the proper table schema. Note, if your notifiable models are using UUID or ULID primary keys, you should replace the morphs method with UUID morphs or ULID morphs in the notification table migration. Formatting database migrations. If a notification supports being stored or formatting database notifications. If a notification supports being stored in a database table, you should define a to database or to array method on the notification class.
This method will receive a notifiable entity and should retain return a plain PHP array. The returned array will be encoded as JSON and stored in the data column of your notifications table. Let's take a look at an example to array method. So to array return invoice ID and amount. When the notification is stored in your application's database, the type column will be populated with the notifications class name. However, you may customize this behavior by defining
a database type method on your notification class. So public function database type and then return invoice-paid. To database versus to array. The to array method is also used by the broadcast channel to determine which data to broadcast to your JavaScript powered front end. If you would like to have two different array representations for the database and broadcast channels, you you should define a to database method instead of a to array method.
Accessing the notifications. Once notifications are stored in the database, you need a convenient way to access them from your notifiable entities. The illuminate notifications notifiable trait, which is included on Laravel's default app model's user model, includes a notifications eloquent relationship that returns the notifications for the entity. fetch notifications, you may access this method. Like any other eloquent relationship, by default,
notifications will be sorted by the created at timestamp with the most recent notifications at the beginning of the collection. If you want to retrieve only the unread notifications, you may use the unread notifications relationship. Again, these notifications will be sorted by the created at timestamp with the most recent notifications at the beginning of the collection.
To access your notifications from your JavaScript client, you should define a notification controller for your application, which returns the notifications for a notifiable entity, such as the current user. You may then make an HTTP request to that controller's URL from your JavaScript client. Marking notifications as red. Typically, you'll want to mark a notification as red when a user views it. The illuminate notifications notifiable trait provides a mark as red method, which updates the red at column on the notifications database record.
However, instead of looping through each notification, you may use the mark as red method directly on a collection of notifications. So user on red notifications, mark as red. You You may also use a mass update query to mark all the notifications spread without retrieving them from the database. So user, find, then user, update, red add, now. You may delete the notifications to remove them from the table entirely. Broadcast notifications. Prerequisites.
Before broadcasting notifications, you should configure and be familiar with Laravel's event broadcasting services. Event Broadcasting provides a way to react to server-side Laravel events from your JavaScript-powered frontend. Formatting Broadcast Notifications The broadcast channel broadcast notifications using Laravel's event broadcasting services, allowing your JavaScript-powered frontend to catch notifications in real time.
If a notification supports broadcasting, you can define a to-broadcast method on the notification class. This method will receive a notifiable entity and should return a broadcast message instance. instance. If the to-broadcast method does not exist, the to-array method will be used to gather the data that should be broadcast. The return data will be encoded as JSON and broadcast to your JavaScript powered frontend. Let's take a look at an example to-broadcast method.
Public function to-broadcast. Return new broadcast method. Invoice ID is this invoice ID. Amount this invoice amount. Broadcast queue configuration. All broadcast configurations are queued for broadcasting. If you would like to configure the queue connection or queue name that is used to queue the broadcast operation, you may use the on connection and on queue methods of the broadcast message. Customizing the notification type. In addition to the data you specify,
all broadcast notifications also have a type field containing the full class name of the notification. If you would like to customize the notification type, you may define a broadcast type method on the notification class. Listening for notifications. Notifications will broadcast on a private channel formatted using a notifiable ID convention. So if you are sending a notification to an app models user instance with an ID of one, the notification will be broadcast on the app.models.user.one
private channel. When using their fill echo, you may easily listen for notifications on a channel using the notification method. Customizing the notification channel. If you would like to customize which channel that entities broadcast notifications are broadcast on, you may define a receives broadcast notifications on method on the notification entity. SMS notifications. Sending SMS notifications in Laravel is powered by Vonage, formerly known as
Nexmo. Before you can send notifications via Vonage, you need to install the Laravel Vonage notification channel and guzzle HTTP guzzle packages. The package includes a configuration file. However, you're not required to export this configuration file to your own application. You can simply use the Vonage key and Vonage secret environment variables to define your Vonage public and secret keys. After defining your keys, you should set a Vonage SMS from environment variable that defines the phone number that your SMS messages should be sent
from by default. You may generate this phone number within the Vonage control panel. Formatting SMS notifications. If a notification supports being sent as an SMS, you should define a to Vonage method on the Red Notification class. This method will receive a notifiable entity and should return a notifications messages Vonage message instance. Unicode content. If your SMS message will contain Unicode characters, you should call
the Unicode method when constructing the Vonage message instance. Customizing the from number. If you would like to send some notifications from a phone number that is different from the phone number specified by your Vonage SMS from environment variable, you may call the from method on a Vonage message instance. If you would like to keep track of costs per user, team, or client, you may add a client reference to the notification.
Vonage will allow you to generate reports using this client reference so that you can better understand a particular customer's SMS usage. The client reference can be any string up to 40 characters. Routing SMS Notifications. To route Vonage notifications to the proper phone number, define a route notification
for Vonage method on your notifiable entity. Slack Notifications. Before sending Slack notifications, you should install the Slack notification channel via composer. Additionally, you must create a Slack app for your Slack workspace. If you only need to send notifications to the same Slack workspace that the app is created in, you should ensure that your app has the ChatWrite, ChatWritePublic, and ChatWriteCustomize scopes. These scopes can be added from the OAuth and permissions app management tab within Slack.
Next, copy the app's bot user OAuth token and place it within a Slack configuration array in your application's services.php configuration file. This token can be found on the OAuth and permissions tab within Slack. App distribution. If your application will be sending notifications to external Slack workspaces that are owned by your application's users, you will need to distribute your app via Slack. App distribution can be managed
from your app's manage distribution tab within Slack. Once your app has been distributed, you may use Socialite to obtain Slack bot tokens on behalf of your form application's users. Formatting Slack notifications. If a notification supports being sent as a Slack message, you should return, you should define a to Slack method on your notification class. This method will receive a notifiable entity and should return and illuminate notification Slack slash message instance.
You can construct rich notifications using Slack's block kit API. The following example may be previewed in Slack's block kit builder. So return a new Slack message and you have methods available for that. Slack interactivity. Slack's Block Kit notification system provides powerful features to handle user interaction. To utilize these features, your Slack app should have interactivity enabled and a request
URL configured that points to a URL served by your Slack application. These settings can be managed from the interactivity and shortcuts app from management tab from within Slack. In the following example, which utilizes the actions block method, Slack will send a post request to your request URL with a payload containing the Slack user who clicked the
button, the ID of the clicked button, and more. Your application can then determine the action to take based on the payload. You should also verify the request was made by Slack. So confirmation levels. If you would like users to be required to confirm an action before it is performed, you may invoke the confirm method when defining your button.
The confirm method accepts a message and a closure which receives a confirm object instance. Inspecting Slack blocks. If you would like to quickly inspect the blocks you've been building, you can invoke the dd method on the Slack message instance. The dd method will generate and dump a URL to Slack's block kit builder, which displays a preview of the payload and notification in your browser. You may pass true to the DD method to dump the raw payload.
Routing Slack notifications. To direct Slack notifications to the appropriate Slack team and channel, define a route notification for Slack method on your notifiable model. This method can return one of three values. Null, which defers routing to the channel configured in the notification itself. You may use the to method when building your Slack message to configure the channel within the notification. A string specifying the Slack channel will send us a notification to, e.g. hashtag support-channel. A Slack route instance, which allows you to specify an OAuth
token and channel name, e.g. Slack route make. This method should be used to send notifications to external workspaces. For instance, returning support channel from the route notification for Slack method will send a notification to the hashtag support-channel channel in the workspace associated with the bot user OAuth token located in your application's services.php configuration
file. Notifying External Slack Workspaces. Note, before sending notifications to external Slack Workspaces, your Slack app must be distributed. Of course, you will often want to send notifications to the Slack workspace owned by your application's users. To do so, you will first need to obtain a Slack OAuth token for the user. Thankfully, Laravel Socialite includes a Slack driver that will allow you to easily authenticate your application's users with Slack and obtain
a bot token. Once you have obtained the bot token and stored it within your application's database, you may utilize the Slack route make method to route a notification to the user's workspace. In addition, your application will likely need to offer an opportunity for the user to specify which channel notifications should be sent to. Localizing Notifications. Laravel allows you to send notifications in a locale other than the HTTP request's current
locale and will even remember this locale if the location is queued. To accomplish this, the notifications class offers a locale method to set the desired language. The application will change into this locale when the notification is being evaluated and revert back to the previous locale when evaluation is complete. Localization of multiple notifiable entries may also be achieved via the notification facade. User preferred locale. Sometimes applications
store each user's preferred locale by implementing the HasLocale preference contract on the notifiable model. You may instruct Laravel to use the stored locale when sending a notification. Once you have implemented the interface, Laravel will automatically use the preferred locale when sending notifications and mailables to the model. Therefore, there is no need to call the locale method when using this interface.
Testing You may use the notification facade's fake method to prevent notification from being sent. Typically sending notifications is unrelated to the code you are actually testing. likely it is sufficient to simply assert that Laravel was instructed to send a given notification. After calling the notification facades fake method, you may then assert that notifications were instructed to be sent to users and even inspect the date of the notification received.
You may pass a closure to the assert sent to, assert not sent to methods in order to assert that notification was sent that passes a given truth test. If at least one notification was sent that passes the given truth test, then the assertion will be successful. On-demand notifications. If the code you are testing sends on-demand notifications, you can test that the on-demand notification was sent via the assert sent on-demand method. By passing a closure as the second argument to the assert sent on-demand method, you may
determine if an on-demand notification was sent to the correct route address. Notification events. Notification Sending Event. When a notification is sending, the Illuminate Notifications Events Notification Sending Event is dispatched by the notification system. This contains the notifiable entity and the notification instance itself. You may create event listeners for this event within your application.
The notification will not be sent if an event listener from the notification sending event returns false from its handle method. Within an event listener, you may access the notifiable notification and channel properties on the event to learn more about the notification recipient or the notification itself. When a notification is sent, the notification sent event is dispatched by the notification system. This contains the notifiable entity and the notification instance itself.
You may create event listeners for this event within your application. Within an event listener, you may access the notifiable, notification, channel, and response properties on the event to learn more about the notification, recipient, or the notification itself. Custom Channels Laravel ships with a handful of notification channels, but you may want to write your own drivers to deliver notifications via other channels. Laravel makes it simple. To get started, define a class that contains a send method.
The method should receive two arguments, a notifiable and a notification. From the send method, you may call, within the send method, you may call methods on the notification to retrieve a message object understood by your channel and then send the notification to the notifiable instance however you wish. Once your notification channel has been defined, you may return the class name from the via method of any of your notifications.
In this example, the to voice method of your notification can return whatever object you choose to represent voice messages. For example, you might define your own voice message class to represent these messages.
Thank you.
I'm going to go ahead and put it in the middle of the room.
Thank you.
so
Thank you.
so
Thank you.
so
Thank you.
I'm going to go to the next video.
so
I'm going to put a little bit of a bag of water. I'm going to put a little bit of water on the top.
I'm going to go ahead and put it in the middle of the room.
Thank you.
so
Thank you.
All right, so I turned up the microphone a little bit so that I'm not talking as loud and hopefully it's similar, similar volume, but I can start to feel it in my voice, so We're going to dive, continue to go.
We're in the going deeper section, package development. 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 or a package that allows you to associate files with eloquent models like Spotsy's Laravel media library. There are different types of packages. Some packages are standalone, meaning they work with any PHP framework.
and pest are examples of standalone 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 configurations specifically intended to enhance a Laravel application. This guide primarily covers the development of those packages that are Laravel specific. 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 own package tests as if the package were installed inside a Laravel application, a typical Laravel application, you may use the orchestral test bench package. Package discovery. A Laravel application's bootstrap providers.php file contains a 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 façades you would like to be registered.
So that's class voicemail. So that's in the composer.json file, Laravel, providers, and you would have your provider as well as any aliases. Debugbar would be berryvdh, 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. 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 files you can use don't discover for specific packages. You may disable package discovery
for all packages using the asterisk character inside of your applications don't discover directive. Service providers. Service providers are the connection point between your package and Laravel. A service provider is responsible for binding things like Laravel's service container and informing Laravel where to load package resources such as views, configuration, and language files. A service provider extends the service provider class and contains two methods, register and boot.
The base service provider class is located in the illuminate support composer package, which you should add to your own packages dependencies. To learn more about the structure and purpose of service providers, check out their documentation. Resources configuration. Typically, you will still 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. 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. So config. Currier.option. Warning, you should not define closures in your configuration files.
They cannot be serialized correctly when users execute the config cache artisan command. Default package configuration. 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 that they 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. Warning, this method only merges the first level of the configuration array. If your users partially define a multi-dimensional configuration array, the missing options will not be merged. routes. If your package contains routes, you may load them from using the load routes from method. This method will automatically determine if the application's routes are cached and will not load
your routes if the routes have already been cached. Migrations. If your package contains database migrations, you may use the publishes migrations 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 file name to reflect the current date and time. Language files. If your package contains language files, you may use the load translations from
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. So this load translations from lang courier. Package translation lines are referenced using the package colon colon file dot line syntax convention. So you may load the courier packages welcome line from the messages file like so echo trans courier colon colon messages dot welcome you can register json
translation files for your package using the load json translation from method this method that accepts the path to the directory that contains your package json translation files publishing language files if you would like to publish your package's language files to the applications laying vendor directory you may use the service providers publishes method the publishes method accepts an array of package paths in their desired published locations. For example,
to publish the language files for the courier package, you may do the following. Now, when users of your package execute Laravel's vendor publish artisan command, your package's language files will be published to the specified published location. Views. To register your package's views with Laravel, you need to tell Laravel where the views are located. You may do this using the service providers load views from method. The load views from 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. So load views from courier. Package views are referenced using the package colon colon view syntax. So once your view path is registered in a service provider, you may load the dashboard view from the courier packages like so. So return view courier colon colon dashboard. When you are using, when you use the load views from method, Laravel actually registers two locations for
your views, the applications resource views to 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 developer. Then if the view has not been customized, the owner will search the package view directory you specified in your call to load views from. This makes it easy for package users to customize slash override your package's views. So if you'd like to make your views publishable or 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. Now when users of your package execute Laravel's vendor publish orders in command, your package's views will be copied to the specified publish location. 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 to the boot method of your package's service provider. Once your component has been registered, it may be rendered using its tag alias. So if the package alert component, it would be x-package-alert. Auto loading package components. Alternatively, you may use the component
namespace method to auto load component classes by convention. For example, a nightshade package might have calendar and color picker components that reside within the nightshade views components namespace. This will allow the usage of package components by their vendor namespace using the package-name syntax 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 .notation. If your package contains anonymous views, if your package contains anonymous components, sorry, they must be placed with a components directory of your package's views directory as specified by the load views from method. Then you may render them by prefixing the component name with the package's view namespace
x-currier colon colon alert. About Artisan command. Letterbill'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 about command class. Typically, this information may be added from your package service provider's boot method. Commands. To register your package's Artisan commands with Laravel, you may use the command method. This method expects an
array of command class names. Once the commands have been registered, you may execute them using the Artisan CLI. 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. 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. Publishing file groups. If you want to publish, 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 packages, courier config and courier migrations, and then boot method of the packages of service provider. So this publishes, and then the directory, config path package.php, and then courier-config. Same thing with Publishers Migrations. Now your users may publish these groups separately by referencing their tag when executing the vendor publish command. So php
artisan vendor publish dash dash tag equals courier dash config versus courier dash migrations. All right, digging deeper processes. Introduction. Laravel provides an expressive Laravel provides an expressive minimal API around the Symfony process component, allowing you to conveniently invoke external processes from your Laravel application.
Laravel's processes features are focused on the most common use cases and a wonderful developer experience. Invoking processes. To invoke a process, you may use the run and start methods offered by the process facade. The run method will invoke a process and wait for the process to finish executing, while the start method is used for a synchronous process execution. We'll examine both approaches within this documentation. First, let's examine how to invoke a basic synchronous process
and inspect its result. Of course, the Illuminate Contracts Process of Process Result instance returned by the run method, so result equals process, colon, colon, run, offers a variety of helpful methods that may be used to inspect the process result. Throwing exceptions. If If you have a process result and would like to throw in an instance of process failed exception if the exit code is greater than zero, thus indicating failure, you may use the throw and throw if methods.
If the process did not fail, the process result instance will be returned. Process options. Of course, you may need to customize the behavior of a process before invoking it. Thankfully, Laravel allows you to tweak a variety of process features such as the working directory, timeout, and environment variables. Working directory path. You may use the path method to specify the working directory of the process. If this method is not invoked, the process will inherit the working directory of the currently executing PHP script.
You may provide input via the standard input of the process using the input method. By default, processes will throw an instance of process exceptions process timed out exception after executing for more than 60 seconds. However, you can customize this behavior via the timeout method. By default, processes will throw an instance. Oh, or if you would like to disable the process timeout entirely, you may invoke the forever method.
The idle timeout method may be used to specify the maximum number of attempts, maximum number of seconds the process may run without returning any output. Environment variables may be provided in the process via the ENV method. The invoked process will also inherit all the environment variables defined by your system. So result, process, colon, colon, forever, EMV.
If you wish to remove an environment variable from the invoked process, you may provide that environment variable with a value of false. So process, forever, environment, false. TTY mode. The TTY method may be used to enable TTY mode for your process. TTY mode connects the input and output of the process to the input and output of your program, allowing your process to open an editor like Vim or Nano as a process. So process forever,
TTY, run, Vim. Process output. As previously discussed, process output may be accessed during the or using the output STD out and error output STD error methods on a process result. However, output may also be gathered in real time by passing a closure as the second argument to the run method. The closure will receive two arguments, the type of output, stdout or stdError, and the output string itself.
Laravel also offers the cnOutput and cnErrorOutput methods which provide a convenient way to determine if a given string was contained in the process's output. Disabling Process Output. If your process is writing a significant amount of output that you are not interested in, you can conserve memory by disabling output retrieval entirely. To accomplish this, invoke the quietly method while building the process.
Sometimes you may want to make the output of one process the input of another process. This is often referred to as piping the output of a process into another. The pipe method provided by the process facades makes this easy to accomplish. The pipe method will execute the piped processes synchronously and return the process result for the last process in the pipeline. If you do not wish to customize the individual processes that make up the pipeline, you may
simply pass an array of command strings to the pipe method. The process output may be gathered in real time by passing a closure as the second argument to the pipe method. The closure will receive two arguments, the type of output, sddout or sdderror, and the output string itself. It also allows you to assign string keys to each process with the pipeline via the as method. The key will also be passed to the output closure provided to the pipe method, allowing you to determine which process the output belongs to. Asynchronous processes.
While the run method invokes processes synchronously, the start method may be used to invoke a process asynchronously. This allows your application to continue performing other tasks while the process runs in the background. Once the process has been invoked, you may utilize the running method to determine if the process is still running. As you may have noticed, you may invoke the wait method. So
while process running, result equals process wait. To wait until the process is finished executing and retrieve the process result instance. So process timeout, start, and then process wait. Process IDs and signals. The ID method may be used to retrieve the operating system assigned process ID of the running process. You may use the signal method to send a signal to the running process. A list of predefined signal constants can be found
within the PHP documentation. Asynchronous process output. While an asynchronous process is running, you may access its entire current output using the output and error output methods. However, you may utilize the latest output and latest error output to access the output from the process that has occurred since the output was last retrieved. Like the run method, output may also be gathered in real time from asynchronous processes by passing a closure as the
second argument to the start method. The closure will receive two arguments, the type of output and the output strength itself. Current concurrent processes. Laravel also makes it a breeze to manage a pool of concurrent asynchronous processes, allowing you to easily execute many tasks simultaneously. To get started, invoke the pool method, which accepts a closure that
receives an instance of IlluminateProcessPool. Within this closure, you may define the processes that belong to the pool. Once a process pool is started via the start method, you may access the collection of running processes via the running method. As you can see, you may wait Wait for all of the pool process to finish executing and resolve the results via the wait method. So, pool wait. The wait method returns an array, an accessible object, that allows you to access the process
result instance of each process in the pool by its key. So, result equal pool wait, echo results key output. Or for convenience, the concurrently method may be used to start an asynchronous process pool and immediately wait on its results. can provide particularly expressive syntax when combined with PHP's array destructuring capabilities. Naming pool processes.
Accessing process pool results via a numeric key is not very expressive. Therefore Laravel allows you to assign string keys to each process within a pool via the as method. So pool as first, pool as second command. Since the process pool's running method provides a collection of all invoked processes within the pool, you may easily access the underlying pool process IDs. So process IDs, pool running each ID.
And for convenience, you may invoke the signal method on a process pool to send a signal to every process within the pool. Testing. Many Laravel services provide functionality to help you easily and expressively write tests and Laravel's process service is no exception. The process facades fake method allows you to instruct Laravel to return stubbed dummy results when processes are invoked. Faking processes. To explore Laravel's ability to fake processes, let's imagine a route that invokes
a process. So route git import process run bash import.ish. When testing this route, we can instruct Laravel to return a fake successful process result for every invoked process by calling the fake method on the process facade with no arguments. In addition, we can even assert that a given process was run. As discussed, invoking the fake method on the process facade will instruct Laravel to
always return a successful process result with no output. However, you may easily specify the output and exit code for fake processes using the process facade's result method. So process fake, asterisk, process result. Faking specific processes. As you may have noticed in a previous example, the process facade allows you to specify different fake results per process by passing an array to the fake command.
The array's keys should represent command patterns that you wish to fake and their associated results. The asterisk character may be used as a wildcard character. Any process commands that have not been faked will actually be invoked. You may use the process facade's result method to construct stub and fake results for these commands. If you do not need to customize the exit code or error output of a faked process, you may find it more convenient to specify the fake process results as simple strings.
ProcessFake, cat, testcatoutput, ls, testlsoutput. Faking process sequences. If the code you are testing invokes multiple processes within the same command, you may wish to assign a different fake process result to each process invocation. You may accomplish this via the processFacadesSequence method. faking asynchronous process life cycles. Thus far, we have primarily discussed faking processes which are invoked synchronously using the run method. However, if you are attempting
to test code that interacts with asynchronous processes invoked via start, you may need a more sophisticated approach to describing your fake processes. For example, let's imagine the following route which interacts with an asynchronous process. So route get import process equals process start bash import.sh while the process is running log info of the process latest output and the latest error output. To properly fake this process, we need to be able
to describe how many times the running method should return true. In addition, we may want to specify multiple lines of output that should be returned in sequence. To accomplish this, we can use the process facade's describe method. Let's dig into the example above with process fake fake bash import.sh process describe making less the output error output exit code, etc. Using the output and error output methods, we may specify multiple lines of output that will
be returned in sequence. The exit code method may be used to specify the final exit code of the fake process. Finally, the iterations method may be used to specify how many times the running method should return true. Available assertions. As previously discussed, Laravel provides several process assertions for your feature tests. We'll discuss each of these assertions below. So there's assert ran, assert that a given process was invoked. The assert ran method also accepts a
closure which will receive an instance of a process and process result, allowing you to inspect the process configured options. If this closure returns true, the assertion will pass. The process passed the assertRan closure is an instance of eliminate process pending process, while the result is an instance of eliminate contracts process process result. AssertDidn't Run, assert that a given process was not invoked. Like the assertRan method, the assertDidn'tRun
method also accepts a closure which will receive an instance of a process and a process result, allowing you to inspect the process's configured options. If this closure returns true, the the assertion will fail. Assert ran times. Assert that a given process was invoked a given number of times. So assert ran times times three. The assert ran times method also accepts a closure, which will receive an instance of a process and a process result, allowing you to inspect the process's configured options. If this closure returns true and the process was invoked,
the specified number of times the assertion will pass. Preventing stray processes. If you would like to ensure that all invoked processes have been faked throughout your individual tests or complete test suite, you can call the prevent stray processes method. After calling this method, any processes that do not have a corresponding fake result will throw an exception rather than starting an actual process. Digging deeper cues.
Introduction. While building your web application, you may have some tasks such as parsing and storing an uploaded CSV file that take too long to perform during a typical web request. Thankfully, Laravel allows you to easily create queued jobs that may be processed in the background. By moving time-intensive tasks to a queue, your application can respond to web requests
with blazing speed and provide a better user experience to your customers. Laravel queues provide a unified queuing API across a variety of different queue backends, such as Amazon SQS, Redis, or even a relational database. Laravel's queue configuration options are stored in your application's queue.php configuration file. In this file, you will find connection configurations for each of the queue drivers that are included with the framework,
including the database, Amazon SQS, Redis, and Beanstalk drivers, as well as a synchronous driver that will execute jobs immediately for use during local development. A null queue driver also includes which can discard queue jobs. Note, Laravel now offers Horizon, a beautiful dashboard and configuration system for your Redis-powered queues. Check out the full Horizon documentation for more information. Connections vs. Queues
Before getting started with Laravel queues, it is important to understand the distinction between connections and queues. queues. In your config queue.php configuration file, there is a connections configuration array. This option defines the connections to back-end queue services such as Amazon SQS, Beanstalk, or Redis. However, any given queue connection may have multiple queues, which may be thought of as different stacks or piles of queue jobs. Note that each connection
configuration example in the queue configuration file contains a queue attribute. This is the default queue that jobs will be dispatched to when they are sent to a given connection. In other words, if you dispatch a job without explicitly defining which queue it should be dispatched to, the job will be placed on the queue that is defined in the queue attribute of the connection configuration. Some applications may not need to ever push jobs onto multiple queues, instead preferring
to have one simple queue. However, pushing jobs to multiple queues can be especially useful for applications that wish to prioritize or segment how jobs are processed. Since the Laravel queue worker allows you to specify which queues it should process by priority, for example if you push jobs to a high queue, you may run a worker that gives them higher processing priority. Driver Notes and Prerequisites Database.
In order to use the database queue driver, you will need a database table to hold the jobs. Typically, this is included in Laravel's default create jobs table database migration. However, if your application does not contain this migration, you may use the make q-table artisan command to create it. Redis. In order to use the Redis queue driver, you should configure a Redis database connection in your database.php configuration file. Warning.
The serializer and compression Redis options are not supported by the Redis queue driver. Redis cluster. If your Redis queue connection uses a Redis cluster, your queue names must contain a key hashtag. This is required in order to ensure all of the Redis keys for a given queue are placed into the same hash slot. So Redis, DriverRedis, Connection, Environment, Queue, RetryAfter, Block4, AfterCommit. Blocking.
When using the Redis queue, you may use the Block4 configuration option to specify how long the driver should wait for a job to become available before iterating through the worker loop and re-pulling the Redis database. Adjusting this value based on your queue load can be more efficient than continually pulling the Redis database for new jobs. For instance, you may set the value to 5 to indicate that the driver should block for 5 seconds while waiting for a new job to become available.
Warning, setting block 4 to 0 will cause queue drivers to block indefinitely until a job is available. This will also prevent signals such as sigterm from being handled until the next job is unprocessed. Other driver prerequisites. The following dependencies are needed for the listed queue drivers. These dependencies may be installed via the composer package manager. So Amazon SQS has
a competency of AWS SDK PHP, Beanstalk has a PHE in stock, and Redis has Predis or PHP Redis, php extension creating jobs generating a job classes by default all the queueable jobs for your application are stored in the app jobs directory if the app jobs directory doesn't exist it will be created when you run the make job artisan command the generated class will
implement the queue should queue interface indicating to laravel the job should be pushed onto the queue to run asynchronously note job stubs may be customized using stub publishing Class structure. Job classes are very simple, normally containing only a handle method that is invoked when the job is processed by the queue. To get started, let's take a look at an example job class. In this example, we'll pretend we manage a podcast publishing service
and need to process the uploaded podcast files before they are published. So this class process podcasts implements should queue, you can use dispatchable, interacts with queue queueable, execute the job public function handle. In this example, note that we were able to pass an eloquent model directly into the queued jobs constructors. In this case, public function construct public
podcast dollar side podcast. Because of the serialized models trait that the job is using, eloquent models and their loaded relationships will be gracefully serialized and unserialized when the job is processing. If your queue job accepts an eloquent model and its constructor, only the identifier for the model will be serialized onto the queue. When the job is actually
handled, the queue system will automatically retrieve, re-retrieve the full model instance and its loaded relationships from the database. This approach to model serialization allows for much smaller job payloads to be sent to your queue driver. Handle Method Dependency Injection. The handle method is invoked when the job is processed by the queue. Note that we are able to type in dependencies on the handle method of the job. The Laravel Service Container automatically injects
these dependencies. If you would like to take control over how the container injects dependencies into the handle method, you may use the container's bind method method. The bind method method accepts a callback which receives this job and the container. Within the callback, you are free to invoke the handle method however you wish. Typically, you should call this method from the boot method of your application app service provider service provider. Warning, binary data such as raw image contents should be passed through the Base64 encode function
before being processed, being passed to a queue job. Otherwise, the job may not properly serialize to JSON when being placed on the queue. Queued relationships. Because all loaded eloquent model relationships also get serialized when a job is queued, the serialized job string can sometimes become quite large. Furthermore, when a job is deserialized and model relationships are re-retrieved from
the database, they will be retrieved in their entity entirety. Any previous relationship constraints that were applied before the model was serialized during the job queuing process will not be applied when the job is deserialized. Therefore, if you wish to work with the subset of a given relationship, you should reconstrain that relationship within your Q job. Or, to prevent relations from being serialized, you can call the without relations method on the
model when setting a property value. This method will return an instance of the model without its loaded relationships. If you are using PHP constructor property promotion and would like to indicate that an eloquent model should not have its relations serialized, you may use the without relations attribute. If a job receives a collection or array of eloquent models instead of a single model, the models within that collection will not have their relationships restored when the job is deserialized and executed. This is to prevent excessive resource usage on
jobs that deal with large numbers or large numbers of models. Unique jobs. Sometimes you may want to ensure that only one instance of a specific job is on the queue at any point at any time. You may do so by implementing the should be unique interface on your job class. This interface does not require you to define any additional methods on your class. So class update search or index implements should queue and should be unique. In the example above,
the update search index job is unique. So the job will not be dispatched if another instance of the job is already on the queue and has not finished processing. In certain cases, you may want to define a specific key that makes the job unique, or you may want to specify a timeout beyond which the job no longer stays unique. To accomplish this, you may define unique ID and unique for properties or methods on your job class. So you have public, unique for,
and then the public function, unique ID. In the example above, the update search index job is unique by a product ID, so any new dispatches of the job with the same product ID will be ignored until the existing job has completed processing. In addition, if the existing job is not processed within one hour, the unique lock will be released and another job with the same unique key can be dispatched to the queue. Keeping jobs unique until processing begins. By default, unique jobs are
unlocked after a job completes processing or fails all of its retry attempts. However, there may be situations where you would like your job to unlock immediately before it is processed. To accomplish this, your job should implement the should be unique until processing contract instead of the should be unique contract. Unique job locks. Behind the scenes when a should be
unique job is dispatched, Laravel attempts to acquire a lock with a unique ID key. If the lock is not acquired, the job is not dispatched. This lock is released when the job completes processing or fails all of its retry attempts. By default, Laravel will use the default cache driver to obtain this lock. However, if you wish to use another driver for acquiring the lock, you may define a unique via method that returns the cache driver that should be used. So public function unique via.
Encrypted jobs. Laravel allows you to ensure the privacy and integrity of a job's data via encryption. To get started, simply add the should be encrypted interface to the job class. Once this interface has been added to the class, Laravel will automatically encrypt your job before pushing it onto a queue. Job middleware. Job middleware allows you to wrap custom logic around the execution of queue jobs, reducing boilerplate in the jobs themselves. For example,
consider the following handle method which leverages Laravel's Redis rate limiting features to allow only one job to process every five seconds. So public function handle, Redis throttle, key block allow every five, and then handle the job function could not obtain lock return this release for five. While this code is valid, the implementation of the handle method becomes noisy since it is cluttered with Redis rate limiting logic. In addition, this rate limiting
logic must be duplicated for any other jobs that we want to rate limit. Instead of rate limiting in the handle method, we could define a job middleware, the handles rate limiting. Laravel does not have a default location for job middleware, so you are welcome to place job middleware anywhere in your application.
In this example, we will place the middleware in an app jobs middleware directory. So public function handle, redis throttle, this is in the app jobs middleware. As you can see, like route middleware, job middleware receives the job being processed in a callback that should be invoked to continue processing the job.
After creating job middleware, they may be attached to a job by returning them from the job's middleware method. This method does not exist on job scaffolded by the make job artisan command, so you will need to manually add it to your job class. So you have to use the rate-limited middleware and then public function middleware return that to rate-limited function. Rate-limited. Although we just demonstrated how to write your own rate-limiting job middleware,
Laravel actually includes a rate-limiting middleware that you may utilize to rate-limit jobs. Like route rate limiters, job rate limiters are defined using the rate limiter facades for method. For example, you may wish to allow users to backup their data once per hour while imposing no such limits on premium customers. To accomplish this, you may define a rate limiter in the boot method of your app service provider. So, rate limiter for backups function, return job user
VIP customer, limit none, else limit per hour. In the example above, we defined an hourly rate limit. However, you may easily define a rate limit based on minutes using the per minute method. In addition, you may pass any value you wish to the buy method of the rate limit. However, this value is most often used to segment rate limits by a customer. Once you have defined your rate limit, you may attach the rate limiter to your job using
the queue middleware rate limited middleware. Each time the job exceeds the rate limit, this middleware will release the job back to the queue with an appropriate delay based on the rate limit duration. Releasing a rate-limited job back into the queue will still increment the job's total number of temps. You may wish to tune your tries and max exceptions property on your job class accordingly, or you may wish to use the retry until method to define the amount of time until the job
should no longer be attempted. If you do not want a job to be retried when it is rate-limited, you may use the don't release method. Preventing job overlaps. includes an illuminate queue middleware without overlapping middleware that allows you to prevent job overlaps based on an arbitrary key. This can be helpful when a queue job is modifying a resource
that should only be modified by one job at a time. For example, let's imagine you have a queue job that updates a user's credit score and you want to prevent credit score update job overlaps for the same user ID. To accomplish this, you can return the without overlapping middleware from from your job's middleware method. Any overlapping jobs of the same type will be released back to the queue. You may also specify the number of seconds that must elapse before the release job will be attempted again.
So function middleware, return that specific middleware without overlapping, this order ID, release after 60 seconds. If you wish to immediately delete any overlapping jobs so that they will not be retried, you may use the don't release method. The without overlapping middleware is powered by Laravel's atomic lock feature. Sometimes your job may unexpectedly fail or time out in such a way that the lock is not released.
Therefore, you may explicitly define a lock expiration time using the expire after method. For example, the example below will instruct Laravel to release the without overlapping lock three times or three minutes after the job has started processing. So public function middleware expires after. Sharing lock keys across job classes. By default, the without overlapping middleware will only prevent overlapping jobs of the same class. So although two different
job classes may use the same lock key, they will not be prevented from overlapping. However, you can instruct Laravel to apply the key across job classes using the shared method. Throttling Exceptions. Laravel includes a QMiddleware Throttles Exceptions middleware that allows you to throttle exceptions. Once the job throws a given number of exceptions, all further attempts to execute the job are
delayed until a specified time interval lapses. This middleware is particularly useful for jobs that interact with third-party services that are unstable. For example, let's imagine a queued job that interacts with a third-party API that begins throwing in exceptions. To throttle exceptions, you can return the throttleExceptionsMiddleware from your job's middleware method. Typically, this middleware should be paired with a job that implements time-based attempts. The first constructor argument accepted by the middleware is the number of exceptions
the job can throw before being throttled, while the second constructor argument is the number of minutes that should elapse before the job is attempted again once it has been throttled. code example above, so public function middleware, throttles exceptions 10 comma 5. If the job throws 10 exceptions within five minutes, we will wait five minutes before attempting the job again. When a job throws an exception but the exception threshold does not have been reached, the job
will typically be retried immediately. However, you may specify the number of minutes such a job should be delayed by calling the backoff method when attaching the middleware to the job. So return in a new throttles exception, back off five. Internally, this middleware uses Laravel's cash system to implement rate limiting, and the job's class name is utilized as the cash key. You may override this key by calling the buy method when attaching the middleware
to your job. This may be useful if you have multiple jobs interacting with the same third party service and you would like them to share a common throttling bucket. By default, the middleware will throttle every exception. You can modify this behavior by invoking the win method when attaching the middleware to your job. The exception will then only be throttled if closure provided to
the win method returns true. So if you'd like to have the throttled exceptions reported to your application's exception handler, you can do so by invoking the report method when attaching the middleware to your job. Optionally, you may provide a closure to the report method and the exception will only be reported if the given closure returns true. If you are using Redis, you may use the throttles exceptions with Redis middleware, which is fine-tuned for Redis and more efficient than the basic exception throttling middleware.
Dispatching jobs. Once you have written your job class, you may dispatch it using the dispatch method on the job itself. The arguments passed the dispatch method will be given to the jobs constructor. So process podcast, colon, colon, dispatch that podcast. If you would like to conditionally dispatch a job, you may use the dispatch if and dispatch unless method. In new
Laravel applications, the sync driver is the default queue driver. This driver executes jobs synchronously in the foreground of the current request, which is often convenient during a local development. If you would like to actually begin queuing jobs for background processing, you may specify a different queue driver within your application's config slash queue.php configuration file. Delayed dispatching. If you would like to specify that a job should not be immediately
avail or should not be immediately available for processing by a queue worker, you may use the delay method when dispatching the job. For example, let's specify that a job should not be available for processing until 10 minutes after it has been dispatched. Dispatching after the response is sent to the browser. Alternatively, the dispatch after response method delays dispatching a job until after
the HTTP response is sent to the user's browser if your web browser is using FastCGI. This will still allow the user to begin using the application even though a queue job is still executing. They should typically only be used for jobs that take about a second, such as sending an email. Since they are processed within the current HTTP request, jobs dispatched in this fashion do not require a queue worker to be running in order for them to be processed.
You may also dispatch a closure and chain the after response method onto the dispatch helper to execute a closure after the HTTP response has been sent to the browser. So use app mail welcome message dispatch function mail to send after response. Synchronous dispatch. If you would like to dispatch a job immediately synchronously, you may use the dispatch sync method when using this method.
The job will not be queued and will be executed immediately within the current process. So go to the collection store, process pod tasks, dispatch sync. Jobs and database transactions. While it is perfectly fine to dispatch jobs within database transactions, you should take special care to ensure that your job will actually be able to execute successfully. When dispatching a job within a transaction, it is possible that the job will be processed by a worker before the parent transaction has committed.
When this happens, any updates you have made to models or database records during the database transactions may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. Thankfully, Laravel provides several methods of working around this problem. First, you may set the after commit connection option in your queue connections configuration array. When the after commit option is true, you may dispatch jobs within database transactions.
However, Laravel will wait until the open parent database transactions have been committed before actually dispatching the job. Of course, if no database transactions are currently open, the job will be dispatched immediately. If a transaction is rolled back due to an exception that occurs during the transaction, the jobs that were dispatched during that transaction will be discarded. Specifying column dispatch or specifying commit dispatch behavior inline.
If you do not set the after commit queue connection configuration option to true, you may still indicate that a specific job should be dispatched after all open database transactions have been committed. To accomplish this, you may chain the after commit method onto your dispatch operation. Process podcash dispatch after commit. Likewise, if the after commit configuration option is set to true, you may indicate that a specific job should be dispatched immediately without waiting
for any open database transactions to commit. Job chaining. Job chaining allows you to specify a a list of queue 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 queue 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. So bus,
chain, new process podcast, new optimized podcast, new release podcast, dispatch. In addition to chaining job class instances, you may also chain closures. So bus chain, new process podcast, new optimized podcast, and then the closure function, podcast update with some chaining there. Chain connection and queue. If you would like to specify the connection and queue that should be
used for the chain jobs, you may use the on connection and on queue methods. These methods specify the queue connection and queue name that should be used unless the queue job is explicitly assigned a different connection slash queue. 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 prepend to chain and append to chain methods. 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. Customizing the queue connection. Dispatching to a particular queue. By pushing jobs through different queues, you may categorize your queue jobs and even prioritize how many workers you assign to various queues. Keep in mind this does not push jobs through 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. Alternatively, you may specify the jobs queue by calling the on queue method within the jobs constructor. So construct this on queue processing. 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 on connection method. So process podcast dispatch on connection, the SQS connection. You may chain the on connection and on queue methods together to specify the connection and the queue for the job. Alternatively, you may specify the jobs connection by calling the onConnection method within the jobs constructor.
Specifying max attempts and timeout values. If one of your queue jobs is encountering any, 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 specify the maximum number of times a job may be attempted is via the dash dash 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 they may be attempted. So php artisan q
colon work dash dash tries equal three. If a job exceeds the maximum number of attempts, it will be considered a failed job. For more information on handling failed jobs, consult the failed job documentation. If dash dash tries equals zero is provided to the q 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 dash dash tries value
provided on the command line. So if you need dynamic control over a particular job's maximum attempts, you may define a tries method on the job. So public function tries with an integer return 5. 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 timeframe. To define the time at which a job should
no longer be attempted, add a retry until method to your job class. So this method should return a date-to-time instance. So return now plus add 10 minutes. 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 need to find a max exceptions property on your job class.
So public max exception equal three. Max exceptions. In this example, the job is released for 10 seconds. The application is unable to obtain a redis lock. So the handle function redis throttle for allow 10 and will continue to be retried up to 25 times because there's a public tries method value of 25. However, the job will fail if three unhandled exceptions are thrown by the job.
Timeout. Often you know roughly how long you expect your due 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. The maximum number of seconds that jobs can run may be specified using the dash dash timeout switch on the artisan command line. 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. 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 connection and request timeout value. Failing on timeout. If you would like to indicate that a job should be marked as failed on timeout, you may define the fail on timeout property on the job class. So public fail on timeout equals true. Error handling. If an exception is thrown while the job is being processed, the job will automatically be released back into 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 of attempts is defined by the dash dash try switch used on the QWorkArtisan command. Alternatively, the maximum number of attempts may be defined on the job class itself. More information on running the QWorker can be found below. Manually releasing a job. Sometimes you may wish to manually release a job until the queue onto the queue so that
it can be attempted again at a later time. You may accomplish this by calling the release method. 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. Occasionally, you may need to manually mark a job as failed. To do
So you may call it the fail method. 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 where it will be converted to an exception for you. So this fail, something went wrong. Job batching. Laravel's job batching feature allows you to easily execute a batch of jobs and then perform some action when the batch of jobs is completed executing. Before getting started, you should create a database migration to build a table
which will contain meta information about your job batches, such as their completion percentage. This migration may be generated using the make queue batches table artisan commands. Defining Batchable Jobs. To define a batchable job, you should create a queueable job. As normal, however, you should add the IlluminateBus batchable trait to the job class. This trait provides access to a batch method, which may be used to retrieve the current batch that the job is executing within. Dispatching Batches.
To dispatch a batch of jobs, you should use the batch method of the bus facade. Of course, batching is primarily useful when combining with completion callbacks, so you may use the then, catch, and finally methods to define completion callbacks for the batch. Each of these callbacks will receive an IlluminateBusBatch instance when they are invoked. In this example, we will imagine we are queuing a batch of jobs that each process a given number of rows from a CSV file.
So batch, bus batch, new, import CSV, and there's about five of those. And then you can have before, progress, then catch, finally dispatch. The batch's ID, which may be accessed via the batch ID property, may be used to query the Laravel command, but be bused for information about the batch after it has been dispatched. Naming batches. Some tools, such as Laravel Horizon and Laravel Telescope, may provide more user-friendly debug information for batches if batches are named.
To assign an arbitrary name to a batch, you may call the name method while defining the batch. So batch plus batch, then at the propending name. Batch connection and queue. If you would like to specify the connection and queue that should be used for the batch jobs, you may use the on connection and on queue methods. All batch jobs must execute within the same connection and queue. Chains and batches. You may define a set of change jobs within a batch
by placing the chain jobs within an array. For example, we may execute two job chains in parallel and execute a callback when both job chains have finished processing. So bus batch, one array of jobs, two array of jobs, then function, and then dispatch that bus batch. Conversely, you may run batches of jobs within a chain by defining batches within the chain. For example, you could first run a batch of jobs to release multiple podcasts and then a batch of jobs to send the release notifications.
Adding jobs to batches. Sometimes it may be useful to add additional jobs to a batch from within a batch job. This pattern can be useful when you need to batch thousands of jobs, which may take too long to dispatch during a web request. So instead, you may wish to dispatch an initial batch of loader jobs that hydrate the batch with even more jobs.
So batch new and then all jobs completed successfully. In this example, we will use the load import batch job to hydrate the batch with additional jobs. To accomplish this, we may use the add method on the batch instance that may be accessed via the jobs batch method.
So within the load import job batch, this batch add collection, colon, colon, times a thousand. Warning, you may only add jobs to a batch from within a job that belongs to the same batch. Inspecting batches. The Illuminate Bus Batch instance that's provided to batch completion callbacks has a variety of properties and methods to assist you in interacting with and inspecting a given batch of jobs.
Returning Batches from Routes. An Illuminae bus batch instance are JSON serializable, meaning you can return them directly from one of your application's routes to retrieve a JSON payload containing information about the batch, including its completion progress. This makes it convenient to display information about the batch's completion progress in your application's UI. To retrieve a batch by its ID, you may use the bus facade's find batch method. Canceling batches.
Sometimes you may need to cancel a given batch's execution. This can be accomplished by calling the cancel method on the IlluminateBusBatch instance. So if this user exceeds import limit, return this batch cancel. As you may have noticed in the previous examples, batch jobs are typically determined if the corresponding batch has been canceled before continuing execution. However, for convenience, you may assign the skip if batch canceled middleware
to the job instead. As its name indicates, this middleware will instruct Laravel to not process the job if its corresponding batch has been canceled. Batch failures. When a batch job fails, the catch callback, if assigned, will be invoked. This callback is only invoked for the first job that fails within the batch. So allowing failures. When a job within a batch fails, Laravel will automatically mark the batch as canceled. If you wish, you may disable this behavior so that the job failure does not automatically mark the batch as canceled. This may be accomplished by calling the allowed
failures method while dispatching the batch. So bust batch allow failures. Retrying failed fetch jobs. For convenience, Laravel provides a Q-Retry Batch Artisan Command that allows you to easily retry all the failed jobs for a given batch. The Q-Retry Batch Command accepts the UUID of the batch whose failed jobs should be retried. Pruning batches. Without pruning, the job batches table can accumulate records very quickly. To mitigate this,
you should schedule the Q prune batches artisan command to run daily. So schedule command Q prune batches daily. By default, all finished batches that are more than 24 hours old will be pruned. You may use the hours option when calling that command to determine how long to retain batch data. For example, the following command will delete all batches that finished over 48 hours ago. Schedule command Q prune batches dash dash hours equal 48 daily. Sometimes your job batches
table may accumulate batch records for batches that never completed successfully, such as batches where a job failed and that job was never retried successfully. You may instruct the Q prune batches command to prune these unfinished batch records using the unfinished option. So schedule command Q prune batches dash dash hours equals 48 dash dash unfinished equals 72. Likewise, your jobs batches table may also accumulate batch records for canceled batches. You may instruct the Q prune batches command to prune these canceled batch records
using the canceled option. Storing batches in DynamoDB. There also provides support for storing batch meta information in DynamoDB instead of a relational database. However, you will need to manually create a DynamoDB table to store all the batch records. Typically, this table should be named JobBatches, but you should name the table based on the value of the queue.batch.tableConfiguration value within your application's queue configuration file.
DynamoDB batch table configuration. The job batches table should have a string primary partition key named application and a string primary sort key named id. The application portion of the key will contain your application's name as defined by the name configuration value within your applications.env file. Since the application name is part of the DynamoDB table's key, you can use this same table to store job batches for multiple variable applications. In addition, you may define
TTL attribute for a table if you would like to take advantage of automatic batch pruning. DynamoDB configuration. Next, install the AWS SDK so that your Laravel application can communicate with Amazon DynamoDB. Then, set the queue.batching.driver configuration options value to DynamoDB. In addition, you should define key, secret, and region configuration options within
the batching configuration array. These options will be used to authenticate within AWS. When using the DynamoDB driver, the queue.batching.database configuration option is unnecessary. Pruning batches in DynamoDB. When utilizing DynamoDB to store job batching information, the typical pruning commands used to prune batches stored in a relational database will not work. Instead, you may utilize DynamoDB's native TTL functionality to automatically remove records
for all database. Hold batches. If you defined your DynamoDB table with a TTL attribute, you may define configuration parameters to instruct Laravel how to prune batch records. The queue.batching.ttl attribute configuration value defines the name of the attribute holding the TTL, while the queue.batching.ttl configuration value defines the number of seconds after which a batch record can be removed from the the DynamoDB table relative to the last time the record was updated.
Queuing closures. Instead of dispatching a job class to the queue, you may also dispatch a closure. This is great for quick, simple tasks that may need to be executed outside of the current request cycle. When dispatching closures to the queue, the closure's code content is cryptographically signed so that it cannot be modified in transit. Using the catch method. You may provide a closure that cannot be executed if the queued closure fails to complete successfully
after exhausting all of your queues configured retry attempts. Running the Queue Worker. 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 Worker command has started, it will continue to run until it manually stopped or you close your terminal. You may include the "-v flag when invoking
the QueueWork command if you would like the process job IDs to be included in the command's output. Remember, QueueWorkers are long-lived processes and store the booted application's state in memory. As a result, they will not notice changes in your codebase after they have been started. So during your deployment process, be sure to restart your QueueWorkers. 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. Running multiple queue workers. To assign multiple workers 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 printout process manager's configuration
settings. When using supervisor, you may use the numprox configuration value, specifying the connection in 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 in your config queue.php file. PHP Artisan 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 email's queue on your Redis queue server or queue connection, you may issue the following command to start a worker that only processes that queue. so artist in queue work redis dash dash queue equals emails. The dash dash once option may be used to instruct the worker to only process the single job from the queue. Queue work dash dash
once. The max job option may be used to instruct the worker to process the given number of jobs and then exit. This option would be useful when combining with supervisor so that your workers are automatically restarted after processing a given number of jobs, releasing any memory they may have accumulated. Processing all queued jobs and then exiting. The dash dash 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 shut down the container after the queue is empty. 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 supervisors so that your workers are automatically restarted after processing jobs for any given amount of time, releasing any memory
that they may have accumulated. 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. Maintenance mode and queues. While your application is in maintenance mode, no queue jobs will be handled. The jobs will be continued to be handled as normal once the application is out of maintenance mode. To force your queue workers to process queue
jobs, even in maintenance mode is enabled, you may use the dash dash force option. Resource configurations. 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 image destroy when you are done processing the image. 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 want to wish to push a job to a high priority queue like so. Dispatch on queue high. To start worker that verifies that all the high queue jobs are processed before continuing to do any of the jobs on the low queue, pass a comma to eliminate a list of queue names to the worker command. So
artisan queework dash dash queue equals high and then low queue workers and then 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. This command will instruct all queue workers to
gracefully exit after they finish processing the 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 to automatically restart the queue workers. Note, the queue uses the cache to store restart singles, so you should verify that a cache driver is properly configured for your application before using this feature. Job expirations and timeouts. Job expiration.
In your config queue.php configuration file, each queue connection defines a retry after option. The 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 into 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 job should reasonably take to complete processing.
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 which is managed within the AWS console. Worker timeouts. The queue work artisan command exposes a dash dash timeout option. By default, the dash dash 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, this worker will be restarted automatically by a process manager configured on your server. PHP Artisan Q work, timeout 60. The retry after configuration option and the timeout CLI option are different but work together to ensure the jobs are not lost and the jobs are only successfully processed once. Supervisor configuration. In production, you need a way to keep your QWR processes running. A QWR process may stop running for a variety of reasons, such as exceeded worker timeout
for the execution of the QRestart command. For this reason, you need to configure a process monitor that can detect when your QWR processes exit and automatically restart them. In addition, process monitors can allow you to specify how many QWR 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.
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. Pseudo apt-get install supervisor. Configuring Supervisor Supervisor configuration files are typically stored in the etc. c supervisor conf.d directory. Within this directory, you may create any number of configuration files that instructs Supervisor how your processes should be monitored. For example,
let's create a larivel-worker.conf file that starts and monitors Q work processes. In this example, the numprox directive will instruct Supervisor to run eight Q 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.
Starting supervisor. Once the configuration file has been created, you may update the supervisor configuration and start the processes using the following commands. For more information on supervisor, consult the supervisor documentation. Dealing with failed jobs. But sometimes your queue jobs will fail. Don't worry, things don't always go as planned. Laravel includes a convenient way to specify the maximum number of times a job should be attempted. After a synchronous job has exceeded this number of attempts, it will be inserted into the failed jobs database table.
Synchronously dispatch jobs that fail are not stored in this table and their exceptions are immediately handled by the application. A migration to create the failed jobs table is typically already present in new level applications. However, if your application does not contain a migration for this table, you may use the make queue fail table command to create the migration. When running a queue worker process, you may specify the number of times a job should be
attempted using the dash dash tries switch on the queue work command. If you do not specify a value for the tries option, jobs will only be attempted once or as many times as specified by the job class tries property. Using the back off option, you may specify how many seconds Laravel should wait before retrying a job that has encountered an exception. By default, a job is immediately released back onto the queue so that it may be attempted again. If you would like to configure
how many seconds Laravel should wait before retrying a job that has encountered an exception on a per-job basis, you may do so by defining a backoff property on your job class. If you require more complex logic for determining the job's backoff time, you may define a backoff method on your job class. You may easily configure exponential backoffs by returning an array
values from the backoff method. In this example, the retry delay will be one second for the first retry, five seconds for the second retry, ten seconds for the third retry, and ten seconds for every subsequent retry if there are more attempts remaining. So put both function back off with an array of one, five, and ten. Cleaning up after failed jobs. When a particular job fails, you may want to send an alert to your users or revert any actions that were partially completed by the job. To accomplish this, you may define a failed method on your job class.
The throwable instance that caused the job to fail will be passed to the failed method. Retrying failed jobs. To view all the failed jobs that have been inserted into your failed jobs database table, you may use the Q failed artisan command. The Q failed command will list the job ID connection, Q failure time and other information about the job. The job ID may be used to retry the failed job. For instance, to retry a failed
job that has an ID of UUID, issue the command PHP artisan Q retry and then the failed ID. If necessary, you can pass multiple IDs to the command, and that's just space limited. We also retry all the failed jobs for a particular queue. So php artisan qretry and dash dash q equals name. To retry all of the failed jobs, execute the qretry command and pass all as the ID.
If you would like to delete a failed job, you may use the qforget command. When using horizon, note, you should use the horizon forget command to delete a failed job instead of the qforget command. To delete all of your failed jobs from the failed jobs table, you may use the queue flush command. Ignoring missing models. When injecting an eloquent model into a job, the model is automatically serialized before being placed on the queue and re-retrieved from the database when the job is processed.
However, if the model has been deleted while the job was waiting to be processed by a worker, your job may fail with a model not found exception. For convenience, you may choose to automatically delete jobs with missing models by setting your jobs delete when missing models property to true. When this property is set to true, Laravel will quietly discard the job without raising an exception. Pruning failed jobs. You may prune the records in your application's failed jobs table by
invoking the Q prune dash failed artisan command. By default, all of the failed jobs that are more than 24 hours old will be pruned if you provide the dash dash hours option to the only the failed job records that were inserted within the last n number of hours will be restarted. For example, the following command will delete all the failed jobs records that were inserted more than 48 hours ago. Storing failed jobs in DynamoDB. Laravel also provides
support for storing your failed jobs in DynamoDB instead of a relational database table. However, you must manually create a DynamoDB table to store all the failed job records. Typically, this table should be named failed jobs, but you should name the table based on the value of the queue.failed.table configuration value within your application's queue configuration file. The failed jobs table should have a string primary partition key named application and a string primary sort key named UUID.
The application portion of the app or the key will contain your application's name as defined by the name configuration value within your application's app configuration file. Since the application name is part of the DynamoDB table's key, you can use the same table to store failed jobs for multiple Laravel applications. In addition, ensure that you install the AWS SDK so that your Laravel application can continue or communicate with Amazon DynamoDB. Next, set the Q.fail.driver configuration options value to DynamoDB. In addition, you should define
key, secret, and region configuration options within the failed job configuration array. These options will be used to authenticate within AWS. When using the DynamoDB driver, However, the queue.fail.database configuration option is unnecessary. Disabling failed job storage. You may instruct Laravel to discard failed jobs without storing them by setting the queue.fail.driver configuration option's value to null.
Typically this may be accomplished via the queue.faileddriver environment variable. Failed job events. If you would like to register an event listener that will be invoked when a job fails, you may use the queue.facades.failing method. For example, we may attach a closure to this event from the boot method of the app service provider that is included with Laravel. So boot queue failing, and then have a function there.
Clearing jobs from queues. Note when using Horizon, you should use the horizon clear command to clear jobs from the queue instead of the queue clear command. If you would like to delete all jobs from the default queue of the default connection, you may do so using the queue clear artisan command. You may also provide the connection, argument, and queue option to delete jobs from a specific connection and queue. Monitoring your queues. If your queue receives a sudden influx of jobs, it could become overwhelmed, leading
to a long wait time for jobs to complete. If you wish, Laravel can alert you when your queue job count exceeds a specified threshold. To get started, you should schedule the queue monitor command to run every minute. This command accepts the names of the queues you wish to monitor as well as your desired job count threshold. PHPR does in queue monitor, you can specify the queues. Scheduling this command alone is not enough to trigger a notification alerting you of the queue's overwhelmed status.
When the command encounters a queue that has a job count exceeding your threshold, a queue busy event will be dispatched. You may listen for this event within your application's app service provider in order to send a notification to you or your development team. Testing. When testing code that dispatches jobs, you may wish to instruct Laravel to not actually execute the job itself, since the job's code can be tested directly and separately of the code that dispatches it.
Of course, to test the job itself, you may instantiate a job instance and invoke the handle method directly in your test. You may use the queue facade's fake method to prevent queue jobs from actually being pushed to the queue. After calling the QFaçade fake method, you may then assert that the application attempted to push jobs into the Q. You may pass a closure to the assert pushed or assert not pushed
methods in order to assert that a job was pushed that passes a given truth test. If at least one job was pushed that passes the given truth test, then the assertion will be successful. Faking a subset of jobs. If you only need to fake specific jobs while allowing your other jobs to execute. Normally, you may pass the class names of the jobs that should be faked to the fake method. You may fake all jobs except for a set of specific jobs using the accept method. So, cue, fake, accept, specific job.
Testing job chains. To test job chains, you need to utilize the bus's facades faking capabilities. The bus facades assert chain method may be used to assert that a chain of jobs is dispatched. The assertChain method accepts an array of chained jobs as its first argument. BustAssertChained, shipOrder, recordShipment, update, and inventory. And you have BustFake. As you see in the example above, the array of chained jobs may be an array of the jobs class names.
However, you may also provide an array of actual job instances. When doing so, Laravel will ensure that the job instances are of the same class and may have the same property values of the chained jobs dispatched by your application. You may use the assert dispatch without chain method to assert that a job was pushed without a chain of jobs. Testing chain modifications. If a chain job propends or appends jobs to an existing chain, you may use the jobs assert has chain method to assert that the job has the
expected chain of remaining jobs. The assert doesn't have chain method may be used to assert that the job's remaining chain is empty. Testing chain batches. If your job chain contains a batch of jobs, you may assert that the chain batch matches your expectations by inserting a bus chained batch definition within your chain assertion. Testing job batches. The bus facade's assert batch method may be used to assert that a batch of jobs was dispatched. The closure
given to the assert bus matched method receives an instance of bus pending batch, which may be used to inspect the job within the batch. You may use the assert batch count method to assert that a given number of batches were dispatched. You may use assert nothing batch to assert that no batches were dispatched. Testing job batch interaction. In addition,
you may occasionally need to test an individual with jobs interaction with its underlying batch. For example, you may need to test if a job canceled further processing for its batch. To accomplish this, you need to assign a fake batch to the job via the with fake batch method. The with fake batch method returns a tuple containing the job instance and the fake batch. So, job batch equals new ship order with fake batch. Testing job queue interactions. Sometimes you may need to test that a queue job releases itself
back into the queue. Or you may need to test the job deleted itself. You may test these queue interactions by instantiating the job and invoking the with fake queue interactions method. Once the job's queue's interactions have been faked, you may invoke the handle method on the job. After invoking the job, the assert release, assert deleted, and assert
failed methods may be used to make assertions against the job's queue interactions. Job events. Using the before and after methods on the queue facade, you may specify callbacks to be executed before or after a queued job is processed. These callbacks are a great opportunity to perform additional logging or increment statistics for a dashboard. Typically, you should call these methods from the boot method of a service provider.
For example, we may use the app service provider that is included with Laravel. Using the looping method of the queue facade, you may specify callbacks that execute before the worker attempts to fetch a job from a queue. For example, you might register a closure to roll back any transactions that were left open by a previously failed job. dive into rate limiting. I'm going to take a quick break, get some more tea,
and we'll be right back. So deep dive, rate limiting.
Thank you.
so
Thank you.
All right, let's get back into it. So database. I believe this is still in the diving deeper section. Database, getting started. Introduction. Almost every modern web allocation interacts with
Database. Laravel makes interacting with databases extremely simple across a variety of supported databases using raw SQL, a fluent query builder, and the eloquent URL. Currently, Laravel provides first-party support for five databases. MariaDB, MySQL, Postgres, SQLite, SQL Server. Configuration. The configuration for Laravel's database services is located in your application's
database.php configuration file. In this file you may define all of your database connections as well as specify which database connection and which connection should be used by default. Most of the configuration options within this file are driven by the values of your application's environment variables. Examples for most of Laravel's supported database systems are provided in this file. By default, Laravel's sample environment configuration is ready to use with
Laravel SAIL, which is a Docker configuration for developing Laravel applications on your local machine. However, you are free to modify your database configuration as needed for your local database. SQLite configuration. SQLite databases are contained within a single file on your file system. You can create a new SQLite database using the touch command in your terminal. Touch database database.sqlite.
After the database has been created, you may easily configure your environment variables to point to this database by placing the actual path to the database in the DB database environment variable. So DB connections, SQLite, DB database path. By default foreign key constraints are enabled for SQLite connections. If you would like to disable them, you should set the DB foreign keys environment variable to false. Note, if you use the Laravel installer to create a Laravel application and select SQLite as
database, Laravel will automatically create a database SQLite file for you and run the default migrations. Microsoft SQL Server Configuration. To use a Microsoft SQL Server database, you should ensure that you have the SQL Server and PDO SQL Server PHP extensions installed, as well as any dependencies that may require such as the Microsoft SQL ODBC driver. Configuration using URLs.
Typically, database connections are configured using multiple connections values such as host, database, username, password, etc. Each of these configuration values has its own corresponding environment variable. This means that when configuring your database connection information on a production server, you need to manage several environment variables. Some managed database providers such as AWS and Heroku provide every single database URL that contains all the connection
information for the database in a single string. An example database URL may look something like mysql rootpassword at 127.0.0.1 slash forge. These URLs typically follow a standard schema convention. For convenience, Laravel supports these URLs as an alternative to configuring your database with multiple configuration options. If the URL or corresponding db underscore URL environment variable configuration option is present, it will be used to extract the database
connection and credential information. Read and write connections. Sometimes you wish to use one database connection for select statements and another for insert, update, and delete statements. Laravel makes this a breeze and the proper connections will always be used whether you are using raw queries, the query builder, or the eloquent ORM. Note that three keys have been added
to the configuration array, read, write, and sticky. The read and write keys of array values containing a single key, host, and the rest of the database connections for the read and write connections will be merged from the main MySQL configuration array. You only need to place items on the read and write arrays if you wish to override the values from the main MySQL array. So in this case, 192.168.1.1, which is in the write host array, will be used as the host for the read connection, while 192.168.1.3 will be used for the write connection.
database credentials, prefix, character set, and other options in the main MySQL array. So in this case, in the main MySQL array will be shared across both connections. When multiple values exist in the host configuration array, a database host will be randomly chosen for each request. The sticky option. The sticky option is an optional value that can be used to allow the immediate reading of records that have been written to the database during the current request lifecycle.
So if the sticky option is enabled and a write operation has been performed against the database during the current request cycle, any further read operations will use the write connection. This ensures that any data written during the request cycle can be immediately read back from the database during that same request. If it's up to you, it is up to you to decide if this is the desired behavior for your application. Running SQL queries.
Once you have configured a database connection, you may run queries using the dbFaçade. The dbFaçade provides methods for each type of query. Select, update, insert, delete, and statement. Running a select query. To run a basic select query, you may use the select method on the dbFaçade. The first argument passes the select method to the SQL query, while the second argument is any parameter bindings that need to be bound to the query.
typically these are the values of the where clause constraints. Parameter binding provides protection against SQL injection. The select method will always return an array of results. Each result within the array will be a PHP STD class object representing a record from the database. Selecting scalar values. Sometimes your database query may result in a single scalar value instead of being acquired to retrieve the query scalar result from a record object. Laravel allows you
to retrieve this value directly using the scalar method. So burgers db scalar, then you can select count case from food equals burger, then one end is burgers from many. Selecting multiple result sets. If your application calls stored procedures that return multiple result sets, you may use the select result sets method to retrieve all the result sets returned by the stored procedure.
using named bindings. Instead of using question mark to represent your parameter bindings, you may execute a query using named bindings. So dbselect, select star from users where id equals colon id. Running an insert statement. To execute an insert statement, you may use the insert method on the dbfaçade. Like select, this method accepts the SQL query as its first argument
and bindings as its second argument. Running an update statement. The update method should be used to update existing records in the database. The number of rows affected by the statement is returned by the method. Running a delete statement. The delete method should be used to delete records from the database. Like update, the number of rows affected will be returned by the method. Running a general statement. Some database statements do not return any value. For these
types of operations, you may use the statement method on the dbFaçade. So dbStatementDroptable users. Running an unprepared statement. Sometimes you may want to execute a SQL statement without binding any values. You may use the dbFaçade's unprepared method to accomplish this. So dbUnprepared updateUserSetVotes equals 100 where name equals trees. Implicit commits. When using the dbFaçade
statement and unprepared methods within transactions, you must be careful to avoid statements that cause implicit commits. These statements will cause the database engine to indirectly commit the entire transaction, leaving Laravel unaware of the database's transaction level. An example of such a statement is creating a database table. Please refer to the MySQL manual for a list of all statements that trigger implicit commits. Using multiple database connections. If your application
defines multiple connections in your config database.php configuration file, you may access each connection via the connection method provided by the db facade. The connection name passed to the connection method should correspond to one of the connections listed in your config database.php configuration file or configured at runtime using the config helper. You may access the raw
underlying PDO instance of a connection using the get PDO method on a connection instance. Listening for query events. If you would like to specify a closure that is invoked for each SQL query executed by your application, you may use the DBFaçade's listen method. This method can be useful for logging queries or debugging. You may register your query listener closure in the the boot method of a service provider.
Monitoring cumulative query time. A common performance bottleneck of modern web applications is the amount of time they spend querying databases. Thankfully, Laravel can invoke a closure or callback of your choice when it spends too much time querying the database during a single request. To get started, provide a query time threshold in milliseconds and closure to the when querying for longer than method. You may invoke this method in the boot method of a service provider.
Database transactions. You may use the transaction method provided by the DB facade to run a set of operations within the database transaction. If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown. If the closure executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method.
Handling deadlocks. The transaction method accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs. Once these attempts have been exhausted, an exemption will be thrown. Manually using transactions. If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the begin transaction method provided by the DB facade. You can roll back the transaction via the rollback method. Lastly, you can commit a
transaction via the commit method. Connecting to the database CLI. If you would like to connect to your database's CLI, you may use the DB artisan command. If needed, you may specify a database connection name to connect to a database connection that is not the default connection. Inspecting your databases. Use the db show and dbtable artisan commands. You can get valuable insight into your database and its associated tables. To see an overview of your database,
including its size, type, a number of open connections, and a summary of its tables, you may use the db show command. You may specify which database connection should be inspected by providing the database connection name to the command via the database options, a dash dash database. If you would like to include table row counts and database view details within the option output of the command, you may provide the dash dash counts and dash dash views options respectively. On large
databases, retrieving row counts and view details can be slow. In addition, you may use the following schema methods to inspect your database. So tables schema get tables, view schema get views. If you would like to inspect a database connection that does not your application's default connection, you may use the connection method. Table overview. If you would like to get an overview of an individual table within your database, you may execute the dbtable artisan command. This command
provides a general overview of a database table, including its columns, types, attributes, keys, and indexes. Monitoring your databases. Using the db monitor artisan command, you can instruct Laravel to dispatch and illuminate database events database busy event if your database is managing more than a specified number of open connections. To get started, you should schedule the db monitor command to run every minute. The command accepts the names of the database
connecting configurations that you wish to monitor as well as the maximum number of open connections that should be tolerated before dispatching an event. Scheduling this command alone is not enough to trigger a notification alerting you the open number of connections. When the command encounters a database that has an open connection count that exceeds your threshold, a database-busy event will be dispatched. You should listen for this event within your application's app service provider in order to send a notification to you or to your development team.
database query builder introduction Laravel's database query builder provides a convenient fluent interface to creating and running database queries it can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems the Laravel query system uses PDO parameter binding to protect your application against SQL injection attacks there is no need to clean or sanitize strings passed to the query builder
as query bindings. Running database queries. Retrieving all users from a table. You may use the table method provided by the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally retrieve the results of the query using the git method. So users dbtable, user's git. The git method returns an illuminate support collection instance containing the
results of the query where each result is an instance of the php std class object. You may use or you may access each column's value by accessing the column as a property of the object for each user's user echo username. Laravel collections provide a variety of extremely powerful methods for mapping and reducing data. For more information on Laravel collections, check out the collection documentation. Thankfully, we've already read that.
Retrieving a single row column from a table. If you just need to retrieve a single row from a database table, you may use the dbFaçades first method. This method will return a single std class object. So user dbtable, users where, name john first, return user email. If you don't need an entire row, you may extract a single record, single value from a record using value method. This method will return the value of the common column directly.
To retrieve a single row by its ID column value, use the find method. So dbtable users find three. If you would like to retrieve an illuminate support collection instance containing the values of a single column, you may use the pluck method. In this example, we'll retrieve a collection of user titles. So dbtable users pluck title. You may specify the column that the resulting collection should use as its keys
by providing a second argument to the pluck method. So dbtable users pluck title and name. Chunking results. If you need to work with thousands of database records, consider using the chunk method provided by the db facade. This method retrieves a small chunk of the results at a time and feeds each chunk into a closure for processing, for example, that's retrieved the entire users table in chunks of 100 records at a time. So dbtable users order
by ID chunk 100 with the function of a callback. You may stop further chunks from being processed by returning false from that function closure. If you are updating database records while chunking results, your chunk results could change in unexpected ways. If you plan to update the retrieved records while chunking, it is always best to use the chunk by ID method instead. This method will automatically paginate
the results based on the record's primary key. Streaming result lazily. The lazy method works similarly to the chunk method in the sense that it executes the query in chunks. However, instead of passing a chunk into a callback, the lazy method returns a lazy collection, which lets you interact with the results as a single stream. Once again, if you plan to update the retrieved results while iterating over them, it is best to use the lazy by ID or lazy by ID description
DESC methods instead. These methods will automatically paginate the results based on the record's primary key. Aggregates. The query builder also provides a variety of methods for retrieving aggregate values like count, max, min, average, and sum. You may call any of these methods after constructing your query. Of course, you may combine these methods with other clauses to fine-tune how your aggregate value is calculated. So DB table orders where finalized
is one average price. Determine if records exist. Instead of using the count method to determine if any records exist that match your query's constraints, you may use the exists and doesn't exist methods. Select statements. Specifying a select clause. You may not always want to select all columns from a database table. Using the select method, you can specify a custom select clause for the query. So DB table users select name and email as user email. The distinct
method allows you to force the query to return distinct results. So dbtable users distinct kit. If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method. Raw Expressions. Sometimes you may wish to insert an arbitrary string into a query. To create a raw string expression, you may use the raw method
provided by the dbFaçade. Raw methods. Instead of using the dbraw method, you may also use the following methods to insert a raw expression into various parts of your query. Remember, Laravel cannot guarantee that any query using raw expressions is protected against SQL injection vulnerabilities. Selectraw can be used in place of add select dbraw. This method accepts an optional array of bindings as its second argument. Whereraw and or whereraw methods can be used to inject a
raw where clause into your query. These methods accept an optional array of bindings as their second argument. Having raw or having raw. The having raw and or having raw methods may be used to provide a raw string as the value of the having clause. These methods having an optional array of bindings as their second argument. Order by raw. The order by raw method may be used to provide a
raw string as the revalue of the order by clause. Group by raw. The group by raw method may be used to provide a raw string as the value of the group by clause. Joins. Inner join clause. The query builder may also be used to add clauses to your queries. To perform a basic inner join, you may use the join method on a query builder instance. The first argument passed to the join
method is the name of the table you need to join to while the remaining arguments specify the column constraints on the join. You may even join multiple tables in a single query. So dbtable users, join contacts, join orders, select users. Left join, right join clause. If you would like to perform a left join or a right join instead of an inner join, use the left join or right join methods. These methods have the same signature as the join method. Cross join clause. You may use the
cross-join method to perform a cross-join clause. Cross-join generates a Cartesian product between the first table and the join table. Advanced join clause. You may also specify more advanced join clauses. To get started, pass a closure as the second argument to the join method. The closure will receive an illuminate database query join clause instance, which allows you to
to specify constraints on the join clause. If you would like to use a where clause on your joins, you may use the where and or where methods provided by the join clause instance. Instead of comparing two columns, these methods will compare the column against the value. So join contacts function join on, users ID is equal to contacts dot user ID. Subquery joins. You may use the join sub, left join sub, and right join sub methods to join a query to a subquery. Each of these methods receives three arguments. The subquery, the
That's table alias and closure that defines the related columns. In this example, we will retrieve a collection of users where each user record also contains the created at timestamp of the user's most recently published blog posts. So dbtable post, select user ID, where dbraw is max created at, at last post created at, and then where is published true, grouped by user ID. And then conjoined sub for those latest posts. Lateral joins.
You may use the join lateral and left join lateral methods to perform a lateral join with a subquery. Each of these methods receives two arguments, the subquery and its table alias. The join conditions should be specified within the where clause of the given subquery. Lateral joins are evaluated for each row and can reference columns outside the subquery. In this example, we will retrieve a collection of users as well as the user's three most recent blog posts.
user can produce up to three rows in the results set, one for each of their most recent blog posts. The join condition is specified with a where column clause within the subquery referencing the current user row. Unions. The query builder also provides a convenient method to union two or more queries together. For example, you may create an initial query and use the union method to union
it with more queries. In addition to the union method, the query builder provides a union all method. Queries that are combined using the union all method will not have the duplicate results removed. The union all method has the same method signature as the union method. Basic where clauses. Where clauses. You may use the query builder's where method to add where clauses to the query. The most basic call to the where method requires three arguments. The first argument is the name
of the column. The second argument is an operator, which can be any of the database's supported operators. And the third argument is the value to compare against the column's value. For example, the following query retrieves users where the value of the votes column is equal to 100 and the value of the age column is greater than 35. So dvtable users where votes is equal to 100, where age is greater than 35, git. For convenience, if you want to verify that a column is equal to a
to a given value, you may pass the value as the second argument to the where method. Laravel will assume you would like to use the equal operator. So, users dbtable, users where votes, comma, 100 get. As previously mentioned, you may use any operator that is supported by your database system. You may also pass an array of conditions to the where function.
Each element of the array should be an array containing the three arguments typically passed to the where method. Or where clauses. When chaining together calls to the query builder's where method, the where clauses will be joined together using the and operator. However, you may use the or where method to join a clause to the query using the or operator. The or where method accepts the same arguments as the where method.
If you need to group an OR condition within parentheses, you may pass a closure as the first argument to the OR WHERE method. So, users DB table WHERE votes is greater than 100, OR WHERE function, pass in a builder query to query WHERE name is Abigail WHERE votes is greater than 500. The example above will produce the following SQL. So, select star from users WHERE votes is greater than 100, OR in the parentheses. WHERE NOT clauses.
The where not and or where not methods may be used to negate a given group of query constraints. For example, the following query excludes provides that are on clearance or which have a price that is less than 10. So DB table products, where not function, query where clearance is true or where price is less than 10. Where any or all clauses. Sometimes you may need to apply the same query constraints to multiple columns.
For example, you may want to retrieve all records where any columns in a given list are like a given value. You may accomplish this as you may wear any method. Wear any name, email, phone, like, example. The query above will result in the following SQL. So select star from users where active equals true and name like example or email like example, for example. Similarly, the where all method may be used to retrieve records
where all the given columns match a given constraint. So postdb table where publish is true where all title content is like Laravel. The query above will result in the following SQL. Select star from post where publish equals true and title like Laravel and content like Laravel.
JSON where clauses. Laravel also supports querying JSON column types on databases that provide support for JSON column types. Currently, this includes MySQL 8.0+, PostSQL 12.0+, SQL Server, and SQLite with the JSON 1 extension. So query a JSON column, use the arrow operator. So users DB table, where preferences, dining, meal, salad.
You may use whereJSONContains to query JSON arrays. If your application uses the MySQL or PostSQL databases, you may pass an array of values to the whereJSONContains method. You may use whereJSONLength method to query JSON arrays by their length. Additional where clauses. WhereBetween or whereBetween. The whereBetween method verifies that a column's value is between two values. WhereNotBetween method verifies that a column's value lies outside two values.
The where between columns method provides that a column's value is between the two values of two columns in the same table row. So dbTable, where between columns, weight, minimum allowed weight, and maximum allowed weight. The where not between columns method provides that a column's value lies outside the two values of two columns in the same table row. The where in method verifies that a given column's value is contained within the given array.
The WHERE NOT IN method verifies that the given column's value is not contained in the given array. You may also provide a query object as the WHERE IN method's second argument. The example above will produce the following SQL. Select star, so DBTable, users, select ID, where is active 1, and then DBTable, WHERE IN, user ID is the $active users.
where null, where not null, or where null, or where not null. The where null method verifies that the value of the given column is null. The where not null method verifies that the column's value is not null. The where date method may be used to compare a column's value against the date. The where month method may use to compare a column's value against a specific month. The where day method may be used to compare a column's value against a specific day of the month.
The where year method may be used to compare a column's value against a specific year. So where year created at 2016. The where time method may be used to compare a column's value against a specific time. Where column slash or where column. The where column may be used to verify that two columns are equal. You may also pass a comparison operator in the where column method. So greater than or less than.
You may also pass an array of column comparisons to the where column method. These conditions will be joined using the AND operator. So dbtable where column, first name is equal to last name, updated at is greater than created at. Logical grouping. Sometimes you may need to group several where clauses within parentheses in order to achieve your query's desired logical grouping. In fact, you should generally always group calls to the or where method in parentheses
in order to avoid unexpected query behavior. To accomplish this, you may pass a closure to the WHERE method. As you can see, passing a closure into the WHERE method instructs the query builder to begin a constraint group. The closure will receive a query builder instance which you can use to set the constraints that should be constrained within the parentheses group. The example above, the dbtable WHERE function, QUERY WHERE or WHERE will produce
the following SQLs, like star from users where name is John and votes is greater than 100 or title is equal to admin. Advanced where clauses. Where exists clauses. The where exist method allows you to write where exist SQL clauses. The where exist method accepts a closure which will receive a query builder instance, allowing you to define the query that should be placed inside of the exists clause.
Alternatively, you may provide a query object to the where exists method instead of a closure. Sometimes you may need to construct a where clause that compares the results of a subquery to a given value. You may accomplish this by passing a closure and a value to the where method. For example, the following query will retrieve all users who have a recent membership of a given type. So user where query select from membership where column order by descending limit.
Or you may need to construct a WHERE clause that compares a column to the result of a subquery. You may accomplish this by passing a column operator enclosure to the WHERE method. For example, the following query will retrieve all income records where the amount is less than average. So incomes where amount is less than function builder query, query select raw average from incomes as I. Full text WHERE clauses.
The WHERE full text and OR WHERE full text methods may be used to add full text WHERE clauses to a query for columns that have full text indexes. These methods will be transferred into the appropriate SQL for the underlying database system by Laravel. For example, a match against clause will be generated for applications utilizing MySQL. ORDERING The ORDER BY method allows you to sort the results of the query by a given column. The first argument accepted by the ORDER BY method should be the column you wish to sort
by, while the second argument determines the direction of the sort and may be either ASC ascending or DESC descending. To sort by multiple columns, you may simply invoke to order by as many times as necessary. The latest and oldest methods. The latest and oldest methods allow you to easily order results by date. By default, the result will be ordered by the tables created at
column or you may pass the column name that you wish to sort by. The in random order method may be used to sort the query results randomly. For example, you may use this method to fetch a random user. Removing existing orderings. The reorder method removes all of the order by clauses that have previously been applied to the query. You may pass a column and direction when calling the
the reorder method in order to remove all existing order by clauses and apply an entirely new order to the query. Grouping. As you might expect, the group by and having methods may be used to group the query results. The having methods signature is similar to that of the where method. So dbtable users group by account ID having account ID greater than 100. You can use the having between method
to filter the results with the given range. You may pass multiple arguments to the group by method to group by multiple columns. To build more advanced halving statements, see the halving raw method. The skip and take methods to limit the number of results returned from the query or to skip a given number of results in the query. So dbtable user skip 10 take 5. Alternatively, you
can, you may use the limit and offset methods. These methods are functionally equivalent to the take and skip methods respectively. Conditional clauses. Sometimes you may want certain query clauses to apply to a query based on another condition. For instance, you may only want to apply a where statement if a given input value is present on the incoming HTTP request. You may accomplish this using the win method. The win method only executes
the given closure when the first argument is true. If the first argument is false, the closure will not be executed. So in the example above, so when role function query where role id is role, the closure given to the win method will only be invoked if the role field is present on the incoming request and evaluates to true. You may pass another closure as the third argument to the win method. This closure will only execute if the first argument evaluates as false.
Insert statements. The Query Builder also provides an insert method that may be used to insert records into the database table. The insert method accepts an array of column names and values. You may insert several records at once by passing an array of records. Array of arrays. Each array represents a record that should be inserted into the table. The insert or ignore method will ignore errors while inserting records into the database.
When using this method, you should be aware that duplicate record errors will be ignored and other types of errors may also be ignored depending on the database engine. Record errors will be ignored and other types of errors may also be ignored. For example, insert or ignore will bypass MySQL's strict mode. The insert using method will insert new records into the table while using a subquery to determine the data that should be inserted. Auto-incrementing IDs. If the table has an auto-incrementing
ID, use the insert-get-id method to insert a record and then retrieve the ID. Upserts. The upsert method will insert records that do not exist and update the records that already exist with new values that you may specify. The method's first argument consists of the values to insert or update, while the second argument lists the columns that uniquely identify records within the associated table. The method's third and final argument is an
array of columns that should be updated if a matching record already exists in the database. In the example above, so in dbtable flights, upsert, departure array, Oakland, destination, San Diego price. In the example above, Laravel will attempt to insert two records. If a record already exists with the same in departure and destination column values. Larryville will update that record's price column. Update statements. In addition to inserting
records into the database, the query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs indicating the columns to be updated. The update method returns the number of affected rows. You may constrain the update query using where clauses. Sometimes you may want to update an existing record in the database or create if no matching record exists. In this scenario,
the update or insert method may be used. The update or insert method accepts two arguments, an array of conditions by which to find the record and an array of column and value pairs indicating the columns to be updated. The update or insert method will attempt to locate a matching database record using the first arguments column and value pairs. If the record exists, it will be updated with the values in the second argument. If this record cannot be found, a new record will be
inserted with the merged attributes of both arguments. Updating JSON columns. When updating a JSON column, you should use the arrow syntax to update the appropriate key in the JSON object. This operation is supported on MySQL 5.7 and PostgreSQL 9.5 plus.
Increment and decrement. The query builder also provides convenient methods for incrementing or decrementing the value of a given column. Both of these methods accept at least one argument, the column to mollify. A second argument may be provided to specify the amount by which the column should be incremented or decremented. So dbtable increment votes. dbtable increment votes by five.
If needed, you may also specify additional columns to update during the increment or decrement operation. In addition, you may increment or decrement multiple columns at once using the increment each and decrement each methods.
Delete statements. The Query Builder's delete method may be used to delete records from the table. The delete method returns the number of affected rows. You may constrain delete statements by adding where clauses before calling the delete method. If you wish to truncate an entire table, which will remove all records from the table, and reset the auto-incrementing ID to zero, you may use the truncate method. Table truncating in Postgres.
When truncating a Postgres database, the cascade behavior will be applied. This means that all foreign key related records in other tables will be deleted as well. Pessimistic locking. The query builder also includes a few functions to help you achieve pessimistic locking. When executing your select statements, to execute a statement with a shared lock, you may call the shared lock method.
A shared lock prevents the selected rows from being modified until your transaction is complete. Alternatively, you may use the lock for update method. A for update lock prevents the selected records from being modified or from being selected with another shared lock. Debugging. You may use the DD and dump methods while building a query to dump the current query bindings and SQL.
The DD method will display the debug information and then stop executing the request. The dump method will still display the debug information but allow the request to continue executing. The dump raw SQL and DD raw SQL methods may be invoked on a query to dump the query SQL with all parameter bindings properly substituted. Database pagination. 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 a query builder and eloquent ORM 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. However, bootstrap pagination support is also available.
If you are using Tailwind's default, Laravel's default Tailwind pagination views and the Tailwind JIT engine, you should ensure your application's Tailwind.config.js files content key references Laravel's pagination views so that their Tailwind classes are not purged. Basic usage, paginating query builder results. There are several ways to paginate items.
The simplest is by using the paginate method on the Query Builder or an Eloquent Query. 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 to display per page. In this case, let's specify that we would like to display 15 items per page. So public function index, view, return view, users, dbtable, users, paginate 15. Simple pagination. The paginate method contains the total number of records matched by the query before deleting,
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 simple paginate method to perform a single efficient query. Paginating Eloquent Queries. You may also paginate Eloquent Queries. In this example, we will paginate
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, so user paginate 15. Of course, you can call the paginate method after setting other constraints on the query, such as where clauses. You may also use the simple paginate method when paginating eloquent models. Similarly, you can also use the cursor paginate method to cursor paginate eloquent models.
multiple paginations, 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 paginators will conflict. To resolve this conflict, you may pass the name of the query string parameter you wish to use to store the paginators current page via the third argument provided to the paginate, simple paginate, and cursor paginate methods.
Cursor pagination. While paginate and simple paginate 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. The method, this method of pagination is particularly well suited for large data sets and infinite scrolling user interfaces. Unlike offset based pagination, which includes a 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 the next paginated query should start paginating and the direction that it should paginate. You may create a cursor-based paginator instance via the cursor-paginate method offered by the query builder. This method returns an instance of pagination cursor-paginator.
So dbtable users order by ID cursor paginate 15. Once you've retrieved a cursor paginator instance, you may display the pagination results as you typically would when using the paginate and simple paginate methods. For more information on the instance methods offered by the cursor paginator, please consult the cursor paginator instance method documentation. Cursor versus 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 users table ordered by ID. So select star from users order by ID ascending limit 15 offset 15. But with the cursor pagination, it's select star from users where ID is greater than 15 order by ID ascending 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 simple paginate, cursor pagination can only be used to display next and previous links and does not support generating links with page numbers.
It requires that the ordering is based on at least one unique column or a combination of columns that are unique. Columns with null values are not supported. Query expressions in order by clauses are supported only if they are aliased and added to the select clause as well. Query expressions with parameters are not supported. Manually creating a paginator. Sometimes you 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, Length Aware Paginator or Cursor Aware Paginator instance, depending on your needs. The Paginator and Cursor Paginator classes do not need to know the total number of items in the results set. However, because of this, these classes do not have methods for retrieving the index of the last page. The Length Aware Paginator accepts almost the same arguments as the Paginator. However, it requires a count of the total number of items in the results set.
In other words, the paginator corresponds to the simple paginate method on the query builder. The cursor paginator corresponds to the cursor paginate method, and the length aware paginator corresponds to the paginate method. Customizing paginator URLs. By default, links generated by the paginator will match the current request URL. However, the paginators with path method allows you to customize the URI used by the paginator when generating links.
For example, if you want the paginar to generate links like htpexample.com slash admin slash users question mark page equals end, you should pass slash admin slash users to the with path method. Appending query string values. You may append query string of pagination links using the appends method. For example, to append sort equals votes to each pagination link, you should make the following call to appends.
route get users, user paginate, user appends, sort votes. You may use the with query string method if you would like to append all of the current requests query string values to the pagination links. 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. Paginate fragment users. Displaying pagination results. When calling the paginate method, you will receive an instance of length aware paginator, while calling the simple paginate method returns an instance of paginator, and finally calling the cursor paginator returns an instance of cursor paginator. These objects provide several methods that describe the results 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. So for each user as user, user name, and then in double quotes, double curly brackets, users links. The links method will render the links to the result of the pages in the results 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. 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 on each side 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. The Laravel paginator classes implement the 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. 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.
By default, the views rendered to display the pagination links are compatible with the Tailwind CSS 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. However, the easiest way to customize the pagination views is by exporting them to your views vendor directory using the vendor publish command.
So this command will place the views in your application's 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 paginators default view and default simple view methods within the boot method of your app service provider class.
Using Bootstrap, Laravel includes pagination views built into or built using Bootstrap CSS. To use these views instead of the default tailwind views, you may call the paginators use Bootstrap 4 or use Bootstrap 5 methods within the boot method of your app service provider class. Paginator and lengthware paginator instance methods. Each paginator instance provides additional pagination information via the following methods. Paginator account, paginator current page, pagination your first item, get options,
Get URL range, has pages, has more pages, items, last item, last page, next page URL, on first page, per page, previous page URL, total URL, get page name, set page name through, which accepts the callback. Cursor paginated instruments, instant methods.
Paginator count, cursor, get options, has pages, has more pages, get cursor name, items, next cursor, next page URL, on first page, on last page, per page, previous cursor, previous page URL, set cursor name, URL, which accepts a cursor instance. Database migrations. Migrations are like version control for your database,
allowing your team to define and share the application's database schema definition. If you've ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you face the problem that database migrations solve. The Laravel schema facade provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems.
Typically, migrations will use this facade to create and modify database tables and columns. Generating migrations. You may use the make migration artisan command to generate a database migration. The new migration will be placed in your database migration's directory.
Each migration file name contains a timestamp that allows Laravel to determine the order of the migrations. Laravel will use the name of the migration to attempt to guess the name of the table and whether or not the migration will be creating a new table. If Laravel is able to determine the table name from the migration name, Laravel will pre-fill the generated migration file with the specified table. Otherwise, you may simply specify the table in the migration file manually. manually. If you would like to specify a custom path for the generated migration, you may use
the dash dash path option when executing the make migration command. The given path should be relative to your application's base path. Squashing migrations. As you build your application, you may accumulate more and more migrations over time. This can lead to your database migrations directory becoming bloated with potentially hundreds of migrations. If you
would like, you may squash your migrations into a single SQL file. When you execute the SEMA dump command, Laravel will write a schema file to your application's database schema directory. Migration structure. A migration class contains two methods, up and down. The up method is used to add new tables, database columns, or indexes to your database, while the down method should reverse the operations performed by the up method. Within both of these methods, you may use the Laravel Schema Builder
to expressively create and modify tables to learn about all of the methods available in the Schema Builder, check out its documentation. For example, the following migration creates a flights table. So table ID, table string, table string airline, and table timestamps in the up function. Setting the migration connection. If your migration will be interacting with a database connection other your application's default database connection, you should set the connection property of your
migration. Running migrations. To run all of your outstanding migrations, execute the migrate artisan command. If you would like to see which migrations have run thus far, you may use the migrate status artisan command. If you would like to see the SQL statements that will be executed by the migrations without actually running them, you may provide the dash dash pretend flag to the
migrate command. If you are deploying your application across multiple servers and running migrations as part of your deployment process, you likely do not want two servers attempting to migrate the database at the same time. To avoid this, you may use the isolated option when invoking the migrate command. When the isolated option is provided, Laravel will require an atomic lock using your acquire an atomic lock using your application's cache driver before attempting to
run your migrations. All other attempts to run the migrate command while that lock is held will not execute. However, the command will still exit with a successful exit status code. Forcing migrations to run a production. Some migration operations are destructive, which means they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the dash dash force
flag. To roll back the latest migration operation, you may use the rollback artisan command. This command rolls back the last batch of migrations, which may include multiple migration files. You may roll back a limited number of migrations by providing the step option to the rollback command. For example, the following command will roll back the last five migrations, dash dash step equals five. You may roll back a specific batch of migrations by providing the batch option to
the rollback command where the batch option corresponds to a batch value within your application's migrations database table. For example, the following command will roll back all migrations in batch three. Rollback dash dash back equals three. If you would like to see the SQL statements that will be executed by the migrations without actually running them, you may provide the dash dash pretend flag to the migrate rollback command. The migrate reset command will roll back all of your applications migrations. The migrate refresh command will
roll back all of your migrations and then execute the migrate command. This command effectively recreates your entire database. You may roll back and re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will roll back and re-migrate the last five migrations. So PHP be artisan migrate free refresh equals or dash dash step equals five. Drop all tables and migrate.
The migrate fresh command will drop all tables from the database and then execute the migrate command. By default, the migrate fresh command only drops tables from the default database connection. However, you may use the database option to specify the database connection that should be migrated. The database connection name should correspond to a connection defined in your application's database configuration file. Creating tables. To create a new database table,
use the create method on the schema facade. The create method accepts two arguments. The first is the name of the table, where the second is the closure, which receives a blueprint object that may be used to define the new table. When creating the table, you may use any of the schema builder's custom methods to define the table's columns. You may determine the existence of a table, column or index using the has table, has column, and has index methods.
Database connection and table options. If you want to perform a schema operation on a database connection that is not your application's default connection, use the connection method. In addition, a few other properties and methods may be used to define other aspects of the table's creation. The engine property may be used to specify the table's storage engine when using MySQL. It's a table engine in Odb. The car set and collation properties may be used to specify the character set and collation for the created table when using MySQL.
The temporary method may be used to indicate that a table should be temporary. Temporary tables are only visible to the current connection's database session and are dropped automatically when the connection is closed. If you would like to add a comment to a database table, you may invoke the comment method on the table instance. Table comments are currently only supported by MySQL and Postgres. The table method on the SchemaFside may be used to update existing tables. Like the create method, the table method accepts two arguments.
The name of the table and a closure that receives a blueprint instance you may use to add columns or indexes to the table. Renaming or dropping tables. To rename an existing database table, use the rename method. To drop an existing table, you may use the drop or drop if exists methods. Renaming tables before increase. Before renaming a table, you should verify that any foreign key constraints on the table
have an explicit name in your migration files instead of letting Laravel assign a convention-based name. Otherwise, the foreign key constraint name will refer to the old table name. Creating columns. The table method on the schema facade may be used to update existing tables. Like the create method, the table method accepts two arguments, the name of the table and a and a closure that receives a blueprint instance, so you may use to add columns to the table. So schema table, users, function,
an instance of blueprint with table, and then the column type. The schema builder blueprint, schema builder blueprint offers a variety of methods that correspond to the different types of columns you can add to your database tables. Each of the following methods are listed in the table below. I'm going to go through these quick.
Big increments creates an auto incrementing unsigned big int primary key equivalent column. Big integer creates a big int equivalent column. Binary creates a blob equivalent column. Utilizing MySQL MariahDB or SQL Server may pass length and fixed arguments to create var binary or binary equivalent column.
method creates a Boolean equivalent column. The car, chair, char, whatever you want to call it, method creates a char equivalent column with a given length. The date time, TZ, method creates a date time with time zone equivalent column with an optional fractional seconds precision. The date time method creates a date time equivalent column with an optional fractional seconds precision. The date method creates a date equivalent column. The decimal method creates a
decimal equivalent column with the given precision total digits and scale. The double method creates a double equivalent column. The enum method creates an enum equivalent column with the given valid values. The float method creates a float equivalent column with the given precision. The for an id method creates an unsigned big int equivalent column. The for an id for method has a column id equivalent column for a given model class. The column type will be unsigned
big int char of 36 or char of 26 depending on the model key type. Foreign ULID method creates a ULID equivalent column. The foreign UUID method creates a UUID equivalent column. The geography method creates a geography equivalent column with the given spatial types and SRID spatial reference system identifier. The geometry method creates a geometry equivalent column with the given spatial type and SRID spatial reference system identifier.
The ID method is an alias of the big increments method. By default, the method will create an ID column. However, you may pass a column name if you would like to assign a different name to the column. The increments method creates an auto incrementing unsigned integer equivalent column as a primary key. The integer method creates an integer equivalent column. The IP address method creates a varchar equivalent column. When using Postgres, an inet column will be created. The JSON method creates a JSON equivalent column.
The JSONB method creates a JSONB equivalent column. Long text creates a long text equivalent column. Utilizing MySQL or MyIDB, you may apply a binary character set to the column in order to create a long blob equivalent column. The MAC address creates a column that is intended to hold a MAC address. Some database systems, such as Postgres, have a dedicated column type for this type of data. Other database systems will use a string equivalent column.
The medium increments method creates an auto incrementing unsigned medium int equivalent column as a primary key. The medium integer method creates a medium int equivalent column. The medium text method creates a medium text equivalent column. When utilizing MySQL or MyIDB, you may apply a binary character set to the column in order to create a medium blob equivalent column. The morphs method is a convenience method that adds a column ID equivalent column and a column type varchar equivalent column.
The column type for the column ID will be unsigned big int char 36 or char 26 depending on the model key type. The method is intended to be used when defining the columns necessary for a polymorphic eloquent relationship. In the following example, taggable ID and taggable type columns will be created. So table morphs taggable. The nullable timestamps method is an alias of the timestamps method. The method is similar to the morphs method in nullable morphs.
Nullable morphs, however the columns that are created will be nullable. Nullable UUID morphs, however the columns are created will be nullable. Nullable UUID morphs is like UUID, but they will be nullable. Remember token method creates a nullable varchar 100 equivalent column that is intended to store the current Remember Me authentication token.
Auto incrementing unsigned small int equivalent column as a primary key. Small integer method creates a small int equivalent column. The soft delete. The soft delete tz method adds a nullable deleted at timestamp with time zone equivalent column with an optional fractional seconds precision.
This column is intended to store the deleted at timestamp needed for Eloquent's soft delete functionality. Soft delete method adds a millable deleted at timestamp equivalent column with an optional fractional seconds precision. This column is intended to store the deleted at timestamp needed for Eloquent's soft delete functionality. The string method creates a varchar equivalent column of the given length. The text method creates a text equivalent column. When using MySQL or MyDB, you may apply a binary character set to the column in order to create a blob
equivalent column. The timeTZ method creates a time with time zone equivalent column with an optional fractional seconds precision. The time method creates a time equivalent column with an optional seconds precision. The timestampTZ method creates a timestamp with time zone equivalent column with an optional fractional seconds precision. The timestamp method creates a timestamp equivalent column with an optional fractional seconds precision. The timestampTZ method creates treated at, created at an updated at timestamp with time zone equivalent columns with
with an optional fractional seconds precision. The timestamps method creates created at and updated at timestamp equivalent columns with an optional fractional seconds precision. The tiny increments method creates an auto incrementing unsigned tiny int equivalent column as a primary key. The tiny integer method creates a tiny int equivalent column. Tiny text method creates a tiny text equivalent column. When utilizing my SQL or MariaDB, you may apply a binary character set to the column in order to create a tiny blob equivalent column.
The unsigned big integer method creates a unsigned big int equivalent column. Unsigned integer creates an unsigned equivalent column. The unsigned medium integer creates an unsigned medium int equivalent column. The unsigned small integer creates a unsigned small int equivalent column. The unsigned tiny integer method creates an unsigned tiny int equivalent column.
The UUID morphs method is a convenience method that adds a column ID char 26 equivalent column and a column type varchar equivalent column. The UUID morphs method is a convenience method with a column ID char 36 equivalent column and a column type varchar equivalent column. The UUID method creates a UUID equivalent column. The year method creates a year equivalent column. Column modifiers.
In addition to the column types listed above, there are several column modifiers you may use when adding a column to a database table. For example, to make the column nullable, you may use the nullable method. The following table contains all of the available column modifiers. This list does not include index modifiers. After column autoincrement char set collation comment default first from invisible nullable
stored as, unsigned, use current, use current on update, virtual as, generated as, always. Default expressions. The default modifier accepts a value or an eliminate database query expression instance. Using an expression instance will prevent Laravel from wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is where you need to assign default values to JSON columns. Column order. When using the MySQL database, the after method may be used to add columns
after an existing method or existing column in the schema. Modifying columns. The change method allows you to modify the type and attributes of existing columns. For example, you may wish to increase the size of a string column. To see the change method in action, let's increase the size of the name column from 25 to 50. To accomplish this, we simply define the new state of the column and then call the change method. When modifying a column, you must explicitly include all the modifiers you want to keep on the column definition. Any missing attribute will be dropped.
For example, to retain the unsigned, default, and common attributes, you must call each modifier explicitly when changing the column. 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. Rename a column, you may use the rename column method provided by the schema builder. To drop a column, you may use the drop column method on the schema builder.
You may drop multiple columns from the table by passing an array of column names to the drop column method. Laravel provides several convenient methods related to dropping column types of columns. Each of these methods is described in the table below. The table will drop morphs, drop remember token, drop soft deletes, drop soft deletes tz, drop timestamps, drop timestamps tz. Indexes. Creating indexes. The Laravel schema builder supports several types of indexes.
The following example creates a new email column and specifies that its value should be unique. To create the index, we can chain the unique method onto the column definition. So schema, table users, table string, email, unique. Alternatively, you may create the index after defining the column. To do so, you should call the unique method on the schema builder blueprint. This method accepts the name of the column that should receive a unique index. You may even pass an array of columns to an index method to create a compound or composite index.
When creating an index, Laravel will automatically generate an index name based on the column table, column names, and the index type. But you may pass a second argument to the method to specify the index name yourself. Available index types. Laravel's Schema Builder Blueprint class provides methods for creating each type of index supported by Laravel. Each index method accepts an optional second argument to specify the name of the index. If omitted, the name will be derived from the names of the table and columns used for
the index, as well as the index type. Each of the available index methods is described in the table below. Table primary, table primary, table unique, table index, table full text, table full text with the language, and table spatial index. Renaming indexes. To rename an index, you may use the rename index method provided by the schema builder blueprint. This method accepts the current index name as its first argument and the desired name
as its second argument. Dropping indexes. To drop an index, you must specify the index's name. By default, Laravel automatically assigns an index name based on the table name, the name of the index column and the index type. Here are some examples. TableDropPrimary, TableDropUnique, TableDropIndex, TableDropFullText, TableDropSpatialIndex. If you pass an array of columns into a method that drops indexes, the conventional index
name will be generated based on the table name, columns, and index type. Foreign key constraints. Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user ID column on the post table that references the ID column on a user's table. So table inside mbig integer, user ID, table foreign, user ID references ID on users. Since this syntax is rather verbose, Laravel provides
additional tertiary methods that use conventions to provide a better developer experience. When using the foreign ID method to create your column, the example above can be rewritten like so. Table for an ID user, ID constrained. The foreign ID method creates an unsigned big integer equivalent column while the constrained method will use conventions to determine the table and
column being referenced. If your table does not match Laravel's conventions, you may manually provide it to the constrained method. In addition, the name that should be assigned to the generated index may be specified as well. You may also specify the desired action for the on delete and on update properties of the constraint. An alternative expressive syntax is also provided for these actions. So table cascade on update, restrict on update, on no action on update,
cascade on delete, restrict on delete, or null on delete. Any additional column modifiers must be called before the constraint method. To drop a foreign key, you may use the drop foreign method, passing the name of the foreign key constraint to be deleted as an argument. Foreign key constraints use the same naming convention as indexes. In other words, the foreign key constraint name is based on the name of the table and the columns in the constraint, followed by a underscore foreign
suffix. Alternatively, you may pass an array containing the column name that holds the foreign key to the drop foreign method. The array will be converted to a foreign key constraint name using Latifels constraint naming conventions. You may enable or disable foreign key constraints within your migrations by using the following methods. So that's schema enable foreign key constraints or disable foreign key constraints. Events. For convenience, each migration operation
will dispatch an event. All of the following events extend the base migration event class. Events migration started, events migration ended, events migration started, events migration ended, events schema dumped, and events schema loaded. Database seeding. Laravel includes the ability to seed your database with data using seed.
Seed classes. All seed classes are stored in the database seeders directory. By default, a database seeder 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. Writing seeders. To generate a seeder, execute the make seeder artisan command. All seeders generated by the framework will be placed in the database seeders directory. A seeder class only contains one method by default, run.
This method is called when the db seed artisan command is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data, or you may use eloquent model factories. As an example, let's modify the default database seeder class and add a database insert statement to the run method. So public function run, dbtable, users, insert, name, email, password with strings of random.
User using model factories. Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories to conveniently generate large amounts of database records. First, review the model factory documentation to learn how to define your factories. For example, let's create 50 users that each has one related post. So user factory count of 50 has posts 1 create, calling additional seeders.
Within the database seeder 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. So this call, user seeder, post seeder, common seeder. Muting model events. While running seeds, you may want to prevent models from dispatching events. You may achieve this using the without model events trait.
When used, the withoutModelEvents trait ensures no model events are dispatched even if additional seed classes are executed via the call method. Running seeders. You may execute the dbseedartisan command to seed your database. By default, the dbseed command runs the database seeder class, which may in turn invoke other seed classes. However, you may use the dash dash class option to specify a specific seeder class to run individually. You may also seed your database
using the migrate fresh command in combination with the dash dash seed option, which will drop all tables and rerun all of your migrations. This command is useful for completely rebuilding your database. The seeder option may be used to specify a specific seeder to run. Forcing seeders to run in production. Some seeding operations may cause you to alter or lose data in
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. Redis. Redis is an open source advanced key value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and sorted sets. Before using Redis of Laravel, we encourage you to install and use the PHP Redis PHP extension via Peckl.
The extension is more complex to install compared to user LAN PHP packages, but may yield better performance for applications that make heavy use of Redis. If you are using Laravel Sale, this extension is already installed and your application is Docker container. If you are unable to install the PHP Redis extension, you may install the predis package via Composer. The predis is a Redis client written entirely in PHP and does not require any additional extensions.
Configuration. You may configure your application's Redis settings via the config database.php configuration file. Within this file, you will see a Redis array containing the Redis servers utilized by your application. So Redis client options array, default array, and cache array. Each Redis server defined in your configuration file is required to have a name, host, and a port unless you define a single URL to represent the Redis connection. So Redis client options default
Cache. Configuring the data connection scheme. By default, Redis clients will use the top scheme, or TCP scheme, when connecting to your Redis servers. However, you may use TLS slash SSL encryption by specifying a scheme configuration in your Redis server's configuration array. Clusters. If your application is utilizing a cluster of Redis servers, you should define these clusters within a clusters key of your Redis configuration. This configuration key does not exist by default, so you will need to create it within your application's config
database.php configuration file. By default, Laravel will use native Redis clustering, since the options.cluster configuration value is set to Redis. Redis clustering is a great default option, as it gracefully handles failover. Laravel also supports client-side sharding. However, client-side sharding does not handle failover. Therefore, it is primarily suited for transient cache data that is available from another primary data store. If you would like to use client-side
sharding instead of native Redis clustering, you may remove the options.cluster configuration value within your application's config.database.php configuration file. PREDIS If you would like your application to interact with Redis via the PREDIS package, you should ensure the Redis client environment variable's value is PREDIS. In addition to the default configuration options, PreDIS supports additional connection parameters that may be defined for each
of your Redis servers. To utilize these additional configuration options, add them to your Redis server configuration in your application's database.php configuration file. By default, Laravel will use the PHP Redis extension to communicate with Redis. The client that Laravel will use to communicate with Redis is dictated by the value of the redis.client configuration option, which typically reflects the value of the Redis client environment variable.
In addition to the default configuration options, PHP Redis supports the following additional connection parameters. Name, persistent, persistent ID, prefix, read timeout, retry interval, timeout, and context. You may add any of these options to your Redis server configuration in the configdatabase.php configuration file. PHP Redis serialization and compression. The PHP Redis extension may also be configured to use a variety of serializers and compression algorithms.
These algorithms can be configured via the options array of your Redis configuration. Currently, supported serializers include Redis Serializer, Redis Serializer PHP, Serializer JSON, Serializer IG binary, and Serializer MSG PAC. Supported compression algorithms include Redis compression none, compression LZF, compression ZSTD, and compression LZ4.
Interacting with Redis. You may interact with Redis by calling various methods on the Redis facade. The Redis facade supports dynamic methods, meaning you may call any Redis command on the facade and the command would pass directly to Redis. In this example, we will call the Redis git command by calling the git method on the Redis facade. So return view user profile
user redis git user colon profile. As mentioned above, you may call any of Redis's commands on the Redis facade. Laird will use magic methods to pass the commands to the Redis server. If a Redis command expects arguments, you should pass those to the facades corresponding method. Use illuminate support facades redis redis set name Taylor. Alternatively, you may pass commands
to the server using the redis facades command method, which accepts the name of the command as its first argument and an array of values as its second argument. Your application's config database configuration file allows you to define multiple Redis connections in servers. You may obtain a connection to a specific Redis connection using the RedisFacades connection method. To obtain an instance of the default Redis connection, you may call the connection method without any additional arguments. Transactions. The RedisFacades transaction method provides a
convenient wrapper around Redis's native multi and exec commands. The transaction method accepts a closure as its only argument. The closure will receive a Redis connection instance and may issue any commands it would like to this instance. All of the Redis commands issued within the closure will be executed in a single atomic transaction. Lua Scripts, the eval method provides another
method of executing multiple Redis commands in a single atomic operation. However, the eval method has the benefit of being able to interact with and inspect Redis key values during that operation. Redis scripts are written in the Lua programming language. The eval method can be a bit scary at first, but we'll explore a basic example to break the ice. The eval method expects several arguments. First, you should pass the Lua script as a string to the method. Secondly, you should pass the number
of keys as an integer that the script interacts with. Thirdly, you should pass the name of those keys. Finally, you may pass any other additional arguments that you need to access within your script. In this example, we will increment a counter, inspect its new value, and increment a second counter if the first counter's value is greater than five. Finally, we will return the value of the first counter. So value redis eval lua, local counter redis call, if counter is greater than five, then redis.call increment keys to end.
Pipelining commands. Sometimes you may need to execute dozens of Redis commands instead of making a network trip to your Redis server for each command. You may use the pipeline method. The pipeline method accepts one argument, a closure that receives a Redis instance. You may issue all of your commands to this Redis instance and they will all be sent to the Redis server at the same time to reduce network trips to the server. The commands will still be executed
in the order they were issued. PubSub. Laravel provides a convenient interface to the Redis publish, and subscribe commands. These Redis commands allow you to listen for messages on a given channel. You may publish messages to the channel from another application or even using another programming language, allowing easy communication between applications and processes. First, let's set up a channel listener using the subscribe method. We'll place this method call
within an artisan command since calling the subscribe method begins a long running process. Now we may publish messages to the channel using the publish command. Wildcard subscriptions. Using the PSubscribe method, you may subscribe to a wildcard channel, which may be useful for catching all messages on all channels. The channel name will be passed as the second argument due to the provided closure. Alright, another bathroom break.
Thank you.