YouTubestream· May 27, 2024· 9:53:24· 2,300 views on YouTube

I'm reading the entire Laravel documentation

Watch on YouTube ↗
0:00

React at a moment you like. The best moments light up here.

transcript

1159 moments
  1. for

  2. for for

  3. for

  4. for for

  5. that for

  6. for

  7. all right I think I think we are about ready so let's switch this over how's it going everyone

  8. hopefully everyone can hear me just fine um but for those tuning in this is a complete read through of the Lille documentation and I don't know if I can pull up the the Twitter comments so I don't know how that specifically works first time streaming on Twitter itself um

  9. but little bit of an echo hopefully everything sounds pretty fine um the echo might just be the room but so we'll we'll kind of we'll kind of just jump right into it um yeah we're going to be reading the uh larel

  10. documentation live on stream U if it's completely unbearable Echo let me know um but uh the goal was for me to at least have like 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 um so hopefully this works a little bit

  11. yeah I think everything's going pretty good we're going to get started so basically uh this isn't sponsored by laravel at all this is something that I you know wanted to do um mostly just to have some fun with doing this completely but then also being able to read the documentation from start to finish and just learn a little bit more about um the larabel docs that I might not have

  12. heard before or might not have been able to read before I should say too okay so um let's get into it uh what's going to happen uh EO my perfect what's going to do so what's

  13. going to happen is I'm just going to start reading the documentation um and again this is just something to be able to say hey this is like an official audio book or anything like that this is just me saying hey here's the documentation I printed out all 1,472 pages I'm going to read it start to finish I'm not going to read every single phrase every single syllable not all the code blocks and everything like that but we're just going to see how far we can get and the goal is as long as it

  14. doesn't take days the goal is to be able to read it from start to finish uh so hopefully I'll be able to learn something hopefully you'll be able to learn something and uh we'll kind of uh get going I don't know exactly how to check Twitter comments like on the on the stream um I have like the broadcast

  15. window open but I don't exactly know where the comments are for that um let's see one second

  16. that for

  17. all right again hopefully you're not watching this the whole way through but the goal is to be able to uh get through as much as possible hopefully learn a little bit about the lville documentation as we go and then um I don't know I don't know where the like actual comments show up for for Twitter but I I I I posted a post on so if you're watching on Twitter I have a post and if you comment on there then I

  18. will be able to see it better um but for those watching on YouTube I do see your comments looks like everything's going fairly fairly well and uh let's get going this is larel 11x offline documentation I found a GitHub repo to print these off

  19. um there's preface for why this PDF create 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 Laro and its other first party packages follow semantic versioning major framework releases are released every year while minor and Patch releases may be released

  20. as often as every week minor and Patch releases should never contain breaking changes when referencing the larl framework or its components from your application package you should always use a version constraint such as 11.0 since major releases of larel 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

  21. to remain function arguments when necessary in order to improve the Layel code base therefore using named arguments when calling laral methods should be done cautiously and with the understanding that the parameter names may change in the future for all larel releases bug fixes are provided for 18 months and security fixes are provided for 2 years for all additional libraries including Lumen only the latest major release fixes release receives bug fixes in addition please review the database

  22. version supported by larl larl 11 larl 11 continues the improvements made in larl 10ox by introducing a streamlined application structure per second rate limiting Health routing graceful encryption key rotation Q testing improvements resend mail transport prompt validator integration new Artisan commands and More in addition Lille Reverb first party scalable websocket server has been introduced to provide robust real-time

  23. capabilities to your applications PHP 8.2 laravel 11xp version of 8.2 streamlined application structure larl streamlined application structure was de developed by Taylor otwell and Nuno Maduro larl 11 introduces a streamlined application structure for new Lille applications without requiring any changes to existing applications the new application structure is intended to provide a leaner more modern experience

  24. while retaining many of the concepts that LEL developers are already familiar with below we will discuss the highlights of lille'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 highlevel application Behavior settings that were previously scattered throughout your application's file

  25. structure uh return application configure with routing with middleware with exceptions create service providers instead of the default larel application structure containing five service providers larl 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

  26. 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 root M route route model bindings are authorization Gates you may have previously registered in the off service provider may also be registered in the app service provider opin API and broadcast routing the api.php and channels. PHP route files are no longer present by default as many applications

  27. do not require these files instead they may be created using simple Artisan commands PHP Artisan install API PHP Artisan install broadcasting middleware previously new laral applications included nine middleware these middleware performed a variety of tasks such as authenticating requests trimming input strings and validating csrf tokens and larl 11 these middleware have been moved into the framework itself so that they do not add bolt to your application structure new methods for customizing

  28. the behavior of these middleware have been added to the framework and may be invoked from your application bootstrap app.php file with middleware function middleware middleware validates csrf tokens middleware web Etc since all middleware can be easily customized via your applications bootstrap app.php the need for a separate HTTP kernel class has been eliminated scheduling using a new

  29. schedule facade scheduled tasks now can be find directly in your applications 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 bootstrap app.php file instead of a separate exception Handler class reducing the overall number of files included a new in a new

  30. Lille application for example with exceptions exceptions report base controller class the base controller included in new larel applications has been simplified it no longer extends Lil'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 Lille applications use

  31. sqlite for database storage as well as the database driver for Lille session cache and Q this allows you to begin building your application immediately after creating a new Lille application without being required to install additional software or create additional database migrations in addition over time the database drivers for these larel Services have become robust enough for production usage in many application contexts therefore they provide a sensible unified choice for both local

  32. and production applications LEL Reverb LEL Reverb was developed by Joe Dixon LEL Reverb begins brings blazing fast and scalable real time webs communication directly to your Lille application and provides seamless integration with laravel's existing Suite of event broadcasting tools such as larel Echo PHP Artisan Reverb start in addition Reverb supports horizontal scaling via Red's publish/subscribe

  33. capabilities allowing you to distribute your websocket traffic across multiple backend Reverb servers all supporting a single high demand application for more information on larel reverb please consult the complete Reverb documentation per second rate limiting per second rate limiting was contributed by Tim McDonald larel now supports per second rate limiting for all rate limiters including those for HTTP requests and Q jobs previously lille's rate limiters were limited to per minute

  34. granularity so rate limiter for invoices function return limit per second for more information on rate limiting in larel check out the rate limiting documentation Health routing Health routing was contributed by Taylor otwell new larel Liv applications include a health routing directive which instructs larel to Define a simple health check endpoint that may be invoked by thirdparty application Health modering Services or orchestration systems like

  35. kubernetes by default this route is served at slup with routing web directory commands Health slup when HTTP requests are made to this route Lille 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

  36. session cookie every request to a laral 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 larel 11 allows you to find

  37. your application's previous encryption Keys as a comma delimited lists via the app previous Keys environment variable when encrypting VAR values larvo will always use the current encryption key which is within the app key environment variable when decrypting values lar will first provide 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

  38. keep using your application uninterrupted even if your encryption key is rotated for more information on encryption and lville check out the encryption documentation automatic password rehashing was contributed by Steven ree Carter lille'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

  39. be increased over time as CPU GPU processing power increases if you increase the bcrypt work factor for your application Lara will now gracefully and automatically rehashed user passwords as users authenticate with your application prompt validation prompt validator integration was contributed by Andreas Marco Satori LEL promps is a PHP package for adding beautiful I'm sorry Andrea Andrea Marco Satori larvo promps is a PHP package for

  40. adding beautiful and userfriendly forms to your command line applications with browser-like features including placeholder text and validation larvo prompt supports input validation via closures so name text you have a label you have validate string length Etc however this can become cumbersome when dealing with many inputs or complicated validation scenarios therefore in Lille 11 you may utilize the full power of lille's validator when validating prompt

  41. inputs so name text name required men 3 Max 255 Q interaction testing Q interaction testing was contributed by Taylor otwell previously attempting to test that a q job was released deleted or manually failed was cumbersome and required the definition of custom Q fakes and stubs however and laral 11 you may easily test for these Q interactions using the with fake Q interactions

  42. method so job job handle job assert released with fake CU interactions new Artisan commands class creation artistan commands were contributed by Taylor otwell new Artisan commands have been added to allow the quick creation of classes enums interfaces and traits PHP artisan make class PHP artisan make enum PHP artisan make interface PHP artisan make model casts improvements model cast improvements were contributed by Nuno

  43. Maduro laral 11 supports defining your models 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 El eloquent documentation the once function the once helper was contributed by Taylor otwell and Nuno Maduro the once helper function execute Utes the given call back and

  44. caches the result in memory for the duration of the requests any subsequent call so the once function with the same call back will return the previously cached result so function random return once for more information on the one helper check out the helper's documentation improve performance when testing with in-memory databases improved in-memory database testing performance was contributed by Anders jembo larvo 11 offers a significant

  45. speed boost when using the memory sqlite datab during testing to accomplish this L 11 now maintains a reference to php's pedo object and reuses it across connections often cutting total test runtime in half improve support for mariadb improved support for Marb was contributed by yonas ster and Julius kickbush Lara 11 includes improved support for Mari DB in previous Lara releases you could use Mari DB via lal's

  46. MySQL driver however laral 11 now includes a dedicated Maria DB driver which provides better defaults for this database system for more information on lel's database drivers check out the database documentation inspecting databases and improved schema configurations operations improved schema operations and database inspection was contributed by Haz dandari lvo 11 provides additional database schema operation and inspection methods including the native modifying

  47. renaming and dropping of columns for their more advanced spatial types non-default schema types and Native schema methods for manipulating tables views columns index and foreign keys are provided so use eliminate tables schema get tables schema get views get columns get indexes get forign keys upgrade guy uh skipping the terms of table of content so upgrading to 11.0 from 10 pointx estimate upgrade time 15

  48. minutes no 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 Lille shift to help a your application upgrades updating dependencies likelihood of impact High PHP 8.20 required lell now requires PHP 8.20 or greater Cur Cur curl 7.34 point0 required lille's HTTP client now

  49. requires curl 7.34 point0 or greater composer dependencies you should update the following dependencies in your application composer. Json file LL framework to 11 n Maduro Collision to 0.1 or 8.1 Leo Breeze to 2. 0 if installed Lille cashier to 15.0 if installed lville Dusk to 8.0 if

  50. installed Lille jet string to 5.0 if installed octane to 2.3 if installed passport to 12.0 if installed syum to 4.0 if installed spark stripe to 5.0 if installed telescope to 5.0 if installed inertia JS inertia laral to 1.0 if installed if your application is using lville cashier stripe passport sanctum spark stripe or telescope you will need to publish the migrations to your application cashier stripe passport sanctum spark stripe and Telescope no

  51. 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 artist and 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 larel cashier stripe pass support sanctum spark stripe and Telescope if you have manually installed the Lille installer you should update the installer via

  52. composer so Lille installer 5.6 composer Global require finally you may remove the doctrine dball composer dependency if you have previously added it to your application as larel is no longer dependent on this package application structure laral 11 introduces a new default application structure with fewer default files namely new larl applications contain fewer service providers middleware and configuration files however we do not recommend the laral 10 applications upgraded to larvo 11 attempt to migrate their application

  53. structure as laral 11 has been carefully tuned to also support the laral 10 application structure authentication password rehashing larvo 11 will automatically rehash your user's passwords during authentication if you're 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 hash in.php configuration

  54. file rehash on login false the user provider contract likelihood of impact low the illuminate contracts off the user provider contract has received a new rehash password if required method this method is responsible for rehashing and storing the user's password and 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

  55. reference implementation can be found within the illuminate off eloquent user provider class so public function rehash password if required authenticatable user go Force equals false so the authenticatable contract likelihood of impact low the illuminate contracts off authenticatable contract has received a new get off password name method this method is responsible for returning the name of your authenticatable entity's password column

  56. if your application or package defines a class that implements this interface you should add the new get off password name method to your implementation so public function get off password name return password the default user model included with larel receives this method automatically since the method is included with the illuminate off authenticatable trait the authenticate authentication exemption class likelihood of impact very low the redirect to method of the illuminate off authentication exception class now

  57. requires an illuminate HTTP request instance as its first argument if you are manually catch catching this exception and calling the redirect tun method you should update your code accordingly if instance of of authentication exception path redirect to Cache cash key prefixes likelihood of impact very low previously if a cash key prefix was defined for the Dynamo DB MIM cach to R to Cache stores lville would

  58. append a colon a semicolon to prefix in Lille 11 the cash key prefix does not receive the semicolon suffix if you would like to maintain the previous prefixing Behavior you may you can manually add the semicolon the colon suffix to your cach key prefix collections the innumerable contract likelihood of impact low the dump method of the illuminate support inumerable

  59. contract has been updated to accept a ver vartic arguments Arc if you are implementing this interface you should update your implementation accordingly public function dump args database sqlite 3.35 point0 plus likelihood of impact I if your application is utilizing a sqlite database sqlite 3.35 point0 or greater as required eloquent model casts method likelihood of impact low the base eloquent model class now

  60. defines a casts method in order to support the definition of attribute casts if one of your application model is defined 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 common attributes you must call each modifier explicitly when changing the column even if those attributes have

  61. 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 common attributes so schema create users table integer votes later you write a migration that changes the column to be nullable as well so table inor votes nullable change in LEL 10 this migration would retain the unsigned default and comment attributes on the column however in in lval 10 excuse me however in lval 11 the migration must now also include all the attributes that

  62. 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 to add an index big increment ID primary change drop in index table care poster code unique false change if you do not

  63. 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 artison schema dump once your migrations have been squashed larl will migrate the database using your application 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 column the double and Float migration column types now creates

  64. a double equival valent column within total 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 4 byte single Precision column or as an 8 by double Precision column

  65. 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 unsign 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 there however if you wish to continue using the deprecated unsigned attribute for these column types you may change the chain the unsigned method onto the

  66. columns definition so table decimal unsigned table double unsigned table float unsigned dedicated Mariah DB driver likelihood of impact very low instead of always utilizing the MySQL MySQL driver when connecting to mariia DB databases larvo 11 adds a dedicated database driver for Mar DB if your application connects to a Mariah DB database you may update the connection

  67. configuration to the new Mariah DB driver to benefit from Mari DB specific features in the future so driver Mari DB currently the new Mari driver behaves like the current MySQL driver with one exception the uid schema Builder method creates native uid columns instead of car 36 columns if your existing migrations utilize the uid schema Builder method and you choose to use the numer DB databased driver you should update your migrations invocations of

  68. the uid method to car to avoid breaking changes or unexpected Behavior so schema table table car spatial types likelihood of impact low the spatial column types of database migrations have been written to be consistent across all databases therefore you may remove point line string polygon geometry collection multi-point multi-line string multi- polygon and multipolygon Z methods from your migrations and use geometry or geography methods instead so table geography table geometry to explicitly

  69. restrict the type or the spatial reference system identifier for values stored in the column on my SQL my mariet B and postgress SQL you may pass the subtype and SRI ID method to the method so table geometry dimension subtype S ID the G is geometry and projection column modifiers of the post postgress grammar have been removed accordingly Doctrine dball removal likelihood of impact low the following lists of Doctrine dball related classes and methods have been

  70. removed laral 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 as 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

  71. type PDO directory timestamp type class change column class rename column class grammar get Doctrine table diff method in addition registering custom Doctrine types via dball do types in your applications database configuration file is no longer required if you are previously using Doctrine debal to inspect your database and it's Associated tables you may use lel's new native schema methods schema get tables schema get columns get indexes get

  72. forign 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 lville native schema get tables get views and get types methods when using postgres and SQL Server none of the new schema methods will accept three-part reference EG database. schema. table therefore you should use connection to declare the database instead so schema connection

  73. 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 deall equivalent type database connection interface likelihood of impact very low the illuminate database connection interface method interface has received a new scalar method if you are defining your own implementation of this interface you should add the scaler method to your

  74. implementation so public function scaler dates carbon 3 likelihood of impact medium Lille 11 supports both Carbon 2 and carbon 3 carbon is a date manipulation Library utilized extensively by Lille and packages throughout the ecosystem if you upgraded harbon 3 be aware that diffin methods now return floating Point

  75. numbers and may return negative values to indicate time Direction which is a significant change from Carbon 2 review carbon's change log for detailed information on how to handle these and other changes mail the mailer contract likely to have impact very low the illuminate contracts mail mailer contract has received a new send now method if your application or package is manually implementing 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

  76. like ctive impact very low if you have written a larvel package then manually publishes the service provider to the applications app providers directory 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 ad provider to bootstrap file method the ad 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

  77. configuration file in new larvo 11 applications so service provider add provider to bootstrap file cues the batch repository interface like of impact very low but the illuminate bus batch Repository interface has received a new roll back method if you are implementing this interface within your own package or application you should add this new method to your implementation public function roll back synchronous jobs in database transactions likely of impact very low previously synchronous jobs jobs using

  78. the sync Q driver would execute immediately regardless of whether the after commit configuration option of the Q connection was set to true or the after commit method was invoked on the job in Lille 11 synchronous Q jobs will now respect the after commit configuration of the Q connection or job rate limiting per second rate limiting likel of impact medium like there have 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

  79. 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 instructure Constructor now accepts seconds instead of minutes all documented usage of this cases are limited to static instructure such as limit per minute limit per second however if you are instant instantiating this class manually you should update your application to provide seconds to the classes and constructure so new limit key attempts 2 * 60 the limit

  80. classes Decay minutes property has been renamed to Decay seconds and now contains seconds instead of minutes the illuminate middleware throttle exceptions middleware throttles exceptions with reddis class instructors now accept seconds instead of minutes so new throttle exception two attempts exceptions with reddis attempts cashier stripe updating cashier stripe likelihood of impact High therefore 11 no longer supports cashier stripe 14x therefore you should update your applications Lille cashier stripe

  81. dependency to 15.0 in your composer. Json file cashier stripe 16 15.0 no longer automatically loads migrations from its own migrations directory instead you should run the following command publish cashier Stripes migrations to your application PHP Artisan vendor publish tag cashier migrations please review the complete cashier stripe upgrade guide for additional breaking changes spark stripe updating spark stripe likelihood of impact High larvo 11 no longer Sports larvo spark stripe 4.x therefore you

  82. should update Lars application spark Stripes dependency to 5.0 in your composer. Json file spark stripe 5.0 no longer automatically loads migrations from its own migrations directory instead you should run the following command to publish spark Stripes migration to your application vendor publish spark migrations L of 11 Sports oh next please review the complete spark stripe upgrade guide for additional

  83. breaking changes passport updating pass passport likelihood of impact High Lille 11 no longer supports laral passport 11x therefore you should update your laral application Lille 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 passports migrations to your application so Artisan vendor publish passport migrations in addition the passport Grant type is disabled by default you may enable it by invoking the enable

  84. password Grant method and the boot method of your application's app service provider passport enable password Grant sanctum updating syum likel of impact High Lille 11 no longer supports laral syum 3.x therefore you should update your application's Lille 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 sanctums migrations to your application PHP

  85. Artisan vendor publish tag syum mations then in your application s. PHP configuration file you should update the references to the authenticate session and crypt cookies and validate csrf token middleware to the following so change them to authenticate session class and crypt cookies class and validate csrf token class telescope updating telescope likelihood of impact High larl 11 no longer Sports laral telescope 4.x therefore you should update your LEL application structure to

  86. te 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 telescopes migrations to your application PHP Artis inv vendor publish tag telescope migrations spotsy once package likely of inback medium larone 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 spoty once package you should remove it

  87. from your applications composer. Json file to avoid conflicts miscellaneous we also encourage you to view the changes in the levelt levelt GitHub repository while many of these changes are not required You may wish to keep these files in sync with your application some of of these changes 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

  88. you so contribution guide table of contents bug reports to encourage active collaboration Lille strongly encourages poll requests not just bug reports poll 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 p request 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

  89. 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 in listed in our issue trackers you must be authenticated with

  90. GitHub to view all of lel's issues if you notice improper dock block PHP stand or ID warnings while using lell do not create a GI issue instead please submit a poor request to fix the PO problem the leville source code is managed on GitHub and there are repositories for each of the Lille projects and it lists all Lille projects here support questions lille's GitHub issue trackers are not intended to provide larel help or support support instead use one of the following channels discussions lar L

  91. cast forums larl IO fors stack Overflow Discord L chat IRC core development discussion you may propose new features or improvements of existing laravel behavior in the laravel framework repositories 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 Lille Discord server Taylor otwell the maintainer of Lille is typically

  92. present in the channel on weekdays from 8:00 a.m. to 5:00 p.m. that's America Chicago time 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 minor features that are fully backw compatible with the current release may be sent to the latest stable Branch currently 11. X major new fix features or features or features with

  93. 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 the most such as most of the files in resources CSS or resources JS or lar lar repository do not commit the compiled files due to their large size they cannot realistically be reviewed by a maintainer they should this could be exploited as a way to inject malicious code into larl in order to defensively prevent this all compiled files will be

  94. generated and committed by Lille maintainers security vulnerabilities if you discover security vulnerability within Lille please send an email to Taylor otwell at Taylor lil.com all SEC security vulnerabilities will be promptly addressed coding style Lille follows the psr-2 coding standard and the psr-4 autoloading standard PHP doc below is an example of a valid Lille

  95. documentation block note that the at pram attribute is followed by two spaces the argument type two more spaces and finally the variable name so PHP doc block pram string at pram closure at throws exception and then public function bind when the at pram or at return attributes are redundant due the use of native types they can be removed so removing them completely from the PHP doc however when the native type is

  96. generic please specify the generic type of the use of at pram or at return attributes so at return array for example style CI don't worry uh style CI don't worry if your code styling isn't perfect style c will automatically merge any style fixes into the Layel repository after pull requests are merged this allows us to focus on

  97. the content of the contribution and not the code style code of content the Lille code of conduct is derived 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.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

  98. behavior that can be reasonably considered harassment will not be tolerated chapter 2 getting started installation so meet LEL LEL 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

  99. while providing powerful features such as thorough dependency injection an expressive database abstraction layer cues and scheduled jobs unit and integration testing and more whether you are new to PHP web Frameworks or have years of experience larel is a framework that you can grow with you will help you take your first step as a we 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 Lille check out the lville boot camp for a Hands-On tour of the framework while we walk you through your building your

  100. first larl application why laravel there are a variety of tools and Frameworks available to you in building a web application however we believe larl is the best choice for building modern full stack web applications a progressive framework we like to call larl a progressive framework by that we mean that laral grows with you if you're just taking your first steps into web development lille's vast library of documentation guides and video tutorials will help you learn the ropes without becoming overwhelmed if you're a senior

  101. developer larl gives you robust tools for dependency injection unit testing cues realtime events and more larl is fine-tuned for building professional web applications and ready to handle Enterprise workloads a scalable framework laral is incredibly scalable thanks to the scalable scaling friendly nature of PHP and lel's built in support for fast distributed cach systems like reddis horizontal scaling with larel is a breeze in fact Lille applications have

  102. been easily scaled to handle hundreds of millions of requests per month need extreme scaling platforms like Lille Vapor allow you to run your Lille application at nearly Limitless scale on aws's latest service serverless technology a community framework larel combines the best packages in the PHP ecosystem to offer the most robust and developer friendly framework available in addition thousands of talented

  103. developers from around the world have contributed to the framework who knows maybe you'll even become a larel contributor creating a LEL project before creating your first Lal 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 Lille herd in addition we recommend installing node and mpm after you have installed PHP and composer You may create a new larel project being composers create Das project command so

  104. composer create Das project LEL larel example app or you may create new LEL projects by globally installing the lville installer via composer so after you globally require lville installer gille Lille new example app once the project has been created start lille's local development server using Lille Artisans serve command PHP Artisan serve once you have started the Artisan development server your application will be accessible in your web web browser at Local Host 8000 next you're ready to

  105. start taking your next steps into the lirell ecosystem of course you may also want to configure a database note if you would like a head start When developing your Lille application consider using one of our starter kits lille's starter kits provide backend and frontend authentication scaffold for your new lville application initial configuration all the configuration files for the lville 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 lville

  106. 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 local that you may wish to change according to your application environment based configuration since many of lel's configuration option values may vary depending on whether your application is running on your local machine or on a production web server many important configuration values are defined using the EnV file that exists at the root of

  107. your application your EnV file should be committed to your application's Source control s each developer SLS 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 should be would be exposed for more information about the file and environment based configuration check out the full configuration documentation databases and migrations now that you have created your first Lal application you probably

  108. want to store some data in a database by default your applications. configuration file specifies that Lal will be interacting with a sqlite database during the creation of the project larel 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 most cres you can update your EMV configuration file to use the appropriate database for example if you wish to use my SQL update

  109. yourm configurations files DB variables like so so my SQL 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 applications database migrations using PHP Artisan migrate if you are developing a Mac OS and need to install my SQL postgress SQL or redus locally consider using DB engine directory configuration theirl should always be served out of the root of the web directory config fed for your web server

  110. you should not attempt to serve a l 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 larl regardless of your preferred operating system so there are a variety of options for developing and running a Lille project on your local machine while you may wish to explore these options at a later time lville provides sale a built-in solution for running your Lille project using Docker Docker is a tool

  111. for running application and services in small lightweight containers which do not interfere with your local machine 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 sale is a lightweight command line interface for interacting with lel's default Docker configuration sale provides a great starting point for building a laral application using PHP my SQL and reddis

  112. without requiring prior Docker experience already a Docker expert don't worry everything about sale can be customized using the docker-compose IMO file included with LEL sale on Mac OS 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 Lille project for example to create a new Lille application in a directory named example app you may run the following

  113. command in your terminal that's curl DS ll. build example app bash of course you can change example app in this URL to change to anything you like just make sure the directory name only contains output numeric characters dashes and underscores the lvo applications 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 project has been created you can navigate to the

  114. application directory and start Lille sale Lille sale provides a simple command line interface for interacting with lille's default Docker configuration CD example app vendor bin and saale up once the application's doctor 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 Local Host note to continue learning more about sale review its complete documentation so sale on windows before

  115. we create a new Layel 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 EX executables natively on Windows 10 information on how to install and enable WSL 2 can be found within Microsoft's developer environment configuration note after installing and enabling WSL 2 you should ensure the

  116. docker desktop is configured to use the wsl2 backend next you are ready to create your first lvo 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 layal project for example to create a new Layel command new laral application and directory named example app you may run the following command in your terminal that's curl level. build example app of course you can change example- app and this is URL to anything you like just make sure the application

  117. name only contains alpha numeric characters dashes and underscores the lay of 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 nav you can navigate to the application directory and start Lille sale Lille sale provides a simple command line interface for interacting with lille's default Docker

  118. configuration CD example app bin sale up once the application Dockers 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 at Local Host developing within within wsl2 of course you will need to be able to modify the layer of 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

  119. extension for remote development once these tools are installed you may open any LEL 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 Layel 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

  120. create a new Lille application in a directory named example- app you may run the following command in your terminal c-s l.u example- apppp bash of course you can change example- app in this URL to anything you like just make sure the application name only contains alpha numeric characters dashes and underscores the lel's application directory will be created within the lay within the directory you execute the command from sale installation may take several minutes while sales application containers are built on your local

  121. machine after the projects has been created you can navigate to the application directory and start Lille sale Lille sale provides a simple command line interface for interacting with lille's default Docker configuration CD example app saale up once the application's docker containers have started you should run your application's database migrations that's sale Artisan migrate finally you can access the application in your web browser at Local Host note to continue learning more about Lille sale review its complete documentation so choosing your sales

  122. Services when creating a larel application via sale you may use the with query string variable to choose which Services should be configured in your new applications doc compos the ammo file available Services include MySQL post SQL Marb reddis mcash Mele search typ sense Mino selenium and mail pit if you do not specify which Services you would like configured a default stack of MySQL redus melis search mail pit and selenium will be configured you may instruct sale to install a default

  123. Dev container by adding the dev container parameter to the URL so that's curl - s and then example- app Dev container ideas support IDE support if you are you are free to use any code editor you wish When developing Lille applications however PHP storm offers extensive support for Lille and its ecosystem including Lille pint in addition the community maintained laral idea PHP storm plug-in offers a variety of helpful IDE augmentations including code generation eloquent syntax

  124. completion validation rule completion and more next steps now that you have created your larl project you may be wondering what to learn next first we strongly recommend becoming familiar with how larl works by reading the following documentation request life cycle configuration director structure front end service container facades how you want to use Lara will also dictate the next steps on your journey there are a variety of ways to use Lille and we'll explore two primary use cases for the framework below new to Lille check out Lille boot camp for hands- on tour of

  125. the framework while we walk you through building your first Lille application LEL the full stack framework LEL may serve as a full stack framework by full stack framework we mean that you're going to use LL to Route requests to your application and render your front end via blade templates or a single page application hybrid technology like inertia this is the most common way to use larvo framework and in our opinion the most productive way to use larvo if this is how you plan to use larl you may want to check out our documentation on front-end development routing views or

  126. the eloquent omm in addition you might be interested in learning about Community packages like Live Wire and inertia these packages allow you to use larabel as a full stack frame work while enjoying many of the UI benefits provided by single page JavaScript applications if you are using Lille as a full stack framework we also strongly encourage you to learn how to compile your application CSS and JavaScript using vit note if you want to get a head start building your application check out one of our official application

  127. starter kits laral the API backend laral may also serve as an API backend to your JavaScript single page app configuration or mobile application for example you might use laral as an API backend for your next. J JS application in this context you may use LEL to provide authentication and data storage retrieval for your application while also taking advantage of lel's powerful services such as cues emails notifications and more if this is how you plan to use Lille you may want to

  128. check out our documentation on routing Lille sanctum and the eloquent om configuration introduction all the configuration files for the larl 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

  129. such as your application time zone and encryption key the about command LEL can display an overview of your application's configuration driver's environment via the about Artisan command so PHP Artisan about if you're only interested in a particular section of the application overview out output you may filter for that section using the D- only option so -- only- environment or to explore specific configuration files values in detail you may use the config colant show Artisan

  130. command so col 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 cach driver locally than you do on your production server to make this a cinch Lille utilizes the EMV PHP library and a fresh library at Lille installation the root directory of your application will contain aemv example file that defines many common environment variables during the Lille installation process this file will

  131. automatically be copied Tov lille'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 lel's EMV function if you are developing within team You may wish to continue including and updating the. example file with your application by putting placeholder values in the example inte creation file other developers on your

  132. team can clearly see which environment variables are needed to run your application note any variable in your EnV file can be overridden by external environment variables such as server level or system level environment variables environment file security your EnV file should not be committed to your application Source control since each developer server using your application should require a different environment configuration furthermore this will be a security risk in the event an intruder gains access to your Source control

  133. reposit story since any sensitive credentials should would get exposed however it is possible to encrypt your environment file using Lil's built-in environment encryption encrypted environment files can may be placed in Source control safely so additional environment files before loading your application's environment variables lville determines if an appv app _ environment variable has been externally provided or if the --v CLI argument has

  134. been specified if so Lille will attempt to load aemv doapp andile file if it exists if it does not exist the the default EnV file will be loaded environment variable types all variables in your EMV files are typically pars as strings so some resered values have been created to allow you to return a wider range of types from the EnV function so EnV value true false um list here for the EnV

  135. versus the EnV underscore value if you need to Define an environment valuable variable with a value that contains spaces you may do so by inclosing the value in double quotes So appor name equals my application in double quotes retrieving environment configuration all the variables listed in the EnV file will be loaded into the uh dollar signore EnV PHP super Global with your application receives or requests however you may use the do the EnV function to

  136. retrieve values from these variables in your configuration files in fact if you review the lville configuration files you will notice many of the options are already using this function so debug debug is e EnV uh parenthesis the second value pass to the EnV function is the default value so if the first value was app debug second one would be false this value will be turned if no environment variable exists for the given

  137. key determining the current environment so the current application environment is determined via the appor EnV variable from your EnV file you may access this value via the environment method on the app facade so illuminates 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 as a given

  138. value the method will return true if the environment matches any of the given valuables so if app environment local if app environment local or staging encrypting environment v files unencrypted environment files should never be stored in Source control however larvo allows you to encrypt your environment files so that you may safely add be added to your Source control with the rest of your application encryption to encrypt an environment file you may use the N colon encrypt command so PHP

  139. artisan and Co en encrypt running the environment EnV Co en encrypt command will encrypt your EnV file and place the encrypted contents in a.v. encrypted file the decryption ENC decryption key is presented in the output of the command and should be stored in a secure password manager if you would like to provide your own encryption key you may use the Das key option when invoking the command so-- key equals your key note the length of the key provided should match the key length required by the

  140. encryption Cipher being used by default larel we use the aes256 CBC Cipher which requires a 32 character key you are free to use any Cipher supported by lar encryptor by passing the-- Cipher option when invoking the command if your application has multiple environment files such ASV and env. staging you may specify the environment file that should be encrypted by providing the environment name via the D- EMV options-- EMV equals staging decryption to decrypt an

  141. environment file you may use the EnV colon decrypt command this command requires a decryption key which there will retrieve from the larvo _ mcore encryption uncore key environment variable so Artis an M colon decrypt or the key may be provided directly to the command via the D- key so D- key equals your key when the UN M decrypt command is invoked laral would decrypt the contents of the env. encrypted file and place the decrypted context in the EMV

  142. file the-- Cipher option will be provided to the m decrypt command in order to use a custom encryption Cipher that's-- key and then D- Cipher if your application has multiple environment fa variables uh multiple environment files such ASV and. staging you may specify the environment file that should be decrypted by providing the environment name via the d-v options d-v equals staging in order to overwrite an existing environment

  143. file you may provide the-- Force option to the m decrypt command so M the Crypt d-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 do syntax which includes the name of the file and option you wish to access a default value may also be specified and will be

  144. returned if the configuration option does not exist so config colon colon git or config function set configuration values at runtime they invoke the config facade set method or pass an array to the config function so config set or config um as an array for app. time zone to assist with static analysis the config facade also provides typed configuration retrieval methods if the retrieved configuration value does not

  145. match the expected type an exception will be thrown so config Co and col string integer float Boolean array configuration caching to give your application to 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 the framework you should typically run the PHP Artisan config cache command as part of your production deployment process the

  146. command should not be run during local devel 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. file will not be loaded by the framework during requests or artisen commands therefore the EnV function will only return external system level environment variables for this reason you should ensure you are only calling the EMV function from within your application's configuration config files you can see many examples of this by examining lille's default configuration

  147. 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 end function from within your configur configuration files once the configuration has been cached the file will not be loaded therefore the in EnV function will only return

  148. 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-- all debug mode the

  149. 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 dis respect the value of the app debug environment variable which is stored in your DV 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 and users maintenance mode when your application is in maintenance

  150. mode a custom view will be displayed for all of your requests in your into your application this makes it easy to disable your application while it is updating or when you're 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 the status quote to 50 503 to enable maintenance mode execute the down Artisan command so PHP Artisan down if you would like the refresh HTTP header to be sent with all maintenance mode and responses you may

  151. 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 D- 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-- retry equal 60 bypassing maintenance mode to allow maintenance mode to be bypassed using a secret token you may use the secret

  152. option to specify a maintenance mode bypass token so-- secret equals your secret after placing the application and maintenance mode you may navigate to the application URL matching this token and Lille will issue a maintenance mode bypass cookie to your browser if you would like Lille to generate the Seeker token for you you may use the with- secer option this Seeker will be displayed to you once the application is in maintenance mode when accessing this hidden route you will then be directed to the SL route of the application once the cookie has been issued to your

  153. browser you will be able to browse the application normally as it was not in maintenance mode note your maintenance mode secr should typically consist of Alpha Characters and optionally dashes you should avoid using characters that have special meaning in URLs such as uh question mark or Ampersand maintenance mode on multiple servers by default larel determines if your application is in maintenance mode using a file based system this means no activation this means to activate

  154. maintenance mode the PHP Artisan down command has to be executed on each server hosting your application alternatively Lara offers a cash based method for handling maintenance mode this method configures requires running the PHP Artisan down command on just one server to use this approach modify the driver setting 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

  155. 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 larl framework must boot in order to determine your application is in maintenance mode and render the maintenance mode View using the templating engine for this reason Lille allows you to pre-render a maintenance mode view that will be

  156. 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 PHP Artisan down-- render equals errors redirecting maintenance mode requests while in maintenance mode laral will display the maintenance mode view for all of your application URLs the user attempts to access if you wish you may instruct Lille to redirect all requests to a specific URL this may be accomplished using the redirect option

  157. for example You may wish to redirect all requests to the slash URL so-- 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 cues while your application is in maintenance mode no Q jobs will be handled the jobs will continue to be handled as normal once the application is out of maintenance

  158. mode alternatives to maintenance mode since maintenance mode requires your application to have several seconds of downtime consider alternatives like Lille vapor and envoyer to accomplish zero downtime deployment with laraba okay directory structure table of contents for the directory structure introduction the default Lille 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 Lille imposes almost no

  159. restrictions on where any given class is located as long as composer can autoload the class note Lille check out the Lille boot camp for a Hands-On tour of the framework while we walk you through building your first lville application the root directory the app directory app directory contains the core code of your application will 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

  160. also houses a cache directory which contains framework generated files for performance optimization such as the route and services Cache files config directory as the name implies configs contains all of your applications configuration files it's a great idea to read through all these files and familiarize yourself with all the options Available to You database Direct directory contains your database migrations model factories and seeds if you wish you may also use this directory to hold a sqlite database public

  161. directory contains the index.php file which is the entry point for all requests entering your application and configures autoloading this directory also houses your assets such as images JavaScript and CSS Resources directory contains your views as well as your raw uncompiled assets CSS or JavaScript routes directory contains all the route definitions for your app application by default two route files are included with larvo web.php and console. PHP the

  162. web.php file contains routes that Lille places in the web. 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 meet 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 command instance allowing a simple approach to interacting with each command's IQ IO method

  163. 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 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 Artis 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

  164. 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 component 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

  165. finally the logs directory contains your application's log files the storage app directory may be used to store user generated files which such as profile avatars that should be publicly accessible you should create a symbolic link of Public Storage which points to this directory you may create this link using PHP Artisan storage link Artisan command the test directory contains your automated tests example pests or PHP unit unit tests and feature tests are provided out of the box each test class

  166. should be subed with the word test you may run your tests using the VIN bin pest or bin PHP unit commands or if you would like to detail more detailed and beautiful representation for your test results you may run your tests using the PHP Artisan test Artisan 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 namespace under app and is autoloaded by

  167. 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 make Artisan commands to generate classes for example the app console directory will not exist until until you execute the make Command Artisan command to generate a command class both the console and HTTP directories are further explained in their respective sections

  168. 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

  169. review the available commands run the PHP Artisan list make Command in your terminal the broadcasting directory contains all 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 doation on Eed broadcasting the console directory contains all the custom Artisan commands for your application these commands may be generated using the make Command command the directory does not exist by default

  170. but will be created to you by the generate 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 the custom exceptions for your do application these exceptions may be General generated using the make exception command the HTTP directory contains your controllers middleware and form requests almost all the logic to handle requests entering your

  171. 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 uh cuble jobs for your application jobs may be cued by your application or run synchronously within the current request life cycle jobs that run synchronously during the current requests are sometimes referred to as commands since they are an ation of the command pattern the listeners directory this

  172. directory does not exist by default but will be created for you if you execute the event generate or make listener Artisan commands The Listener 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 event 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

  173. application mail objects allow you to encapsulate all the logic of building an email in a single simple class they may be sent using the mail send method the models directory contains all of your eloquent model classes the eloquent omm included with LEL 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

  174. will be created for you if you execute the make notification Artis command the notifications directory contains all the transactional notifications that are sent by your application such as simple notifications about events that happen within your application lille's notification feature abstracts sending notifications of 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 policy's directory contains the authorization policy class

  175. CL for your application policies are used to determine if a user can perform a given action against a resource the provider's 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 laral application this directory will already contain the app service provider you are free to add your own

  176. 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 lville is a backend framework that provides all the features you need to

  177. build modern web applications such as routing validation caching cues file storage and more however we believe it's important to offer de 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 Lille 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

  178. options below so that you can make informed decisions regarding the best approach to frontend development for your application using PHP PHP and blade in the past most PHP applications rendered HTML to the browser using simple HTML templates interspersed with PHP Echo statements which render data that was retrieved from a database during the requests in Lille this approach to rendering HTML can still be achieved using views and blade blade is an ex extremely lightweight templating

  179. language that provides convenient short Syntax for displaying data iterating over data and more for example app for each hello and then in double brackets uh 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 rendered by the browser even today many applications may be perfectly suited to

  180. having their front ends 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 front ends 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 View and react others preferring to stick with the backend language they are comfortable with have developed

  181. solutions that allow the construction of modern web application uis while still primarily utilizing their backend language of choice for example in the rails ecosystem this has spurred the creation of libraries such as turbo hot wire and stimulus within the Lal ecosystem the need to create uh modern dynamic Front Ends by primarily using PHP has led to the creation of larel Livewire in alpine.ca Live Wire is a framework for building larel powered front ends that

  182. feel a dynamic modern and alive just like front ends built with modern JavaScript Frameworks like View and react when using Live Wire you will create Live Wire components that render a discrete portion of your UI and expose methods and data that can be invoked and interacted with from your application front end for example uh a simple counter component might look like the following uh you have public count public function public render and the

  183. corresponding template for the counter would be written like so button wire click increment and then an H1 with the double bracket dollar sign count as you can see Live Wire enables you to write new HTML attributes such as wire cool and click that connect your lville applications front end and back end in addition you may render you can render your components current state using simple blade expressions for many Livewire has revolutionized front end development with lir allowing them to

  184. stay within the comfort of Lille while constructing modern dynamic web applications typically developers using Live Wire will also utilize Alpine JS to sprinkle JavaScript into their front end or only where it is needed such as in order to render a dialogue window if you're new to lville we recommend getting familiar with the basic usage of views and blade then consult the official Lille Livewire documentation to learn how to take your application to the next level with interactive live wire components starter kits if you

  185. would like to build your front end using PHP and live wire you can leverage our Breeze or jet stream starter kits to jump start your application development both of these starter kits scaffold your application backend and frontend authentication flow using blade and Tailwind so you can simply start building your next big idea using view/ react although it's possible to build modern front ends using level and Live Wire many developers still prefer to Leverage The Power of a JavaScript framework like view or react this allows developers to take advantage of the rich

  186. ecosystem of JavaScript packages and tools available via mpm however without additional tooling pairing larel with view 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 pin view view/ react framework such as n and next however DEA hydration authentication remain complicated and cumers some problems to solve when piring a back-end framework like Lille with these front-end Frameworks in addition developers are left maintaining

  187. two separate code repositories often needing to coordinate maintenance releases and deployments across both repositories while these problem s are not insurable we don't believe it's a productive or enjoyable way to develop applications inertia thankfully laral offers The Best of Both Worlds inertia Bridges the gap between your Lal application and your modern view or react front end allowing you to build full-fledged modern front ends using view or react while leveraging Lille routes and controllers for routing data

  188. hydration and authentication all within a single code repository with this approach you can enjoy the full power of both larel and view/ react without crippling the capabilities of either tool after installing inertia into your labal application you will write routes and controllers like normal however instead of returning a blade 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

  189. 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 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 leville powered backend and your JavaScript powered front end server side rendering if you're concerned about

  190. diving into inertia because your application requires serice side rendering don't worry inertia offers service side rendering support and when deploying your application via lvo Forge it's a breeze to ensure that inertia service ad rendering process is always running starter kits if you would like to build your front end using inertia and view/ react you can leverage our Breeze or an Jetstream starter kit to jump start your application's development both of these starter kits scaffold your applications front end and

  191. backend authentication flow using inertia view/ react tailwind and V 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 live wire or view/ react and inertia you will likely need to bundle your application CSS into front into production ready assets of course if you choose to build your application front end with view or react you will also need to bundle your components into browser ready JavaScript assets by default Lille utilizes vit to

  192. bundle your assets V provides lightning fast build times and near instantaneous hot module replacement during local development in all new larval applications including those using our starter kits you will find a V.C config.js file that loads our lightweight Lal V plugin that makes v a joy to use with laral applications the fastest way to get started with LEL and vit is by beginning your application development using LEL brief the simplest way start a kit the jump starts your application by providing

  193. front end and backend authentication scaffolding note for more detailed documentation on utilizing beet with larl please see our dedicated documentation on bundling and compiling your assets quick water break

  194. starter kits introduction to give you a head start building your new layer 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're not required you are free to build your own application from the ground up by simply installing a fresh copy of ladel either way we know you will build something great LEL Breeze is

  195. a minimal simple implementation of all lal'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 larvo Bree's default view layer is made up of simple blade templates Style with tail and CSS additionally Breeze provides scaffolding options based on liary or inertia with a choice of using view or react for the inertia based

  196. scaffolding larvo boot camp if you're new to larvo feel free to jump into the larel boot camp the larel boot camp will walk you through building your first larel application using breeze it's a great way to get a tour of everything that lville and breze have to offer installation first you should need you should create a new lville application if you create your application using the lville installer you will be prompted to install larel Breeze during the installation process otherwise you will need to manually follow the manual installation instructions below if you have already created a new larvel

  197. application without a starter kit you may manually install larvel Breeze using composer require larel Breeze --d after composer has installed the larel breeze package you should run the breeze install Artisan command this command publishes the authentication views routes controllers and other resources to your application larel Breeze publishes all of its code to your authentication views routes controllers and other resources to your application laral Breeze publishes all of its code to your application so you have full

  198. control and visibility over its features and implementation the breeze install command will prompt you for your preferred front and stack and testing framework so PHP Artisan Breeze install Artisan migrate mpm install mpm run Dev Breeze and Blade 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

  199. end stack after Breeze's scaffolding is installed you should also compile your application's frontend assets PHP Artisan Breeze install migrate MPN install mpm run Dev next you may navigate to your applications login or register URLs in your web browser all of Bree's routes are defined within the routes off. PHP file to learn more about compiling your applications CSS and JavaScript check out lel's vit documentation Breeze and Livewire larel Breeze also offers Livewire scaffolding

  200. Livewire is a powerful way of building Dynamic reactive front and UI 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 V you and react to use the Live Wire stack you may select the Live Wire front end stack when executing the breeze install Artis in command after Breeze's scaffolding is installed you should run your database migrations so Breeze install AR and migrate Breeze

  201. and react view laral breeds also offers react and view scaffolding via an inertia front end implementation inertia allows you to build mod modern single page react and view applications using classic server side routing and controllers inertia lets you enjoy the front end power of react and view compined with the incredible backend productivity of Lille and lightning fast vit compilation to use an inertia stack you may select the view or react front end Stacks when executing the breeze install Artisan

  202. command When selecting the view or react front end Stack The Blaze installer will 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 applications front and assets so that's Breeze install ARS migrate install mpm runev next you may navigate to your application SL login orregister URLs in your web browser all of Breeze's routes are defined within

  203. this routes off. PHP file Breeze and nextjs API larvo Breeze can also scaffold an authentication API that is ready to authenticate modern JavaScript applications such as those powered by next next others to get started select the API stack as your desired stack when executing the breeze install Artisan command PHP Artisan Breeze install PHP Artisan migrate during installation Breeze will add a front-end URL environment VAR to your applications. EnV file this URL should be the URL of

  204. your JavaScript application this will typically be Local Host 3000 during local development in addition you should ensure that your app URL is set to Local Host 8000 which is the default URL used by the serve Artisan command next JS reference impation finally you are ready to pair the back end with the front end of your choice a next reference implementation of the breeze front end is available on GitHub this front end is maintained by Lille and contains the same user interface as the traditional blade and inertia Stacks provided by Breeze larel Jetstream while larel

  205. Breeze provides a simple and minimal starting point for building a larel application Jetstream Aug that functionality with more robust features and additional front-end technology stacks for those brand new to larel we recommend learning the ropes with larel Breeze before graduating to laral Jetstream Jetstream provides a beautifully designed application scaffolding for Lille and includes login registration email verification two- Factor authentication session management API support foral syum and optional Team Management Jetstream is designed using

  206. still and CSS and offers your choice of live wire or inertia driven development driven frontend scaffolding complete documentation for installing nille jet stream can be found within the official Jetstream documentation deployment introduction when you're ready to deploy your Lille development Lille application to production there are some important things you can do to make sure your application is running as efficiently as possible in this document we'll cover

  207. some great starting points for making sure your larel application is deployed properly the lvo framework has a few system requirements you should ensure that your web server has the following minimum PHP version and extensions so PHP 8.2 ctype curl Dom file info filter hash MB string op SSL pcre PDO session tokenizer and XML PHP extensions engine X if you are deploying your application to a server that is running engine X you

  208. may use the following configuration file as a starting point for configuring your web server most likely this file will need to be customized depending on your server's configuration if you would like assistant man assistance in managing your server consider using a first-party Layell server management and deployment service such as Lille Forge please ensure like the configuration below your web server directs all requests to your applications public index.php file you should never attempt to move the index.php file to your Project's route as serving the application from the

  209. project rule to expose many sensitive configuration files to the public internet Franken PHP may also be use to serve your laral application Franken PHP is a modern web application server written in go to serve a laral PHP application using Franken PHP you may simply invoke its phps server command Franken PHP server to take advantage of more powerful features supported by Franken PHP such as laral octane integration HTP 3 modern compression or

  210. the ability to package laral applications of Standalone binaries please consult Franken php's laral 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 Lille provides a single convenient optimized Artis command that will cach all these files this command should typically be invoked as part of your application's deployment process so PHP Artisan optimize the optimized clear method may be used to remove all the cache files generated by

  211. the op optimize command PHP optimize clear in the following documentation we will discuss each of the granular optimization commands that are executed by the optimized command caching config ation when deploying your application to production you should make sure that you run the config cache Artisan command deploy during your deployment process this command will combine all lel'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

  212. configuration values warning 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 to the EnV function or EnV variables will return null caching events you should cash your application's AIS 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 cach

  213. caching routes if you are building a large application with many routes you should make sure that you are running the route cach Artisan command during your deployment process PHP Artisan route cach 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

  214. compiled on demand improving the performance of each request that returns a view debug mode the debug option in your 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 stored in your applications. MV file in your production environment warning this value should always be false if the app to be debug variable is set to true in your production you risk exposing sensitive

  215. configuration values to your applications and users the health route Lille includes a built-in Health route 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 registration system such as kubernetes by default the health check route is served at seven or slup and will return a 200 HTTP response if the application is booted without exceptions otherwise a 500 HTTP response will be returned you

  216. may configure the urri for this route in your application's bootstrap slapp file when HTTP requests are made to this route larl will also dispatch eliminate foundation events diagn 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 May simply throw an exception from The

  217. Listener easy deployment with Forge SL Vapor larel 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 larvo application laral Forge is a wonderful alternative laral Forge can create servers on various infrastructure providers such as digital ocean Len Noe AWS and More in addition Forge installs and manages all the tools managed to needed to build robust layal applications such as X my

  218. SQL redus mcash to bean stock and more want a full guide to deploying with larel Forge check out the laral boot camp and the forge video series available on lar laral Vapor if you would like a totally serverless autoscaling development platform tuned for laral check out laral Vapor laral vapor is a serverless deployment platform for LEL powered by AWS launcher Lille instructure infrastructure on vapor and fall in love with the scalable Simplicity of serverless larel vapor is fine-tuned by lel's creators to work seamlessly with the framework so you can

  219. keep writing your larvel applications exact like you're used to chapter three architecture Concepts the request life cycle 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 the goal of this develop document is to give you a good highlevel overview of how the larel framework works by getting to know the

  220. overall framework better Everything feels less magical and you'll be more confident building your application if you don't understand all 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 life cycle overview the entry point for all of your requests to a larel application is the public index.php file all requests are directed to this file by your web server Apache enginex configuration the index.php file does not contain much code rather it is a

  221. starting point for loading the rest of the framework the index.php file loads the composer generated autoloaded definition and then retrieves an instance of larel application from bootstrap app.php the first action taken by larel 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 the handle request or handle command methods of the application instance depending on the type of requests entering the

  222. application these two kernels Ser as the central location through which all requests flow for now let's just focus on the HTTP kernel which is an instance of illuminate found Foundation HTTP kernel the HTTP kernel defines an array of bootstrappers that will be run before the request is executed these bootstrappers configure air handling figure logging detect the application environment and perform other tasks that you need to be done before the request is actually handled typically these classes en handle internal larel configuration that you do not need to

  223. 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 methods handle method is quite simple it receives a request and returns a response thinking of the kernel as a being a big black box that represents your entire application feed the HTTP request and it will return

  224. HTTP responses service providers one of the most important kernel bootstrapping applications is loading the service providers for application service providers are responsible for bootstrapping all the Frameworks various components such as the database Q validation and routing components Lille will iterate through that list of providers and instantiate each of them after instantiating the providers the register method will be called on all the providers then once

  225. 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 they boot method is executed essentially every major feature offered by larl 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 larel bootstrap process while the framework internally uses dozens of service providers you also have the option to create your own you

  226. can find a list of the userdefined or thirdparty service providers that your application is using in the bootstrap providers. PHP file routing 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 any run any route specific metalware middleware provides a convenient mechanism for filtering or examining HTTP requests entering your application for example level includes a middleware that

  227. 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 designed to assign 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

  228. 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 routes 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 requests of the application

  229. 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 larvo request life cycle focus on service providers service providers are the key to bootstrapping a Lille 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 Lar application is built and

  230. bootstrapped Via service providers is very valuable your application's userdefined service providers are stored in the app providers directory by default the app service provider is fairly empty this provider is a great way great place to add your application's own bootstrapping and service containing 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

  231. introduction the lville service container is a powerful tool for 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 uh you have show string and protected user repository so in this example the user

  232. 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 dum dummy implementation of the user repository when testing our application a deep understanding of the Lille service

  233. container is essential to building a powerful large application as well as contributing to the larel 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 route's webp PHP file route get die in this example hitting your application SL route will

  234. automatically resolve the service class and inject it into your router's hand routes Handler this is gamechanging it means you can develop your application and take advantage of dependency inje without worrying about bloated configuration files thankfully many of the classes you'll be writing when building a Lille 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 cued jobs once you taste the power of

  235. 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 hint dependencies on routes controllers event listeners and elsewhere without ever manually interacting with the cont within the container for example you might typ hint the HTTP request object on your Rod definition so that you can easily manage the recurrent request even though we never have to implement or interact with a container to write this code it is

  236. managing the injection of these dependencies behind the scenes so HTTP requests route get function and then inject request in many cases they to automatic dependency injection and facades you can build L applications without ever manually binding or resolving anything from the containers so when would you ever manually interact with a container let's explain two examine two situations first if you write a class that implements an interface and you wish to typeint that interface on a route or class constructure you must tell the container

  237. how to resolve that interface secondly if you writing a lirell package that you plan to share with other larel developers you may need to bind your packages 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 this app property we can register a binding use the bind

  238. 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 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 in acting with a container within service providers however if you would like to interact with a container

  239. 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 use the bind if method to reject 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

  240. there's 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 the Singleton binding is resolved the same object instance will be returned on a subsequent calls into the

  241. Container so use app services this app singlet 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 Singleton the scoped method binds a class or interface into the container that should only be

  242. resolved one time within a given Lille request or jobs life cycle while this method is similar to the Singleton method instances registered using the scoped method will be flushed whenever the larval application starts a new life cycle such as when a laral octane worker processes a new request or when a laral q 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

  243. 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 an event and a Rus event Pusher implementation once we have coded our Rus event Pusher implementation of this interface we can register it with the service container

  244. like so so this app bind event Pusher class with redus event Pusher class this statement tells the container that should inject the Reus event Pusher when a class needs an implementation of the event Pusher now we can typ hint the event Pusher interface in the Constructor a class that is resolved by the container remember controllers event listeners middleware and various other types of classes within lar applications are always resolved using the container so public function construct protected

  245. 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 into each class for example two controllers may depend on different implementations of the file system contract Lille provides a simple fluent interface for finding this Behavior so you can use the needs method for file system class binding Primitives

  246. 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 the container bindings with that tag so this app win export aggregator needs

  247. and give tag if you need to inject a value from one of your applications configuration files you may use the give config method so give config method for this app win binding typed VAR addicts occasionally you may have a class that receives an array of typed objects using a varia adct Constructor argument using contextual binding you may resolve this dependency by providing the give method with with a closure that returns an array of resolved filter instances so

  248. needs filter class give with a function to return app make n filter app make 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 win firewall class needs filter class give null filter profanity filter to Long filter Etc Vari adic tag dependencies sometimes a class may have a variety dependency that is typ hinted

  249. as a given class report 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

  250. 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 the containers tagged method this app bind and return new report analyzer app tagged extending bindings the extend method allows the modification of resolved services for example when a service is resolved you

  251. 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

  252. class's dependencies are not resolved via the container you may inject them by passing them as an associative array into the make with with make withth method for example we make 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

  253. 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 Layel container instance itself injected into a class that is being resolved by the container you may type hint the illuminate container container class on your classes Constructor that's public function construct protected container dollar sign container automatic injunction alternatively and importantly you may type in the dependency in the Constructor of a class

  254. that is resolved by the container including controllers event listeners middlewares and more Additionally you may type in dependencies and the handle method of cued jobs in practice this is how most of your objects should be resolved by the container for example you may typeint a repository defined by your application in a controller's Constructor the repository will automatically be resolved and injected into the

  255. class so PHP public functions show string user this user's find or fail protective function construct protected user repository users method indication and injection sometimes you may wish to invoke a method on an object instance while allowing the container to automatically inject that method's dependent for example given the following class of class user report you may invoke the generated method via the container like

  256. so so Report app call new user report generate the call method accepts any PHP callable the container 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

  257. resolving with a function of mixed object and an application as you can see the object being resolved by the 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 larel service container implements the psr-11 interface therefore you may type hint the PSR 11 container interface to obtain an instance of larvo container use app Services transistor route git function service container get transistor class

  258. 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 in instance of PSR containers container exception interface will be thrown quick water

  259. break for

  260. service providers introduction service providers are the central place of all Lal application bootstrapping your own application as well as all of lille'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 Lille uses dozens of service providers internally to bootstrap its core services such as the mailer q cach and

  261. 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 servic 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 larl application if you would like to learn more about larel handles requests and works internally check out our documentation on the larel request life cycle writing service providers all service providers extend the alumin

  262. 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 an event listener um 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 laral will automatically register your new provider in your application's bootstrap

  263. providers. PHP file PHP artisan make provider make service provider 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 with new 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

  264. 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 Lille service container check out its documentation the bindings and Singleton property if your service provider registers many many simple bindings You may wish to use the bindings and Singleton property instead

  265. 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

  266. 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 Artis command Lal will automatically add the

  267. generated provider to the bootstrap providers. PHP file however if you have manually created the provider class you should manually add the provider class to the array 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 Layel

  268. 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 larel load the service provider to defer the loading a provider implement the defer provider interface and Define a provider method the provides method should return the service container bindings registered by the provider facades introduction throughout the larel documentation you will see examples of code that interacts

  269. with lille's features via facades facades provide a static interface to classes that are available in the application service container layer ships with many facades which provide access to almost all of lille's features lel's facade serves as static proxies to underlying classes in the service container providing the benefit of a tur 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

  270. the flow and continue learning about larl all of lille's facades are defined in the illuminate support facades Nam space so we easily access a facade like so so facad cach or facad route then you can do route dot dot or colon colon git return cash colon colon git throughout the Lille documentation many of the examples will use facades to demonstrate various responsive various features of the framework helper functions to complement facade the laral offers a

  271. variety of global helper functions that make it even easier to interact with common LEL 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 illuminate support facades response facade to generate a Json response we may simply use the response function because helper functions are

  272. globally available you do not need to import any classes in order to use them so instead of returning uh response colon colon Json within the facade you can return response function Json when to utilize facades facades have many benefits they provide a tur memorable syntax that allows you to use lal's features without remembering long class names that must be injected or configured manually furthermore because

  273. 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 glasses continue to grow and use many SS in a simple 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

  274. 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 prim primary benefits of dependency injection is the ability to swap implementations of the injected class this is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub typically it would not be possible to mock or stub a truly static class method however since faades use Dynamic methods to proxy

  275. method calls to object resolved from the service container we actually can test faades just as we would test an injected class instance for example given the following route route git return cash git using lille's facade testing methods we can write the following test to verify that the cash get method was called with the argument we expected so response this get cash and response assert C value

  276. cash should receive response this get response assert C facades versus helper functions in additions to facades level 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's absolutely no practical

  277. 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 git cash return cash key the cash helper is going to call the git method on the class underlying the cache facade so even though we are using the helper function we can write the following tests to verify that the method was called with the argument we expected which would be response this

  278. get cach response ass search see cash should receive get how facades work in a laral 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 L those facades and any custom facades you create will extend the base facade class the facade based class makes use of the call static magic method to defer calls from your facade to an object resolve from the container in the example below

  279. a call is made to the laravel cache system by glancing at this code one might assume that the static G method is being called on the cach class so public function show user equals cash git return view profile notice that the near the top of the file we are importing the cash facade this facade serves as a proxy for accessing the underlying implementation of the cash Factory interface any calls we make using the facade will we pass the underlying instance of lel's cash service if we

  280. look at the facade cach class you'll see that there's no static method git so protected static function get facade accessor instead the cash facade extends the base facade class and defines the method get facade accessor this method method's job is to return the name of a service container binding when the user references any static method on the cache uh facade Laro resolves The cach Binding from the service container and runs the requested

  281. method in this case get against that object so realtime 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 realtime 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

  282. 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 published method using real-time facades we can maintain the same testability while not being required to explicitly pass pass a publisher instance to generate a realtime facade prefix the name space of the imported class with facades so importing you can use app

  283. contracts publisher instead you'll use facade app contracts publisher so now the publisher publish this you have publisher colon colon publish when the realtime facade is used the publisher implementation will be solved out of the service container using the portion of the interface or class name that appears after the facade Prof prefix when testing we can use their's built-in facade testing helpers to mock this

  284. method call so publisher colon colon should receive publish so public function test podcast can be published podcast 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

  285. 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 o o instance blade broadcast broadcast instance bus Cash Cash instance config cookie Crypt date DB DB instance event exceptions exceptions file gate hash HTTP Al log

  286. mail notification p password password instance pipeline instance process q q instance Q Base Class rate limiter redirect rdus Reus instance request response response instance route schedule schema session session instance Storage storage instance URL validator validator instance view view instance and V okay before we hit chapter 4 I'm going

  287. to take a quick break get some water and head to the bathroom

  288. for e

  289. [Music]

  290. s [Music]

  291. n

  292. [Music]

  293. n [Music]

  294. all right so we are back chapter 4 the basics basic routing the most basic larvo routes accept a URI and a closure providing a very simple and expressive method of defining routes and behavior without complicated routing conf configuration files one

  295. second so route get return hello world all laral routes are defined in your route files which are located in the routes directory these files are automatically loaded by larl using the configuration specified in your application bootstrap appp 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

  296. 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 user in your browser that's route get user returns user controller class index if your application also offers a stateless API you may enable API routing using the

  297. install API Artisan command PHP Artisan install API the install API command installs Lille synct which provides a robust 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 routes api.php are stateless and are assigned to the API

  298. middleware Group additionally the/ API URI prefix is automatically applied to these routes so you do not need to manually apply 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 respond responds to multip multiple HTTP verbs you may do so using

  299. the match method or you may even register a route that responds to all HTTP verbs using the any method so when defining multiple routes that share the same URL routes using the get postp put patch delete and option methods should be defined before routes using the any match and redirect methods this data uh this ensures the incoming request is matched with the correct route dependency injection you may type hand any dependencies required by your

  300. route and your route's callback signature the declared dependencies will automatically be resolved and injected into the Callback by the leville service container for example you may type hint the HTTP request class to have the current HTTP request automatically injected into your route callback csrf protection remember any HT 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

  301. rejected you can read more about csrf protection and the csrf documentation so in a form method you can have the at csrf method and blade redirect routes if you are defining a route that red redirects to another URI you may use the route redirect method this method provides a convenient shortcut 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

  302. may customize the status code using the optional third parameter route redirect here there 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

  303. 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 Prov pass to the view as an optional third argument router view welcome router view welcome name tailor when using route parameters and view routes the following parameters are reserved by larl and cannot be used that's view data status and headers listing your routes the route list Artis

  304. in 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 Lille to display the route middleware and middleware group names by adding the- V option to the command so rout list- V you may also instruct lville to only show routes that begin with a evm URI so D- path equals API in addition you may instruct lville to hide any

  305. routes that are defined by thirdparty packages by providing the-- accept Dash 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

  306. 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 and you can provide additional routes there or you may even take complete control over route registration by providing a using closure to the width 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

  307. 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 bra BRAC and should consist of alphabetic characters underscores or underscores are also acceptable within route parameter names route parameters

  308. are injected into route callback SLC controllers based on their order the names of the route callback controller arguments do not matter if your route has dependencies that you would like the lville service container to automatically inject into your route's call back 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

  309. 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 git user 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 wear method on a route instance the wear method accepts the name of the parameter and a regular expression defining how

  310. the parameter should be constrained so route get username function where name and then A to Z A- 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 Inc committ Quest 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

  311. expression you may use the pattern method you should Define these patterns in the boot method of your applications app service provider class public function boot route pattern ID 0 to 9 plus once the pattern has been defined it is automatically applied to all routes using that parameter name Route G user ID function string ID for example encoded forward slashes the Layel routing

  312. component allows all characters except slash to be present within route parameter values you must explicitly allow slash to be part of your play placeholder using a wear condition regular expression so wear search comma period uh star encoded 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 changing

  313. the name method onto the route definition so route git user profile function name profile you may also specify route names for controller actions so user profile controller colon class comma show name profile warning route names should always be unique generating URLs to name routes once you've assigned a name to a given route you may use the route's name when generating URLs or to redirects via lel's Route and redirect helper functions so generating URLs could be

  314. dollar sign URL equals route profile generating redirects red 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 Gen 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

  315. as a second fun second parameter will add uh user1 profile question mark photos equals yes sometimes you may wish to specify request whyde default values for URL parameters such as the current local to accomplish this 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

  316. the current route name from a route [Applause] 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 names space delimiters and slashes and URI prefixes are

  317. 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 middleware and then you can pass them as a parameter first or second controllers if a group of grots 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

  318. 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 routw 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 each route in the group within a given URI for example you may want to prefix

  319. all route I 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 the route name exactly as it is specify so we will be sure to provide the trailing uh period character in the prefix so route colon colon name admin

  320. 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 larel route model binding provides a convenient way to automatically inject the model instances 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 larvo automatically

  321. resolves eloquent models def find in routes or controllers actions whose type hinted variable names match a route segment name for example use app models users rout git users user function user which is injected return user email since the user variable is in is typ hinted as the app SL models user in the function eloquent model and the variable name matches the user URI segment larl

  322. 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 typeint so route git which is the

  323. definition has users sluser where the controller method definition shows the user as the typ hinted function soft leaded 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 git at the end you can append with trashed function customizing the key sometimes you may wish to resolve eloquent models using a

  324. column other than ID to do so you may specify the column in the route parameter definition so route git slost SL 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 get R root getroot key name method on the eloquent model so public function getroot key name Rec return slug for example when implicitly binding multiple eloquent models in a

  325. 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 for by slug for a specific user use appmodel poost route get user post colon slug when using custom key implicit binding as a nested route parameter larel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the

  326. 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 larel 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 Co calling git at the end of that you can append scope bindings or

  327. you may instruct an entire group of Route definitions to use scope bindings so if you pen if you have route scope bindings group function and put your routes in there similarly you may explicitly instruct larel to not scope bindings by invoking the without scope bindings method so be pending that onto the end of your route customizing missing Model Behavior typically a 404 HTTP response we generate if an implicitly bound model is

  328. 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 in enome binding PHP 8.1 introduce support for enums to comp complement this feature Laro allows you to type hint a back enum on your route definition and laral will only invoke the route if that route

  329. segment corresponds to a valid evening fa enum value otherwise a 404 HTTP 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 Lille return of 404 HTTP response so route get categories category you can input uh

  330. implicitly call that function with an enum explicit binding you're not required to use lel'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 service provider next Define a route that

  331. contains a user parameter so route colon git users SL uh brackets user since we have bound all user parameters to the app models user model model in the bootstrap file an instance of that class will be injected into the route so for example request to user SL1 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

  332. 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 col andon 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

  333. boot route colon bind user return user alter 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 utilized ing implicit binding scoping the resolve child route binding will method will be

  334. 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 applications exception Handler however since you would typically Define the fallback route within your routes do/ web.php file all middleware in the web middleware group will apply to the route you are free to add additional

  335. middleware to this group as needed so route col and fallback function as a group route rate limiting LEL 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 defined within the boot method of your applications app service provider class rate limiters are defined using

  336. the rate limiters facades four method the four method accepts a rate limiter name and a closure that Returns the rate the limit configuration that should apply to routes that are assigned to the rate limiter limit configuration are instances of the illuminate cach rate limiting limit 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 four pass a global function request passing the request to

  337. return limit colon colon perm minute 1,000 if the incoming request exceeds the specified rate limit in this case a th000 a response with 4 29 HTTP status code will automatically be returned by larabel if you would like to Define your own response it should be returned by a rate limit you may use the response method so rate limiter call col 4 returns a response of a custom response since rate limiter callmax received the incoming HTTP request instance you may build the appropriate rate limiter rate

  338. limit dynamically based on the incoming request or authenticated user segmented rate limits sometimes 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 IP address to accomplish this you may use the buy method when building

  339. your rate limit so return request user VIP for limit none limit per minute by request to illustrate this feature using another example we could 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 four you can say limit per minute 100 by request user ID or limit per minute 10 by request IP multiple rate limits if

  340. 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 for login rate limit per minute 500 limit per minute three By Request input email attaching rate limiters to rout 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

  341. by default the throt throttle middleware is mapped to the middleware throttle request class however if you are using redus as your application's cash driver You may wish to instruct LEL to use redus to manage rate liming to do so you should use the throttle with redus command or throttle with rdus method in your applications app.php file this method Maps the throttle middleware to the throttle request with Reda middleware

  342. class form methods boothing 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'll need to add a hidden uncore method field to them form the values 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 uncore method with a value of put for convenience you may use the at method blade director to generate the

  343. 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 glasses cross origin resource sharing larl can automatically respond to cores

  344. options HTP requests with values that you configure the options requests will automatically be handled by the handle cores middleware that is automatically included in your applications global global middleware stack sometimes you may need to customize the cores configuration values for your application you may do so by publishing the ches configuration file using the config publish Artisan command PHP Artisan config publish cores this command will place a cores. PHP configuration file within your

  345. applications config directory for more information on cores and course headers please insult the MDM web do documentation on course route caching when deploying your application to production you should take advantage of lille's Route cach using the route cache will drastically decrease the amount of time it takes to register all of your applications routes to generate a route cach execute the

  346. route cash Artisan command PHP Artisan route to Cache after running this command your cach 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 cach command during your Project's deployment you may use the route clear command to clear the route cache okay before we start middleware I'm going to take a quick break

  347. [Music]

  348. e

  349. e e

  350. [Music]

  351. all right middleware middleware provides a convenient me mechanism for inspecting filtering HTTP requests entering your application for example LEL includes a middleware that verifies the user of

  352. your application is authenticated if the user is not authenticated the middleware will redirect the user to your application's login screen however if the user is authenticated the middleware will allow the request to proceed further into the application additional middleware can be written to perform a variety of tasks besides authentication for example a logging middleware might log all incoming requests to your application a variety of middleware are included in LEL including middleware authentication and csrf protection however all user

  353. defined middlewares are typically located in your application's middleware directory to create a new middleware use a 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

  354. 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 ensured 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

  355. into the application allowing the middleware to pass you should call the next call back with the request so return dollar sign next in parenthesis request it's best to Envision middleware is a series of layers HTTP requests must pass through before they hit your application each layer can examine the requests and even even reject it entirely all middleware are resolved via the service container so you may type hit and type hint any dependencies you

  356. need within a middleware Constructor middleware and responses of course a middleware can perform tasks before or after p passing the request deeper into the application for example the following middleware would perform some task before the request is handled by the [Applause] application the middleware object provided to them with middleware closure is an instance of illuminate Foundation configuration middleware and is responsib responsible for managing the

  357. middleware assigned to your application's routes the append method adds the middleware to the end of the list Global parameters and the list of the global middleware if you would like to add a middleware to the beginning of the list you should use the prepend method manually managing lille's default Global middleware if you would like to

  358. manage lel's Global middleware stack manually you may provide lel's default stack of global middleware to the used method then you may adjust the default middleware stack as necessary so middleware use and then add your middleware there as a uh 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 git an appending

  359. 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 group individual route within the group you may accomplish this using the without middleware method you may also exclude a given set

  360. 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 bootstrap app PHP so with middleware as a function you can middleware a pen to group with a group name and then pass in the middleware as an array middleware

  361. 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 Lille automatically applies these middleware groups to the corresponding web.php and api.php files

  362. the web middleware group The API middleware Group if you would like to append or prend middleware to these groups you may use the web and API methods within your applications bootstrap app.php file the web and API methods are convenient 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 L default middleware group entries with a custom middleware of your own or you may

  363. remove a middleware entirely manually managing lille's default middleware groups if you would like to manually manually manage all of the middleware within lille'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

  364. need same thing with the group of API note by default the web and API middleware groups are automatically applied to your applications corresponding web.php and api.php files by the bootstrap app.php file you may assign a 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

  365. middleware with long class names once the middle Ware Alias has been defined in your applications app.php file you may use the Alias when assigning the middleware to routes for convenience some of lel's built-in middleware are Alias by default for example the O middleware is an alias for the authenticate middleware below is a list of the default middleware aliases so we have o o. basic off.

  366. session cache. headers can guest password. confirm precognitive signed described 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

  367. 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 a additional argument additional middleware parameters will be passed to the middleware after the neet after the dollar sign next argument middleware parameters may be specified when defining the route by separating the middleware name and parameters with a colon so middleware

  368. roll colon editor middleware multiple parameters can be deiminated by comma so roll colon editor comma publisher terminable midable middleware sometimes a middleware to 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 service using fast CGI the terminate method will automatically be called after the response is sent to the browser so the terminate method should

  369. 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 applications bootstrap.php file when calling the terminate method on your middleware larel 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

  370. the register method of your app service provider so public function register this app Singleton terminating middleware class csrf protection cross-site request forgies are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user thankfully Lille 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 for request forgeries let's discuss an

  371. example of how this vulnerability can be exploited imagine your application has a SL useremail route that accepts a post request that change the authenticated user's email address most likely this route request an 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 useremail route and submits to the the malicious user's own email address if the malicious website automatically submits the form when this

  372. page is loaded the malicious user only needs to learn 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 postp put patch or delete request for a secret session value that the malicious application is unable to access preventing csrf requests L automatically generates a csrf token for each active user session manager or managed by the

  373. application this token is used to verify that the authenticated user is the person actually man making the request to the application since this token is stored in the user session and changes each time the session is regenerated a malicious application is unable to access it the current session csrf token can be accessed via the request session or via the csrf token helper function

  374. anytime you define a postp 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 in the

  375. 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 larel as an API backend you should consult the larel sanctum documentation for information authenticating with your API and protecting against csrf folder abilities sometimes you may wish to exclude a set of uis from csrf protection for example if you using stripe to process payments and are utilizing their web hook system you will

  376. need to exclude your stripe web hook 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 Lille applies to all routes in the routes web.php file however you may also exclude specific routes by providing their Uris to the validate csrf tokens method in your applications app.php file for convenience the csrf middleware

  377. 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 token middleware which is included in the web middleware Group by default will also check for the X csrf token request header you could for example store the token in an HTML meta tag then you can instruct a library like jQuery to automatically add the token to all request headers this provides simple

  378. convenient csrf protection for your Ajax based applications using Legacy JavaScript technology X xsrf token lville 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 xss XF frf token request header this cookie is primarily sent as a developer convenience since sub JavaScript

  379. Frameworks and libraries like angular and axios automatically place its value in the X xsrf token header on same origin requests note by default the app uh the resources JS bootstrap.js file includes the axos HTTP Library which will automatically send the X xsrf token header for you controllers instead of defining all of your request handling logic as closures

  380. 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

  381. controller Artis and 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 htttp 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

  382. 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

  383. 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 call class you may generate an invocable controller by using the-- invocable option of the make controller

  384. 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 has middleware 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

  385. the controller action so public static function middleware return off new middleware and this extends controller with implements has middleware you may also Define controller middleware as closures which provides a convenient way to define an inline middleware without writing an entire middleware class public static function middleware array return function return request resource controllers if you think of

  386. 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 Lille resource routing assigns the typical create read update and delete crud re routes to controller with a single line of code to get started we can use the make

  387. controller Artisan commands D- resource option to quickly create a controller to handle these actions this command will generate a controller at photocontroller pphp 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 parenthesis of photo controller col and Co class the single route declaration creates

  388. 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 routes by running the route list Artisan command you may even register many resource commands resource controllers at once by passing array to the resources method so route col resources and then an array specifying specific controllers actions handled by resource

  389. controllers resource controllers have git git um get with index get with create post with store get with show get with edit put patch with update and Del El with destroy customizing 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

  390. Missing Method accepts a closure that will be invoked if an implicitly bound model cannot be found for any of the resources routes soft deleted models typically implicit model binding will not retrieve models that have been soft deleted you will instead return and will instead return a 4 for HTTP response however you can instruct the framework to allow softly and models by invoking the with trashed method when defining your resource

  391. route so use HTTP controllers photo controller route resource photos photo controller CL class and then append with trashed calling with trash with no arguments will allow soft Le 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

  392. 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 controllers methods to type hint a model instance you may use the-- model option when generating the controller oops you may provide the-- request option when generating a resource controller to instruct artisen to

  393. generate form request classes for the controller storage and update methods so PHP Artis make controller photo controller um D- model equals photo D- resource D- 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

  394. could pass in accept create store updates 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 Co on API resources and then passing an

  395. array there to quickly generate an API resource controller that does not include the create or edit methods use the DD 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 do notation in your route

  396. declaration so photos. comments in your route resource this route will register a nested resource that may be accessed with Uris like the following so sloto photo as a route binding comments slash then comment as a route binding scoping nested resources lille's implicit model binding feature can be automatically scope can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model by using the

  397. scope method when defining your nested resource you may enable automatic scoping as well has instruct laravel which field the child resources should be retrieved by for more information on how to accomplish this pleas 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

  398. 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

  399. passing a names array with your desired route names so route resource create photos. build by default route resource will create the route parameters for your resource route based on the singz 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

  400. route resource users and then with the parameters array users admin user the example above generates the following URI for the resources show route so SL users SL parentheses admin user scoping resource routes Lille 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

  401. scoped method when defining your nested resource you may enable automatic scoping as well as instruct Layel which field the child resource should be retrieved by this route will register a scoped nested resource that may be accessed with uis like the following /o/ photo comments comment colon slug when using a custom key implicit binding as a nested route parameter Lara will automatically scope the query to retrieve the nested model by its parents

  402. 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 route resource will recate resource uis using English verbs and plural rules if you need to localize the create and edit action verbs you may use the route colon resource verbs method this may be done at the beginning

  403. of the boot method within your applications app service provider so lille's pluralize 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

  404. Spanish public publicar public editar supplementing resource controllers if you need to add additional routes to 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 these supplemental routes so route git photos popular is

  405. above route resource photos note remember to keep your controllers Focus 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

  406. likewise an image may have a single thumbnail these resources are called as single resources meaning one and only one instance of the resource may exist and these scenario you may register a 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

  407. only one instance of the resource may exist so you just have get show get edit or put pass update Singleton resources may also be nested within a standard resource so route Singleton photos. thumbnail can pass in a thumbnail controller class in this example the photos resource would would receive all the standard res resource routes however the thumbnail resource would be a Singleton resource with the following

  408. routes it would have get show get edit and put patch as an update action creatable single creatable single ttin resources occasionally you may want to Define creation and storage routes for a Singleton resource to accomplish this you may invoke the create creatable method when registering the Singleton resource route so route Singleton photos. thumbnail thumbnail controller class creatable and this example the following routes will be registered as you can see a delete route will also be

  409. registered for creatable Singleton resources so get create post store get show get edit put patch update delete destroy if you would like larel to register the delete route for a Singleton resource but not register the creation or storage routes you may utilize the destroyable method so appending to the Singleton API Singleton resources the API Singleton method may be used to register a Singleton resource

  410. 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 to resolve all larel controllers as a result you are able to typ hint any

  411. 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 constructure injection you may also type in dependencies on your controller's methods a common use case for method injection is injecting the illuminate HTP request instance into your controller methods for example public function store and then you can can

  412. 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 the parentheses ID user controller class update you may still typ hint the illuminate HTTP request and access your ID parameter by defining your controller method as follows so in the controller

  413. of the user controller you can add the redirect response to return the user's page HTTP requests introduction laravel's HTTP request class provides an objectoriented way to interact with the current HTTP requests being handled by your application as well as to retrieve the input cookies and files that were submitted with requests interacting with a request accessing the request to

  414. obtain an instance of the current HTTP request via dependency injection you should type in the illuminate htttp request class on your rep closure or controller method the incoming request instance will automatically be injected by the Lille service container as mentioned you may also typin the HTTP request class on a route closure the service container will automatically inject the incoming requests into the closure when it is executed so if your controller method is also expecting input from a route

  415. parameter you should list your route parameters after your other dependencies for example if your route is defined like so route put user with bry's 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 controller method as follows controller extends controller passing in the request to the update function returning

  416. the redirect response HTP 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 symphony comp component htb 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

  417. fbar the path method will return fuar so your uh dollar sign URI equals request U 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 uh you may use the asteris character as a wild card when

  418. utilizing this method so if request is admin asterisk using the route is Method you may determine if the incent request has matched a named route so if request SL route is um is admin. asterisk retrieving the request URL to retrieve the full url url for the incoming request you may use the URL or full URL methods URL method will return the URL

  419. 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 you 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 called request full URL with query and in the array you said type is phone it would if you would like to get the current URL

  420. 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 requests via the host HTTP host and scheme and update scheme and HTTP host methods that's from the request object so retrieving the request method the method the method method will return the

  421. HTTP verb for the request so you may use the is Method method to verify that the HTTP verb match mates a given string so method equals request method request headers you may retrieve a request header from the HTP 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 optionable second second argument that will be returned if the headers are not present on the

  422. request the has header method may be used to determine if the request contains the 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

  423. like to retrieve an array of IP addresses including all of the client IP addresses that were forwarded by proxies you may use the IPS method 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 larel provides several methods for inspecting the incoming requests requested content types via the

  424. accept header first the get acceptable content types method will return an array containing all of the content types accepted by the requests so get acceptable content types the accepts method accepts an array of content types and returns true if any of the content types are re 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

  425. content types are accepted by the request null will be returned since many applications only serve HTML as or Json you may use the expects Json method to quickly determine if the incoming request expects a Json response psr-7 requests the psr-7 standard specifies interface for HTTP messages including requests and responses if you would like to obtain an instance of a PSR 7 request

  426. instead of a larel request you would first need to install a few libraries larl uses the symphony HTTP message Bridge component to convert typical larel requests and responses into PSR 7 compatible implementations once you have installed these libraries that's composer require Symphony par HTTP message bridge and composer require nompc PSR 7 you may obtain a psr-7 request by typ penting the request interface on your rep

  427. closure or controller method so that typeint is used PSR server request interface and then passing that into the function if you return a PSR 7 response note instance from a router controller it will automatically be converted back to a larel 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 method this method may be used

  428. regardless of whether the incoming request is from an HTML form or is an xhr request so input request all using the collect method you may retrieve all of the incoming request input data as a collection the collect method also allows you to retrieve a subset of the incoming requests input as a collection so collect users each function string user and you can break that down retrieving an input value using a few

  429. simple methods you may access all all the user input from 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 then you can have 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

  430. the request when working with forms that contain array inputs use dot notation to access the [Applause] 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 and

  431. 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 retri 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 Json you may

  432. even use dot syntax to retrieve values that are nested within Json arrays or objects retrieving stringle input values instead of retrieving the inputs the request input data as a primitive string you may use this string method to retrieve the request data as an instance of illuminate support string B 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

  433. you may use the Boolean method to retrieve these values as booleans the Boolean method returns true for one one in quotations true true is a string on is a string and yes is a string all other vales will return false so that would be ar the the parameter archived as request Boolean with the parameter archived retrieving date input values for convenience input values containing dates and times may be retrieved as

  434. carbon instances using the date method if the request con 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

  435. 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 is the second argument retrieving input Dynamic properties you may also access user input using Dynamic properties on the illuminate HTP request

  436. instance for example if one of your applications forms contains a name field you may access the value of the field like so request name when using Dynamic properties Lille will First Look for the par parameters value and the request payload if it is not present Lille will search for the field in the Matched routes 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 accept methods both of these methods accept a single array

  437. 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

  438. array the has method will determine if all of the specified values are present so has name or email the has any method returns true if any of the specified values are present so has any name or email the wi 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 Wi has method that will be executed if the specified value is not present on the request so when has name and then the second parameter is not if you would like to Define if a value

  439. is present on the request and is not an empty string you may use the filled method if request filled name the any field method recur the any field method returns true if any of the specified values is not an empty string so the wind field method will execute the given closure if a value is present on the request and is not an empty string so Windfield name a second closure may be passed to the Windfield method that will be executed if the specii value is not

  440. filled so wind filled name and then if it's not here's a 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 in additional input into the request existing input data to accomplish this

  441. 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 exists within the request input data so request merge if missing votes old input laral allows you to keep input from one request during the next request this feature is particularly useful for pre-populating forms after detecting

  442. validation errors however if you are using lils included validation features it is possible that you will not need to manually use these session input flashing methods directly as some of lel's built-in validation facilities will call them automatically flashing input to the session The Flash method on the illuminate HTTP request class will will Flash the current input to the session so that it is available during the user's next request of the application so request flash you may

  443. 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 so flash only the username or email or Flash accept 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

  444. input method so re return redirect form with input return redirect routes retrieving retrieving old input to retrieve flashed input from the previous request invoke the old method on an instance of HTTP request the old method will pull we previously flashed input data from this session so username request old username LEL also provides a global old helper if you are use displaying old input within a blade

  445. 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 from requests all cookies created by the LEL framework are encrypted and signed with an authentication code meaning they will be considered invalid if they have been

  446. changed by the client to retrieve a cookie value from the request use the cookie method on an eluminate illuminate HTTP request instance so value request cookie name input trimming and normalization by default laral 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

  447. have to worry about these normal 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 middleware stack by invoking the middle move method in your application's bootstrap app.php file so in that middleware move you can remove convert empty strings to null and trim strings if you would like to disable string string trimming an empty string conversion for a subset of request to

  448. your application you may use these trm strings and empty strings to null middleware methods within your applications 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 and strings to null except function which route files retrieving uploaded files you may retrieve upload files from an HTTP request instance using the file method

  449. or using Dynamic properties the file method returns an instance of the HTTP uploaded file class which extends the PHP um 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 Define 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

  450. no problems uploading the file via the is valid method the uploaded file class also contains methods for accessing the files the full the files 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

  451. the client so path request photo path extension request photo extension other file methods there are a variety of other methods a ailable on uploaded file instances check out the API documentation for the class for more information regarding these methods storing uploaded files to store an upload 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 diss which may be a location on your local file system or a cloud

  452. storage location like Amazon S3 the store method accepts the path where the file should be stored relative to the file systems configured root directory this path should not contain a file file name since a unique ID will automatically be generated to serve as the file name the store method also can accepts an optional second argument for the name of the dis that should be used to store the file the method will return the path of the file relative to the

  453. disk's route so path requests photo store images path request uh photo 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 TL SSL SSL certificates you may notice your application s does not generate

  454. https links when using the URL helper typically 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 proxy middleware that is included in your LEL application which allows you to quickly customize the load balancers or proxy that should be trusted by your application your trusted proxies should be specified using the trust proxies middleware method in your applications

  455. 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 header's value should be request header X forwarded awsb if your load balancer uses the stand standard forwarded header from RFC 7239 the header's value should be request header

  456. forwarded for information on the constants that may be used in the header's value check out symphony'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 lar will respond to all requests it will re it receives regardless of the

  457. content of the HTTP requests 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 your web server such as engine X 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 larel to only respond to certain host names you may do so by enabling the trust host middleware for your application to enable the trust

  458. host middleware you should invoke the trust host middleware method in your applications 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 truss hosts at l. test for example by default requests coming from subdomains

  459. 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 uh middleware trust host at ll. test subdomains false HTTP responses

  460. HTTP responses creating responses strings and arrays all routes and controllers should return a response to be sent back to the user's browser larel 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 convert the string into a full HTTP response so route get return hello world in addition to returning strings from your routes and controllers you may also return arrays

  461. the framework will convert 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 excuse me 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 typically you won't just be returning simple strings or arrays when you route actions instead you'll be returning full HTTP response instances or views returning a full response instance

  462. allows you to customize the responses HTTP status code and headers a response instance inherits from the symphony component HTTP Foundation response class which provides a variety of methods for building hcp responses by default requests coming from subd eloquent models and collections you may also return eloquent omm models and

  463. collections directly from your routes and controllers when you do larvo 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 keep 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

  464. before 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 so instead of the method cache control metalware larl includes a cache. 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

  465. and should be separated by a semicolon if e tag is specified in the list of directives an mt5 hash of the response content will automatically be set as the eag 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

  466. used less frequently generally these arguments have the same purpose and meaning as the arguments that would be given to php's ative set cookie 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 CU cookies for attachment to the response when it is sent the Q 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

  467. browser generating cookie instances if you would like to generate a symphony component HTTP Foundation cookie instance that can be attached to response instance at later time you may use the global cookie helper the cookie will not be sent back to the client unless it is attached to 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

  468. 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 facad um expire method to expire a cookie so cookie cool and colon expire name cookies and encryption by default thanks to the illuminate cookie HD or middleware encrypt cookies middleware all cookies generated by Lille are encrypted and signed so they can't be

  469. 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 applications bootstrap app.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 a redirect

  470. response instance 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 featur utilizes this session make sure the route calling the back function is using the web middleware group so route post user profile

  471. 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 redirect uh return redirect route if your route has parameters you may pass

  472. 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 with 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

  473. parameter you can specify the column in the route parameter definition or you can override the git 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 re return redirect action and then passing a controller if a controller route requires parameters you may pass them as a second argument to

  474. 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 away method which creates a redirect response without any additional URL encoding 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

  475. when you flash a 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

  476. Bram 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 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

  477. response instances when the response helper is called without arguments and implementation of the contract's routing response Factory contract is returned this contract provides several helpful methods 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 a respones Content you should use the view method so return response view of course if you do not need to pass a custom HTP

  478. 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 Json P resource you may use the Json method in combination with the with callback method so return response Json with the

  479. 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

  480. method warning Symphony HTTP Foundation which manages file downloads requires the file being downloaded to have an asky 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 stream download method in this scenario this method accepts a callback file name and an option array of headers as its argument file responses the file method

  481. may be used to display a file such as an image or PDF directly in the user's browser instead of initiating a download this method accepts the absolute path to the file as its first argument and an array of headers as its second argument response macers 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 applications service providers such as the app

  482. providers app service provider service provider so response col and macro in the boot method the macro function accepts a name as its first argument and a closure as its second argument the macros 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

  483. 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 lelt view templates are usually written using the blade templating in language a simple view might look look something like this you have the HTML of a body with an H1 of

  484. 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 greeing view name then in the second uh second parameter an array

  485. with a 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 SL viw instead of writing their front end templates in PHP via blade many developers have begun to prefer to write their templates using react or view larl makes this painless thanks to inertia a library that makes it a cinch to tie your react viw front

  486. end to your Lal back end without the typical complexities of building an SBA our Breeze and jet stream starter kits give you a great starting point for your next lay application powered by inertia in addition the lay boot camp provides a full demonstration of building a larel application powered by inertia including examples in View and react creating and rendering views you

  487. may create a view by placing a file with theplay PHP extension in your application's Resources slvs directory or by using the makeon view greeting the blade. PHP extension informs the framework the file contains means a blade template blade templates contain HTML as well as blade directives that allow you to easily Echo values create if statements iterate over data

  488. and more once you've created a view you may return it from one of your applications routes or controllers using the global view helper so route get at slash return view of greeting you may also be views may also be returned using the view facade so return view colon colon make greeting as you can see the first argument pass 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

  489. 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 views directory do notation may be used to reference nested views for example if your view is stored at resourcesview admin profile. blade. PHP you may return it from one of your applications /c controllers like so return view admin

  490. not profile warning this view directory name should not contain the dot character creating the first available View using the view facade 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 dimin determine if a view exists if you need to determine if a view exists you

  491. 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

  492. complete array of data to the view helper function you may use the width method to add individual pieces of data to the view the width method returns an instance of the view object so that you continue the can continue chaining methods before returning the view so return view greeting with name is Victoria with occupation comma astronaut sharing data with all views occasionally you may need to share data with all

  493. views that are rendered by your application you may do so using the view facad share method typically you should Place calls to the share method within a service providers boot method you are free to add them to the app providers app service provider class or generate a separate service provider to house them view composers view composers are callbacks or class methods that are

  494. called when a view is rendered if you have data that you want to be bound to a uh 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 particular piece of data typically view composers will be registered within one of your application's service providers in this

  495. example we'll assume that the app provider's app service provider will house this logic we use the view facades composer uh view view facades composer method to register the view composer larel does not include a default directory for class-based view composers so you are free to organize them however you wish for example you could create an app view composers directory to house all of your applications view composers in the class app service

  496. provider you can uh in your boot function you can have facades back SL viw colon col 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

  497. public function of construct with a protected user repository of users and then you combine data to the view public function compose view view with count as you can see all view composers are resolved via these service containers so you may type hint any dependencies you need within a composer's Constructors so in this example public function construct protected user repository

  498. 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 to the composer method the composer method also accepts the asteris character as a wild card 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 instantized instantiated and instead of waiting until the view is about to

  499. 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 larl will determine if a compiled version of The View exists if the file exists Lara will then determine if the uncompiled view has been modified more recently than the

  500. compiled view if the compiled view either does not exist or the uncompiled view has been modified lar larel will recompile the view compiling views during the requests may have a small negative impact on performance so laral provides the view cach Artisan command to pre-compile 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

  501. you may use the view clear command to clear the view cache blade templates in introduction blade is the simple yet powerful templating agent 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

  502. zero overhead to your application blade template files uses 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 pass to the blade View using the view helper's second argument route do uh colon get/ return

  503. view greeting pass in those name supercharging Blade with Live Wire want to take your blade templates to the next level and build Dynamic interfaces with ease check out larl Livewire Livewire allows you to re to write blade components that are augmented with Dynamic functionality that would typically only be possible via front-end Frameworks like react or view providing a great approach to building modern reactive front ends without the complexities client side rendering or

  504. 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 blades double bracket Echo statements are

  505. 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 parenthesis HTML entity encoding by default blade

  506. and larel E function will double encode HTML entities if you would like to disable double encoding call the blade col and colon without double encoding method from the boot method of your app service provider by default blade double uh bracket statements are automatically sent through php's HTML special cars function to present EXs xss attacks if you do not want data to be escaped you

  507. may use the following syntax hello and then only single bracket with two uh quote two exclamation points on each side dollar score dollar name warning 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

  508. 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 larl 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 uh

  509. double double curly brackets name expression will remain Untouched by the blade and 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 a if rendering Json sometimes you may pass an array to your view with the intention of rendering as

  510. Json in order to initialize a JavaScript variable for example script bar app then you can pass in PHP Echo Json and code however instead of manually calling Jon in code you may use the Js from method directive the from method accepts the same arguments as php's Json and code function however it will ensure that the resulting Json is a part properly escaped for inclusion within HTML quotes the from method will return a string

  511. 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 lay application skeleton include a JS capital J lowercase s facade which provides convenient access to the functionality within your blade templates so script VAR app equals double curly brackets JS colon colon from array warning you

  512. 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 you 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

  513. is displayed and there is is echoed out blade directives in addition to template inheritance and displaying data blade also provides uh convenient shortcuts for common PHP control structures such as conditional Loops statements these shortcuts provide a very clean tur 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

  514. else and at and if directives these directives function identically to their PHP [Applause] 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 is set and at empty directives may be

  515. used as convenient shortcuts for their respective PHP functions authentication directives the at off and at Guest directives may be used to quickly determine if the current user is authenticated or as a guest if needed you may specify the authentication guard that should be checked when using the at o or at gu guest directive so at o admin or at Guest admin environment directives you may check if the application is running in the production environment

  516. using the ACT production directive so app 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 MV 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

  517. section missing directive to determine if a section does not have content so as 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 as session within the at session and at end session directives will be evaluated within the at session directives contents you may Echo the valued

  518. variable to display the session value so at session status switch statements switch statements can be constructed using the at switch at case 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 directed functions identically to their PHP counterparts so at four four each four

  519. else empty wow 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're 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 users as user if user type equals one at continue or if the user number equals five at break at for

  520. 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 interation through the loop so at for each users as

  521. user at if Loop first this is the first iteration if you are an nested Loop you may access the parent Loops Loop uh dollar sign Loop variable via the parent property so at for each users as user at for each nested in there user post as post if dollar sign Loop parent first this is the first iteration of the parent Loop the dollar sign Loop

  522. variable also contains a variety of other useful properties so 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

  523. 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 app PHP is active equals false then in the app class method in the span you can add specific variables likewise the at style direcor may be used to conditionally add inline CSS styles to your HTML element so a span of at Style

  524. with the array of background color red for convenience you may also use the app 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

  525. 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 readon directive may be used to indicate if a given element should be readon 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

  526. similar functionality and offer several benefits over the at include directive such as data and attribute binding so blades atribute 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

  527. 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 include a view which does not exist Lille will throw and 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

  528. 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 at the the include first directive so at include first warning you should avoid using the underscore uncore d _ andore file uncore constants in your Rel view since they were referred to the location

  529. 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 toer over while the third argument is the VAR variable name that will be assigned to

  530. 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 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

  531. passing in the jobs variable as a job and then view. empty warning views rendered via at each do not include 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 div piece of JavaScript into the Page's header using

  532. 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 app push or app prepend directives the app push once and app 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

  533. direcor to execute a block of plain PHP within your template so PHP dollar counter equals 1 or if you only need to use PHP to important 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 at models flight Alias is it as flight model comments blade also allows you to Define comments in your views however

  534. unlike HTML comments blade comments are not included in the HTML return by your application so that's double curly brackets with a dash dash on each end this common 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

  535. create a class-based component you may use the makeon component Artisan command to illustrate how to use components we will create a simple alert component the makeon component command will place the component in the app View components directory so PHP artisan make component alert 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

  536. 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 subdirector so PHP artisan make component forms SL input the command above will create an input com 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

  537. component with only a blade template and no class you may use the-- view flag when invoking the make component command the command above will create a blade file at formin put. blade. PHP which can be rendered as a component via x- forms. input as a HTML tag manually registering package components when writing components for your own

  538. 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 alas you should typically register your components in the boot method of your packages service provider so public function boot blade component package alert passing the alert class once your component has been registered it may be

  539. rendered using its tag Alias so x- package D alert as an HTML uh string alternatively you may use the component namespace method to autoload component glasses by convention for example a night shade package might have calendar and Color Picker components that reside within the package views components Nam space this will allow the usage of package

  540. components VI their vendor namespace using the package colon package-name colon colon syntax so x- Nightshade colon colon calendars uh for example as an HTML tag blade will automatically detect the class that's linked to this component by Pascal casing the component name subdirectories are also supported using dot notation to display a component you may use a blade component tag within one of your blad BL

  541. templates blade component tags start with the string x- 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

  542. located at components input SLB buttons. PHP we may render it like x- inputs. button if you would like to conditionally render your component you may Define a should render method on your component class if the should render method returns false the

  543. component will not be rendered passing data to components you may P pass data to Blade components using HTML attributes hardcoded primitive values may be passed to the compon component using simple HTML attribute strings PHP expressions and variables should be passed to the component via attributes that use the coling character as a prefix so in your HTML tag x- alert type equals error while colon message equals

  544. dollar sign message as a PHP attribute you should Define all of the component datri 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 string of message and then when you're passing it to the view it is automatically there when your component

  545. is rendered you may display the contents of your components public variables by echoing the variables by name so alert Das 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

  546. component con structure 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- profile

  547. colon user ID colon name is short attribute syntax but it's equivalent to colon user ID equals dollar sign user ID in Cal syntax escaping attribute rendering since some JavaScript Frameworks such as Java such as Alpine JS also include Colon D prefix attributes you may use a double colon do colon colon prefix to inform blade that the attribute is not a

  548. PHP expression for example given the following component x- button colon colon class equals danger is the leading the following HTML will be rendered by blade it it will escape the colon 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 hasn't

  549. is selected method public function is selected 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 uh 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 classes

  550. render method however in order to access this data you should only return a closure from your components 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

  551. will contain all the attributes that were present on the HTML tag the slot element is an support/ HTML string instance with the contents of the component 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 LEL service container

  552. you may list them before any of the component data attributes and they will automatically be injected by the container so create the public instance component instance in your public function Constructor you could have public alert Creator assigned to Dollar score dollar Creator public string dollar type public string dollar message hiding attributes SL methods if you would like to prevent some public methods or properties from being exposed as variables to your component template

  553. 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

  554. error colon message equals dollar sign message class equals mt-4 all the attributes that are not part of the components constructure will automatically be added to the component attribute bag this attribute bag is automatically made available to the component via the dollar score dollar sign attributes variable all of the attributes may be rendered within the component by echoing this variable so

  555. div double curly brackets dollar sign attributes has the component context warning using directives such as ATV within component tags is not supported at this time for example x- alert colon live equals at EnV production will not be compiled def default SL merged attributes sometimes you may wish to specify default values for attributes or merge additional values into some of the

  556. components 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 d d double curly bracket for attributes merge and you can in that array pass in classes to be merged to that attribute bad

  557. 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 rendered HTML of the component will appear like the following you 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

  558. 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 mer merge method onto the class method so button of attributes

  559. class you can merge the type is button note if you need to compile condition additionally 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

  560. will be overwritten for example a button components implementation may look like the following button attributes merge type button 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- button type is submit the rendered HTML the button component in this example would be button type equals submit if you would like an attribute

  561. other than class to have its default value and injected values joined together you may use the preens method in this example the data- controller attribute will always begin with profile Dash controller and any additional injected data Dash controller values will be placed after this default value retrieving and filtering attributes you may filter attributes using the filter method this method accepts a closure which should return true if you wish to retain the attribute in the attribute

  562. bag so attributes filter with the function string of value string of key that key is equal to Fu 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 who Keys begin with the 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

  563. 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 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

  564. component you may retrieve a specific attributes value using the git method so dollar sign attributes get class reserved keywords by default some keywords are reserved for blades 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

  565. component slots are rendered by echoing the dollar sign slot variable to explore this concept let's imagine that an alert component has the following markup so this is alert bl. PHP with a div of class alert and alert D danger it has a double curly bracket dollar sign slot we may pass content to the slot by injecting content into the component so in your blade file you can have x- alert

  566. 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 Das tile we can have double brackets dollar sign title and a dollar

  567. sign slot you may Define the content of the named slot using the x- slot tag any content not uh within an explicit x- slot tag we pass the component in the in the dollar sign slot variable so in your component x- alert you can have xlot colon title and

  568. passing in that title as a string you may invoke a slots is empty method to determine if the slot contains content so span class alert title dollar sign title uh if slot is empty this is default content if the slot is empty at else slot Additionally the has actual content method may be used to determine if the slot contains any actual content

  569. that is not an HTML comment if dollar sign SL slot has actual content this scope has non-comment content scoped slots if you have used a JavaScript framework such as view 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 lville by defining public methods or properties on your component and accessing the component within your slot via the

  570. component dollar sign 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-s slot colon title dollar sign component method format alert server error slot attributes like blade components you may assign additional attributes to slots such as CSS class

  571. names so x-s slot colon heading classes font Das 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 ATT dollar sign attributes uh Arrow class border dollar sign heading attributes class text large for example inline component

  572. views for very small components it may feel cumbersome to manage both the component class and the component's view template for this reason you may return the component markup directly from the render methods of public function render string return blade generating in nine view components the create a component that renders an inline view you may use the inline option when executing the make component

  573. command PHP Artisan May component alert uh-- 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 lel's builtin Dynamic - component component to render the component based on a runtime value or variable for example dollar sign component name equals secondary Das button um x- Dynamic D component with colon

  574. component equals dollar sign component name manually registering components warning the following documentation on manually registering components is primarily applicable to those who are wanting L who are writing larel packages that include view components if you are not writing a package this portion of the com component documentation may not be relevant to you when writing components for your own application components are automatically discovered within the app view components directory

  575. and resourcesview components directory however if you are building a package that utilizes blade components or placing components in nonconventional directories you will need to manually register your component class and it's HTML tag Alias so that larl knows where to find the component you should typically register your components in the boot method of your packages service service provider once your component has been registered uh it may

  576. be rendered using its tag alias x-package alert autoloading package components alternatively you may use the component uh namespace method to autoload component classes by convention for example a Nightshade package might have calendar and Color Picker components that reside within the package views components name space this will allow the usage of package components by their vendor

  577. namespace using the package-name colon colon syntax x- Nightshade colon calendar x- Nightshade colon colon color Pinter 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 Anonymous components similar to inline components Anonymous components provide a mechanism for managing a component via a single file however

  578. 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 res resources views components directory for example assuming you have defined a component at resources views components alert. blade. PHP you may simply render it like so x- alert you may also use the dot character to indicate if a component is nested deeper inside the component's directory for example assuming the component is

  579. defined at resources views components SL inputs SLB button. blade. PHP you may render it like so x- inputs do button Anonymous index components sometimes times when a component is made up of many blade templates You may wish to group the given component templates within a single directory for example imagine an accordion component with the following directory structure accordion. blade. PHP accordion item. blade. PHP

  580. 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

  581. templates thankfully blade allows you to place an index. blade. PHP file within a component template directory when an index.pl 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 accordian index.php accordian item. blade. PHP

  582. data properties and attributes since Anonymous components do not have an Associated class you may wonder how you may different differentiate which data should be passed to the component as variables and which attributes should be pass passed in the component's attribute bag you may specify which attributes should be considered data variables using the uh at props directive at the at the top of your components blades template all other attributes on the component will be available via the components

  583. 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- alert type equals error colon message that's a prop as message sometimes you may want to access data from a

  584. 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-Men and a child x- men. item Xmen Color Purple X menu. item bunch of those the Xmen component may have an imp implementation like the following so in the X menu component at props color is gray um with the a US of

  585. attributes merge with some classes and then a slot because the color prop was only passed into the parent Xmen it won't be available inside X menu. item however if we use the aware directive at aware we can make it available using the X menu item as well so at aware color is gray warning the aware directive cannot access parent data that is not

  586. 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

  587. with Lille in addition to the default path the anonymous component path method accepts the path to the anonymous comp component location as its first argument and an optional name space 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 service providers when component paths are registered within a specific prefix specified prefix as in the example above

  588. they may be rendered in the blade components without a corresponding prefix as well for example if a PL 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 the anonymous component path method so blade colon colon Anonymous component path then passing in the component there when a prefix is provided components within

  589. that namespace may be rendered by prefixing to the component's namespace to the component name when the component is rendered x- 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

  590. 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 the title and then body of to-dos and we'll pass in a slot applying the layout component once the layout component has been defined we may create a blade view that utilizes the component in this example we will Define a simple

  591. view that displays our task list so tasks. blade. PHP as an x- layout remember content that is injected into component will be supplied to the default slot variable within our layout component as you may have noticed our layout also respects a dollar sign time title slot if one is provided otherwise a default title is shown we may inject a custom title from our task list View

  592. using the standard slot 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 git tasks and return the view tasks and passing the task parameter is Task colon colon all

  593. 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

  594. this layout as a single blade view so ah 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

  595. application let's define a child page that inherits the layout extending a 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

  596. 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 note contrary to the previous example the cbar section ends with at and section instead of at show the at

  597. and section directive will only Define a section well 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 CSR 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

  598. 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 as 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 uncore method field to spoof these HTP verbs the app method blade directive can create this field for you so at method put

  599. 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 at the dollar sign message variable to display the error message so create. blade. PHP um is invalid and then you have at error title with dollar sign message since the error

  600. directive compiles to an if statement you may use the 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 paramet 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

  601. 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 dis required by your child views so at push scripts then you can have the script Source there if you would like to at push content if a given Boolean expression evaluates the true you may use the push if

  602. 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 preen content unto the beginning of a stack you should use the at Preen directive service injection the at inject directive may be used to retrieve a service from the Lille service container this first argument passed to

  603. 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 appserv metric service render in 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

  604. blade template string and an optional array of data to provide to the template Lille renders inline blade templates by writing them to the storage framework views directory if you would like Lille to remove these temporary files after rendering the blade template you may provide the delete cached view argument to the method method rendering blade fragments when using front end Frameworks such as turbo and HDMX you may occasionally need to

  605. only return a portion of a blade template within your HTTP response blade fragments allow you to do just that to get start place a portion of your blade template within at fragment and at n 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 in included in the outgoing HTTP response so return view dashboard

  606. passing in the props of users is call do sign 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

  607. fragments will be concatenated together uh the fragments will be concatenated together view dashboard users fragments view dashboard users users fragments if dollar sign 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 call back with the expression that the

  608. directive contains the following example creates an at datetime VAR directive which which formats a given dollar sign VAR which should be an instance of date time as you can see we will change the format method onto whatever expression is passed into the directive so in this example the final PHP generated by this directive will be PHP Echo dollar sign VAR format warning after updating the logic of a blade directive you will need to

  609. 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 dollar uncore uncore two string method will be invoked the underscore uncore two string 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

  610. 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 string B method the string B method accepts a closure this closure should typ hint the type of object that is responsible for rendering typically the string B method should be invoked within the boot method of your application's app service provider class once your custom Echo Handler has

  611. 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 Define quickly Define custom conditional directives using closures for example let's define a custom conditional that checks the

  612. configured default disc for the application we may do this in 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 V actually before I start that I'm going to take a take a quick break

  613. [Music]

  614. in [Music]

  615. there [Music]

  616. oh [Music]

  617. all right let's continue diving deeper for those who are still still joining we are close to about close close to a third of the way through maybe a little bit a little bit over a third not not half but not not a quarter um we're diving deeper and we're going into mail

  618. so introduction sending email doesn't have to be complicated Lille provides a clean simple email API powered by the popular Symphony mailer component larl and Symphony mailer provide drivers for sending email via SMTP mail gun postmark resend Amon Amazon sces and send mail allowing you to quickly get started sending mail through a local or

  619. cloud-based service of your choice configuration lille's email Services may be configured via your applications 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 used postmark to send transactional emails

  620. while using Amazon sces to send bulk emails within your mail configuration file you will find a mailer's configuration array this array contains a sample configuration entry for each of the major mail drivers and transports supported by larl 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

  621. trans uh trans Choice function you may use the built oops that was what we had already read the API based drivers for driver transport pre pre prerequisites the API based driers such as mail gun postmark resend and mailer send are often simpler and faster than sending mail via SMTP servers whenever possible we recommend

  622. that you use one of these drivers mail gun driver to use the mail gun driver install symphony's mail gun mailer transport via composer so composer require Symphony mail gun mailer Symphony HTTP client next set the default option in your applications config mail.php configuration file to mail gun and add the following configuration array to your array of mailers so mail gun transport client timeout after configuring your application's default mailer add the

  623. following options to your config services. PHP configuration file mail gun domain secret endpoint and scheme and if you are not using the United States mail gun region you may Define your Region's endpoint in the services configuration file postmark driver to use the postmark driver install symphony's postmark mailer transport via composer next set the default option in your applications mail.php configuration file to postmark and after configuration configuring your

  624. application's default mailer ensure that your config Services configuration file contains the following options so postmark a token if you would like to specify the postmark message stream that should be used by a given mailer you may add the message stream ID configuration option to the mailer's configuration array this configuration array can be found in your application's config mail.php

  625. configuration file postmark transport message stream ID this way you able to set up multiple most postmark mailers with different message streams resent driver to use the resent driver install resent PHP SDK via composer next set the default option in your applications configuration file to resend and after configuring your applications default mailer ensure that your config services. PHP configuration file contains the

  626. following options resend key SCS driver to use the Amazon sces 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 sces and verify that your config Services PHP configuration file

  627. contains the following options SC key secret region to utilize AWS temporary credentials via session token you may add a token key to your application's SCS configuration to interact with SS's subscription managements features you may return the x-s list management options header in the array returned by

  628. the headers method of a mail message so public function headers return new headers if you would like to Define additional options that Lille should pass to the AWS SDK send email method when sending an email you may Define an options array within your sces configuration mail or send driver mail or send a transactional email and SMS service maintains their own API based mail driver for larel the package M containing the driver may be installed

  629. via the composer package manager composer requir mail or send LEL driver once the package is installed add the mailer send API key environment variable to your applications. EnV file in addition the mail mailer environment variable should be defined as mailer send finally add mailer send to the mailer's array in your applications mail.php configuration file to learn more about mailer send including how to

  630. use hosted templates consult the mail or send a driver documentation failover configuration sometimes an external service you have configured to send your applications mail may be down in these cases it be 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

  631. your application's failover mailer should contain an array of mailers that reference the order in which configured mailers should be chosen for delivery so mailers failover you can have transport 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

  632. default EnV mail mailer failover round robin configuration the round robin transport allows you to distribute your mailing workload across multiple servers 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 applications round robin mailer contain should contain an array of mailers that reference which configur mailers should be used for

  633. 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 conf 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

  634. which helps to achieve High availability the round robin transport provides load balancing when building Lille applications each type of email sent by your application is represented as a mailable class these classes are stored in the app slma directory don't worry if you don't see this directory and application since it will be generated for you when you create your first mailable class using the make mail Artisan command writing mables once you have generated a mailable class open it

  635. 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 male mailable envelope object that defines the subject and sometimes the recipients of the message the content method returns an illuminate mail mailable content object that defines the blade template that will will be used to generate the message content configuring the sender using the envelope first let's explore configuring

  636. 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 add it to each mailable class you generate instead you

  637. may specify a global from address in your config mail.php configuration file this address will be used if the if no other from address is specified within the mailable mailable class in addition you may Define a global reply to address within your mail.php configuration file configuring The View within a mailable classes content method you may Define the

  638. 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 templating 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

  639. 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 a template name which will be used to render the contents of the email you are free to Define both an HTML and plain text version of your message so return new content View and text for clarity the HTML parameter may be used as an

  640. 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 H the emails HTML there are two ways you may make data available to your view first any public property to find on your mailable class will automatically be made available to the view so for example you may pass data into your

  641. 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 uh order price to the template via the width parameter if

  642. you would like to customize the format of your emails Data before it is sent to the template you may manually pass your data to the view via the content definitions with parameter typ typically you will still pass data via the mailable classes Constructor however you should set the data to protected or private property so the data is not automatically made available to the [Applause] template once the data has been passed to the width method it will automatically be available in your view

  643. so you may access it like you would access any so you you may access it like you would access any other data in your blade templates 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 fromont path method provided by the attachment class when attaching files to a message you may also specify the

  644. display name and or M type for the attachment using the As and with m method attaching files from diss if you have stored a file on one of your file system discs you may attach it to the email using the from Storage attachment method of course you may also specify the attachments name and mime

  645. type the from Storage dis method may be used if you need to specify a storage disc other than your default dis 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 from data method accepts a closure which resolves the raw data bytes as well as the name that the

  646. attachment should be assigned so attachment from data with mime application types inline attachments embedding inline attachments into your emails is typically cumbersome however larl provides a convenient way to attach images to your emails to embed an inline image use the embed method on the dollar sign message variable within your email template larel automatically makes the dollar sign message variable available to all of your email templates

  647. so you don't need to worry about passing it in manually so here's an image image source dollar sign message embed path to image warning the dollar sign message variable is not available in plain text message templates sends 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 embed data method on the message variable when calling the embed data method you will

  648. 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 represents that photo when that is the case wouldn't it be convenient to Simply pass the photo model to the attached

  649. method attachable objects allow you to to do just that to get started implement the contracts male attachable interface on the object that will be attachable to messages the interface dictates that your class defines a two male attachment method that returns a male attachment instance once you have defined your attachable object you may return an

  650. instance of that object from the attachments method when building an email message of course attachment data may be stored on a remote uh file storage service such as Amazon S3 so larel also allows you to generate attachment instances from data that is stored on one of your application's file system diss in addition you may create attachment instances via data that you have in memory to accomplish this provide a closure to the from data

  651. method the closure should return the raw data that represents the attachment LEL 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

  652. headers method should return an illuminate mail mailable 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 thirdparty email providers such as mail gun 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

  653. envelope definition if your application is using the mail gun driver you may consult mail guns documentation for more information on tags and metadata likewise the postmark documentation may also be consulted from more information on their support for tags and metadata if your application is using Amazon SCS to send emails you should use the metadata method to attach SCS tags to the message customizing the symphony message lille's mail capabilities are

  654. powered by Symphony mailer LL 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 to deeply customize the message before it is sent to accomplish this Define a using param on your envelope definition markdown maila bles markdown mailable messages allow you to take advantage of the pre-built templates and

  655. components of mail notifications in your mail lables since the messages are written and markdown laravel is able to render beautiful responsive HTML templates for the messages while also automatically generating a plain text counterpart generating markdown mail lables to generate a mailable with the corresponding markdown template you may use the D- 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

  656. view parameter so return new content markdown mail. orders. Shi writing markdown messages markdown maila bles use a combination of Blade components and markdown syntax which allow you to easily construct mail messages while Levering leveraging lel's pre-built email UI components for example xmail message X mail button xmail message note do not

  657. excess IND use excess indentation when writing markdown emails per markdown standards markdown Partiers 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

  658. 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 published

  659. Artisan command to to publish the levelt dmail asset tag so vendor publish t- tag equals lelt dmail 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

  660. you like customizing 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 lille's markdown components you may make you may place a

  661. CSS file within the HTML themes directory after naming and saving your CSS file update the theme option of your application config mail.php configuration file to match the name of your new theme to customize the theme for an individual mailer mailable you may set the dollar sign 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

  662. message use the two method on the mail facade the two method accepts an email address a user instance or a collection of users if you pass an object or collection of objects the mailable mailer will automatically use their email Emil 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

  663. 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 pens email addresses to the Mel's list of recipients each iteration to the loop will send another email to every recipient therefore you should always

  664. recreate the mailable instance for each recipient so for each Taylor at example Dre at example as recipient mail to recipient sending mail via specific mailer by default larl will send email using the mailer configured as the default Mailer in your applications mail configuration file however you may use the mailer method to send a message using a specific mailer configuration queuing mail since sending

  665. email messages can negatively impact the response time of your application many developers choose to cue email messages for background sending larl makes this easy using its built-in unified Q API to cue a mail message use the Q method on the mail facade after specifying the messages recipients so mail to and then you you can just add Q This method will automatically take care of pushing a job onto the queue so the message is sent in the background

  666. you will need to configure your cues before using this feature delayed message queuing if you wish to delay the delivery of a queed email message you may use the later method as its first argument the later method accepts a datetime instance indicating when the message should be sent mail to request user later pushing to spec specific cues send all mailable classes generated

  667. using the make mail command to make use of the cable trait you may call the onq and on connection methods on any mailable class instance allowing you to specify the connection and Q name for the message queuing by default if you have mailable classes that you want to always be queed you may implement the should CU contract on the class now even if you call the send message send method when mailing the mailable will still be

  668. queed since it implements the contract when queued mables 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 queed

  669. mailable is processed if your Q's connections after commit configuration option is set to false you may still indicate that a particular cued 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 mables Constructor rendering maila bles sometimes you may wish to capture the HTML content of a mailable without

  670. sending it to accomplish this you may call the render method of available this method will return the evaluated HTML cont content of the mailable as a string previewing mailable in the browser when designing a mailable template it is convenient to quickly preview the rendered mailable in your browser like a typical blade template for this reason larvo 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

  671. without needing to send it to an actual email address so route Das route get mailable then you return a new app mail invoice p aable localizing maila bues Lara allows you to send mables in a local other than the requests current local and we even remember this local if the mail is cued to accomplish this the male facade offers a local method to set the desired language the application will change into this local when the

  672. mailable template is being evaluated and then revert back to the previous local when evaluation is complete so mail to request user local send new order shipped user preferred local sometimes applications store each other's preferred local by implementing the has local preference contract on one or more of your models you may instruct lville to use this stored local when sending mail once you have implemented the interface larvo will automatically use the preferred local when sending

  673. messages and notifications to the model therefore there is no need to call the local method when using this interface testing testing mailable content Lille provides a variety of methods for inspecting your mailable structure in addition larel provides several convenient methods for testing that your mailable content contains the

  674. content that you expect these methods are assert C in HTML assert don't C in HTML assert C 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 attach data assert has attachment from storage and assert has attachment from Storage dis as you might expect the HTM assertions assert that the HTML version of your mailable contains a given string while the text assertions assert that the plain text

  675. version of your mailable contains a given string testing mailable sending we suggest testing the content of your mailable separately from your tests that assert that a given mailable was sent to a specific user typically the content maila bles is not relevant to the code you are testing and it is sufficient to Simply assert that Lille was instructed to send a given mailable you may use the maale facades fake

  676. method to prevent mail from being sent after calling the mail facades fake method you may then assert that maila were instructed to be sent to users and even inspect the data the maila bles receive if you are queing mables for delivery in the background you should use the assert cued method instead of assert scent you may pass a closure to the assert scent assert not sent assert cued or assert not cued method in order

  677. 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 male 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 male level so return male has attachment

  678. attachment from path has attachment attachment from storage dish 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 cued sometimes you may wish to assert that no mail was sent or queed to accomplish this you may use the assert nothing outgoing and assert not outgoing me methods mail and local development When developing an application that sends email you probably don't want to actually send email to Live email

  679. addresses Lille 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 mail trap mail pit

  680. alternatively you may use a service like Hilo or mail trap 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 and mail traps message viewer if you using larel sale you may preview your messages using mail pit when sale is running you may access the mail pit interface at Local Host

  681. 8025 using a global 2 address finally you may specify a global 2 address by invoking the always 2 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 Lille dispatches to events while sending mail messages the message sending event is dispatched prior to a

  682. 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 cued you may create event listeners for these events within your application custom transports laral includes a variety of male transport orts however you may wish to write your own transports to deliver email via other services that LEL does not support out of the box to get started to find a

  683. class that extends the abstract transport class then implement the do send and two 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

  684. 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 Symphony transports lvo includes support for some existing Symphony maintained mail

  685. transports like mail gun and postmark however you may wish to extend larel with support for additional Symphony maintained transports you can do so by requiring the necessary Symphony mailer via composer and entering and registering the transport with larabel for example you may install and register the Breo formerly send in blue Symphony mailer once the Breo mailer package has been installed you may add an entry for your Breo API credentials to your

  686. applications Services configuration file next you may use use the mail facad extend method to register the transport with larabel 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

  687. notifications

  688. for for [Music]

  689. so we're still in digging deeper notifications introduction in addition to support for sending email Lille provides support for sending notifications across a variety of delivery channels including email SMS via Vonage formerly known as NEX 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

  690. also be stored in a database so that they may 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 single class that is typically stored in the app notifications directory don't worry if

  691. 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 two mail or two 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

  692. using the notify method of the notifiable trait or using the notification facade the notifiable trait is included on your application's appmodel 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 mod models you are not limited to only including it on your user

  693. 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

  694. implements the should Q interface specifying delivering channels every notification class is a via method that determines on which channels a notification will be delivered notifications may be sent on the email database broadcast Vonage and slack channels note if you would like to use other delivery channels such as telegram or Pusher check out the Community Driven lville notification channels website the Via method receives a notifiable instance which will be an instance of the class to which the notification is

  695. being sent you may use notifiable to determine which channels the notification should be delivered on so object notifiable return notifiable prefers SMS could be vage 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

  696. notification be queed by adding the should CU interface and cable 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 shq interface has been added to your notification you may send the notification like normal LEL will detect the should CU interface on the class and automatically cue the delivery of the notification when queuing

  697. notifications a CU 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 insation you may pass an array to delay method to specify the delay amount for specific channels alternatively you may

  698. 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 CU Connection by default cued notifications will be queed using your application's default CU connection if you would like to specify a different connection that should be used by for a particular notification you may call the on connection method from your notifications Constructor or if you

  699. would like to specify a specific Q connection that should be used for each notification Channel supported by the notification you may Define a via connections method on your notification this method should return an array of channel name or Q name Q connection name pairs if you would like to specify a specific q that should be used for each notification Channel supported by the notification you may Define a via Q's method on your

  700. notification the this method should return an array of channel name Q pairs Q notifications May Define middleware just like Q jobs to get started to get Define a middleware method on your notification class the middleware method will receive not notifiable and channel variables which allow you to customize the return to middleware based on the not notification

  701. destination so return match Channel email new rate limited slack new rate limited cued notifications and database transactions when cued notifications are dispatched

  702. within database transactions they may be processed by the que 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 and addition any models or database records created within the transaction may not exist in the database if your notification depends on these models expected unexpected errors

  703. can occur when the job that sends the cued notification is processed if your queed notifications after commit configuration option is set to false you may still indicate that a particular cued 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

  704. regarding cued jobs and database transactions determining if a cued notification should be sent after a queed notification has been dispatched for the Q by background processing it will typically be accepted by a q worker and sent to its intended recipient however if you would like to make the final determination on whether the Q notification should be sent after it is being processed by a q worker you may Define a should send method on the notification class if this method

  705. 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

  706. 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 Vonage to number mail notifications formatting mail messages if a notification supports being sent as an email you should Define a two mail method on the notification class this method will receive a notifiable entity

  707. and should return an 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 L 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

  708. greeting line line if line or action and then line note we are using this invoice ID in our two mail method so url url 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

  709. 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 notifications be sure to set the name configuration

  710. 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

  711. other mail notification formatting options instead of defining the lines of text in the notif 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 passaging 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. paa invoice and then data

  712. this invoice or if your message only has a plain text view you may utilize the text method customizing the sender by default the emails 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 um in this mail notification from so and so customizing the recipient

  713. 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 in email subject will be invoice

  714. 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

  715. when building your message customizing the templates you can modify the HTML plane and plain text template used by mail notifications by publishing the notifi notification package's resources after running this command the mail notification templates will be located in views render notifications directory PHP Artis and vendor publish d-tag equals level- notifications attachments to add

  716. attachments to an email notification use the attach method while building your message the attached method accepts the absolute path to the file as its first argument note the attached method offered by notification mail messages also accepts attachable objects please consult the comprehensive attachable object not documentation to learn more when attaching me files to a

  717. message you may also specify the display name Andor MIM 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 dis using attach from Storage you would rather use the attached method with an absolute path to the file on the storage disk alternatively you could return a mailable from the two mail method when necessary multiple files may be attached

  718. to a message using the attach many method raw data attachments the attached data method may be used to attach a raw string of bytes as an attachment when calling the attached data method you should provide the file name that should be assigned to the attachment at adding tags and metadata some

  719. thirdparty email providers such as mail gun and postmark support message tags and metadata which may be used to group and track emails sent by your application you may add tags and metadata to an email message via the tag and metadata methods if your application is using the mail gun driver you may consult mail guns documentation for more information on tag and metadata likewise the postmark documentation may also be consulted for more information on their support for tags and metadata if your

  720. application is using amazones to send emails you should use the metadata method to attach sces tags to the message customizing the symphony message with Symphony message method of the mail message 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 custom the message before it is

  721. delivered using maila bles 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 2 method maila bles and On Demand notifications if you are sending an on demand notification the notifiable instance given to the two mail method will be an instance of not notifications SL Anonymous not notifiable

  722. which offers a route notification 4 method that may be used to retrieve the email address the on demand notification should be sent to previewing mail notifications when designing a mail notification template it is convenient to quickly preview the rendered mail message in your browser like a typical blade template for this reason Lille allows you to return any mail message generated by a mail notification typic directly from a route closure or

  723. 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 larel is able to render beautiful responsible HTML

  724. templates for the messages while also generating automatically generating a plain text counterpart so generating the message to generate a notification with the corresponding markdown template you may use the-- markdown option of the make notification Artis and command unlike or like all other mail notifications notifications that use markdown templates should defined a two mail method on their not notification class however instead of using the line and action methods to construct the

  725. 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 a available to the template may be passed as the method's second argument writing the message Mark down mail notifications use a combination of Blade components and markdown syntax which allows you to easily construct notifications while leveraging lel's pre-crafted notification components this is really similar to what we read for the mail we have a

  726. 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 notification As You Wish panel component the panel component renders the given block of text and a panel that has slightly different background color than the real than the rest of the notification this allows you to draw attention to a given block of text table component the table

  727. 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 the markdown notification components to your own application for customization to export the components use the vendor Das vendor polish Artisan command to publish

  728. the larel mail asset tag so Artisan vendor publish d-tag equals larel dmail this command will publish the markdown mail components in the resources views vendor mail directory the mail directory will contain an HTML and a text directory each containing their respective representations of every available component you are free to customize these these components however you like customizing the CSS after exporting

  729. the components the resources views vendors mail HTML themes directory will contain a default.css file you may customize the CSS in this file and your Styles will automatically be in line within the HTML representations of your markdown notifications if you would like to build an entirely new theme for lille'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

  730. name of your new theme to customize the theme for an individual notification you may call the theme method while building the notifications mail message the theme me 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 prerequisits the database notification Channel stores the the notification information in a database table this table will contain

  731. 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 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 you're notifiable models are using uid or ulid primary Keys you

  732. should replace the morphs method when with u uid morphs or ulid morphs in the notification table migration formatting database migrations if a notification supports being stored or format database notifications if a notification supports being stored in a database table you should Define a two database or two array method on the notification class this method will receive a notifiable entity and should retain return a plane

  733. 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 meod so to array return invoice ID and amount when the notification is stored in your application 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 notifi notification

  734. class so public function database type and then return invoice Das pain two database versus two array the two array method is also o 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 should Define a two database method instead of a two array method accessing the notifications once notifications are

  735. 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 lel's default app models user Model includes includes a notifications eloquent relationship that Returns the notifications for the entity to fetch notifications you may access this method like any other eloquent Rel relationship by default notifications will be sorted by the created at

  736. 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 [Applause] collection note to access your

  737. 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 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

  738. 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 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 at now you may delete the notifications to remove them from the table

  739. entirely broadcast notifications prerequisites before broadcasting notifications you should configure and be familiar with lel's event broadcasting Services event broadcasting provides a way to react to serers side Lille events from your JavaScript powered front end formatting broadcast notifications the broadcast channel broadcast notifications using lel's event broadcasting Services allowing your JavaScript powered front end to catch notifications in real time if a

  740. notification notification supports broadcasting you can define a two broadcast method on the notification class this method will receive a notifiable entity and should return a broadcast message instance if the two broadcast method does not exist the two 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 front end let's take

  741. a look at an example two broadcast method public function to broadcast return new broadcast method invoice ID is this invoice ID amount this invoice amount broadcast Q configuration all broadcast configurations are cued for broadcasting if you would like to configure the Q connection or Q name that is used to cue the broadcast operation you may use the on the on connection and onq methods of the

  742. 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

  743. 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 nville 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 N N's broadcast notifications are broadcast on you may Define a receives broadcast notifications on method on the

  744. 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 LEL 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

  745. 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 vage control panel formatting SMS notifications if a notification supports being sent as an SMS you should Define a two Vonage method on the red notification class this method will receive a notifiable

  746. entity and should return uh notifications messages vage 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 fr number if you would like to send some notifications from a phone 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

  747. environment variable you may call the from method on a Vonage message instance if you would like to keep TR 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 you can better understand a particular customer's SMS usage the the client reference can be any string up to 40

  748. 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

  749. in you should ensure that your app has the chat right chatri public and chatri customized Scopes these Scopes can be added from the ooth and permissions App Management tab within slack next copy the app's bot user oof token and place it within a slack configuration array in your application services. PHP configuration file this token can be found on the ooth and permissions tab within slack app distribution if your application will be sending notif

  750. 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 slackbot tokens on behalf of your form applications users formatting slack notifications if a notification being sent as a slack message you should

  751. return you should Define a two slack method on your notification class this method will receive a notifiable entity and should return an illuminate notification sl/ message instance you can construct Rich notifications using slack block kit API the following example may be preu in slack block kit Builder so return a new slack message and you have methods available for that slack

  752. interactivity slacks block kit notification system provides powerful features to handle user interaction to utilize these features your slack app should have interactivity enabled and in 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

  753. 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 uh to take based on the payload you should also verify the request was made by slack so confirmation modals if you would like

  754. 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 confirmed 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

  755. 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 two method when building your slack message to configure the channel within the notification a string

  756. specifying the slack channel to send this a notification to EG #s support- Channel a slack route instance which allows you to specify an ooff token and channel name EG slout 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 # support- channel channel in the workspace associated with

  757. the bot user ooth token located in your application 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

  758. obtain a slack ooff token for the user thankfully larel social light includes a slack driver that will allow you to easily authenticate your application's users with slack and obtain a bot token once youve 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 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

  759. to localizing Notifications laravel allows you to send notifications in a local other than the HTTP requests current local and we'll even remember this local if the location is cued to accomplish this the notifications class offers a local method to set the desired language the application will change into this local when the notification is being evaluated and then revert back to the previous local when evaluation is complete localization of multiple

  760. notifiable entries may also be achieved via the notification facade user preferred local sometimes Applications store each user's preferred local by implementing the has local preference contract on your notif notifiable model you may instruct Lille to use the stored local when sending a notification once you have implemented the interface larvo will automatically use the preferred local when sending

  761. notifications and maila bles to the model therefore there is no need to call the local method when using this interface testing you may use the notification facade fake method to prevent notification from being sent typically sending notifications is unrelated to the code your action testing most likely it is sufficient to Simply assert that Lille was instructed to send a given notification after calling the notification fac sod's fake method you may then assert that

  762. 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 the 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

  763. 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

  764. 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 for the not 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

  765. notification itself when a notification is sent the notification sent event is dispatched by 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

  766. about the notification recipient or the notification itself custom channels larabel ships with a handful of notification channels but you may want to write your own drivers to deliver notifications via other channels lvo makes it simple to get started def find a class that contains a send method the method should receive two arguments a notifiable and a notification when the send method you may call within the send method you may call methods on the

  767. 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 two voice method of your notification can return whatever object you choose to represent voice messages for example you

  768. might Define your own voice message class to represent these messages before we dive into package development I'm going to take a quick break to uh get some tea [Music]

  769. oh [Music]

  770. all right so I turned up the microphone a little bit so that I'm not talking as loud and hopefully it's similar um similar volume but I can start to feel 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 Lille packages might be anything from a great

  771. way to work with dates like carbon or a package that allows you to associate files with eloquent models like spoty's Lille media library there are different types of packages some pack packages are Standalone meaning they work with any PHP framework carbon and pest are examples of Standalone packages any of these packages may be used with Lille by requiring them in your composer. Json file on the other hand other packages

  772. are specifically intended for use with Layell these packages may have routes controllers views and configurations specifically intended to enhance a Layell application this guide primarily covers the development of those packages that are LEL specific a note on facades when writing a larel 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

  773. typically have access to all of lille's testing helpers if you would like to be able to write your own package tests as if the package were installed inside Lal application a typical Lal application you may use the orchestral test bench package package Discovery larel applications bootstrap providers. PHP file contains the list of server providers that should be loaded by Lille however instead of requiring users

  774. to manually add your service provider to mly add your service provider to the list you need to find the provider in the extra section of your packages composer Json file so that it is automatically loaded by larabel in addition to service providers you may also list any facades you would like to be registered so that's class voicemail send

  775. oh so that's in the composer. Json file Lille providers and then you would have your provider as well as any aliases debug bar would be Barry vdh debug bar facade once your package has been configured for Discovery larl will automatically register its service providers and facades when is installed creating a

  776. convenient installation experience for your packages 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 applications composer Json files you can use don't discover for specific packages you may disable package Discovery for all packages using the asteris character inside of your applications don't discover a

  777. directive service providers service providers are the connection point between your package and larel a service provider is responsible for binding things like larel service container and informing larel 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

  778. composer package which you should add to your packages 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 packages 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

  779. call the publishes method from the boot method of your service provider now when users of your package EX 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 access like any other configuration file so config cure your. option warning you should not Define closures in your configuration files they cannot be

  780. serialized correctly when users execute the config cache Artis command default package configuration you may also merge your own package configuration file with the application's published copy this will allow you to users to Define only the options that they want to override in the publish copy of the configuration file to merge the configuration file values use the merge config from method within your service provider's

  781. register method the merge config from 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 you're 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 Lo using the load routes from method this method will

  782. 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 publish publishes migrations method to inform lelt that the given directory or file contains m migrations when Lille publishes the migrations it will automatically update the timestamp within their file name to reflect the current date and time language files if

  783. your package contains language files you may use the load translations from method to inform Lille 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 langing courier package translation lines are referenced using the package colon file. line syntax convention so so you may load The Courier packages welcome line from the messages file like so Echo

  784. trans Courier messages. 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 Jon translation files publishing language files if you would like to publish your packages language files through the applications laying vendor directory you may use the service providers publishes method the publishes ex method accepts any an array

  785. of package paths in their desired publish locations for example to publish the language files for the cier package you may do the following now when users of your package execute lel'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 larel you need to tell larl where the views are located you may do this using the service providers load views from method the

  786. loads view from load views from method 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 referenc using the package col calling 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

  787. dashboard when you are using when you use the load views from method Lille actually registers two locations for your views the application resource views is vendor directory and the directory you specify so using The Courier package as an example Lille will first check if a custom version of The View has been placed in the resources views vendor Courier directory by the developer then if the view has not been customized vvo will search the package view directory you specified and you're

  788. called to load views from this makes it easy for package users to customize SL override your packages View views so if you would like to make your views publishable or available for publishing to the applications resources views vendor directory you may use the service providers 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 arst

  789. and command your packages views will be copied to the specified published 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 Lille knows where to find the component you should typically register your components to the boot method of your packages service provider once your component has been registered it may be

  790. rendered using its tag Alias so if the package alert component it would be x- package alert autoloading package components alternatively you may use the component namespace method to autoload component classes by convention for example a Nightshade package might have calendar and Color Picker components that reside within the Nightshade views components name space this will allow the usage of package components by their vendor

  791. namespace using the package-name colon syntax x- Nightshade calender 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 supportive using dot notation if your package contains Anonymous views if your package contains Anonymous components sorry they must be placed with the components directory of your

  792. packages views directory as specified by the load views from method then you may render them by prefixing the component name with the packages view namespace x- cier colon colon alert about Artisan command lill's built-in about Artisan command provides a synopsis of the application environment and configuration packages May push additional information to this command's output via the about command class typically this information may be added

  793. from your package service providers boot method commands to register your package as Artisan commands of Lille 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 these assets to the application's publish public directory use the service

  794. providers 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 you're at packages 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

  795. groups of package assets and resources separately for instance you might want to allow your users to publish your packages configuration files without being forced to publish your packages assets you may do this by tagging them when calling the publishes method from a packages service provider for example let's use tags to Define two published groups for The Courier packages Courier config and Courier migrations in the boot method of the packages service provider so this publishes and then the

  796. directory config paath package. PHP and then Courier DC 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 d-tag equals career- config versus career- migrations all right digging deeper processes

  797. introduction laravel provides an expressive larel provides an expressive minimal API around the symphony process component allowing you to conveniently invoke external processes from your laral application lel's process features are focused on the most common use cases and a wonderful developer experience invoking processes to invoke a process you may use the run and start methods offered by the process facade the run

  798. method will invoke a process and wait for the process to finish executing while the start method is used for asynchronous process execution we'll examine both approaches within the documentation first let's examine how to invoke a basic synchronous process and expect inspect its result of course the illuminate contracts process process result instance returned by the run method so result equals process to and colon run offers a variety of helpful

  799. methods that may be used to inspect the process result throwing exceptions if you have a process result and would like to throw an instance of process failed exception if the ex exit code is greater than zero thus IND IND ating 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 larl

  800. 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 Dory of the current currently executing PHP script input you may provide input via the standard input of the process using the input method timeouts by default

  801. 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

  802. 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 colant forever EMV if you wish to remove an environment variable from the invoked process you

  803. 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

  804. 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 STD out or stdd error and the output string itself

  805. laral also offers the CN out outut and C in error output 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

  806. building the process pipeline 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

  807. 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 me the closure will receive two arguments the type of output STD out or STD air and the output string itself Lara 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

  808. 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

  809. running as you may have noticed you may invoke the weight method so while process running result equals process weit to wait until the process is finished executing and retrieve the process result instance so process timeout start and then process wait process s and signals the ID method may be used to retrieve the operating system assigned process ID of the return of the running process you may use this signal method to send a signal to the running

  810. process a list of predefined signal constants can be found within the PHP documentation a synchronous process output while a 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

  811. real time from asynchronous process 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 string itself current concurrent processes LEL also makes it a breeze to manage a pool of concurrent asynchronous processes allowing you to easily EX execute many tasks simultaneously to get started invoke the pool method which

  812. accepts a closure that receives an instance of illuminate process pool within this closure you may Define the processes that belong to the pool once a process pool is started via the start method you may access the collection of running processes via the running method as you can see you may wait for all the pool process to finish executing and resolve the results via the weight method so pool weight the weight method returns an array an accessible object

  813. that allows you to access the process result instance of each process in the pool by its key so results equal pool weight Echo results key output or for convenience the concurrently method may be used to start an in synchronous process pool and immediately wait on its results this can provide particularly expressive syntax when combined with php's array destructuring capabilities

  814. normal naming pool processes accessing process pool results via numeric key is not very expressive therefore larvo 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 pool pool process IDs and signals since the process pool's running method provides a collection of all invoked processes within the pool you may easily

  815. access the underlying pool process IDs so process ID 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 Lille Services provide functionality to help you easily and expressively write tests and lal's process service is no exception the process facade fake method allows you to instruct Lal to return stubbed dummy

  816. results when processes are invoked faking processes to explore lal's ability to fake processes let's imagine a route that invokes a process so Route G import process run bash import. when testing this route we can instruct Lille 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

  817. that a given process was [Applause] run as discussed invoking the fake method on the process faade will instruct Lille to always return a successful process result with no output however you may easily specify the output and exit code for faked processes using the process facade result method so process fake asteris process

  818. 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 arrays Keys should represent command patterns that you wish to fake and their Associated results the asteris character may be used as a wild card character any process commands that have not been faked will actually be invoked you may use the process facad result method to con construct stub and fake results for

  819. 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 so process fake cat test cat output LS test LS output 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

  820. invocation you may accomplish this via the process facades sequence method faking a synchronous process life cycles thus far we have primarily discussed faking processes which are invok syn invoked synchronously using the run method however if you are attempting to test code that interacts with asynchronous processes invoke via start you may need a more sophisticated approach to describing your fake processes for example let's imagine the

  821. following route which inter interacts with an asynchronous process so Route G import process equals process start bashin 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

  822. use the facade the process facade describe method let's dig into the example above with process fake fake bash import process describe and then we can 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

  823. may be used to specify how many times the running method should return true through available assertions as previously discussed larvo provides several process assertions for your future 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

  824. options if this closure returns true the assertion will pass the process passed the assert ran closure is an instance of illuminate process pending process while the result is an instance of illuminate contracts process process result assert didn't run assert that a given process was not invoked like the assert ran method the assert didn't run method also accepts a closure which will receive an instance of a process and a process result

  825. allowing you to inspect the processes configured options if this closure returns true the assertion will fail assert ran times assert that a given process was invoked a given number of times so assert ran times time 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 expect inspect the process's configured options if this closure returns true and the process was invoked the specified number of times

  826. the assertion will pass preventing stray processes if you would like to ensure that all invoked processes have been faked throughout your individual test or complete test Suite you can call the 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 [Applause]

  827. 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 larel allows you to easily create cued jobs they may be processed in the background by moving

  828. time intensive tasks to a queue your application can be uh your application can be can respond to web requests with blazing speed and provide a better user experience to your customers larel Q's provide a unified queuing API across a variety of different queue backends such as Amazon sqs redus or even a relational database lille's Q configuration options are stored in your application q. PHP

  829. config configuration file in this file you'll find connection configurations for each of the Q drivers that are included with the framework including the database Amazon sqs redus and bean stocked drivers as well as a synchronous driver that will execute jobs immediately for use during local development a null Q driver is also include which can discard CU jobs note lville now offers Horizon a beautiful dashboard and configuration system for

  830. your redest powered cues check out the full Horizon documentation for more information connections versus cues before getting started with LEL cues it is important to understand the distinction between connections and cues in your config q. PHP configuration file there is a connections configuration array this option defines the connections to backend Q services such

  831. as Amazon sqs bean stock or redice however any given Q connection may have multiple cues which may be thought of as different Stacks or piles of Q jobs note that each connection configuration example in the Q configuration file contains a q attribute this is the default cue that jobs will be dispatched to when they are sent to a given Connection in other words if you dispatch a job without exp explicitly defining which queue it should be

  832. dispatched to the job will be placed on the Queue that is defined in the Q attribute of the connection configuration some applications may not need to ever push jobs onto multiple cues instead preferring to have one simple que however pushing jobs to multiple cues can be especially useful for applications that wish to prioritize or segment how jobs are processed since the larel Q worker allows you to specify which cues it should process by priority

  833. for example if you push jobs to a high Q you may run a worker that gives them higher processing priority driver notes and prerequisites database in order to use use the database CU driver you will need a database table to hold the jobs typically this is included in lel's default create jobs table databased migration however if your application does not contain this migration you may

  834. use the make q-table Artisan command to create it reddis in order to use the redus Q driver you should configure a reddis database Connection in your database.php configuration file warning the serializer and compression r options are not supported by the reddis Q driver redis cluster if your redis Q connection uses a redus cluster your q names must contain a key hashtag this is required

  835. in order to ensure all of the reddest keys for a given queue are placed into the same hash slot so redus driver redus connection environment Q retry after block for after commit blocking when using the RIS Q you may use the block 4 configuration option to specify how long the driver should wait for a job to become available before iterating through the worker Loop and reping the reddest database adjusting this value based on your Q load and be more

  836. efficient than continually pulling the reddest database for new jobs for instance you may set the value to five to indicate that the driver should block for 5 seconds while waiting for a new job to become available warning setting block for to zero will cause Q drivers to block indefinitely until a job is available this will also prevent signals such as Sig term from being handled until the next job is been processed other driver prerequisites the following dependencies

  837. are needed for the listed Q drivers these dependency may be installed via the composer package manager so Amazon sqs has a competency of a wssd kphp being stocked has a uh pH stock and redus has predus or PHP rdus PHP extension creating jobs generating a job classes by default all the cable jobs for your application are stored in the app jobs directory if the app jobs

  838. directory doesn't exist it will be created when you run the make job Artisan command the generated class will implement the Q should Q interface indicating to Lille the job should be pushed onto the queue to run a synchronously 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

  839. class in this example we'll pretend we manage a podcast publishing service and need to Pro process the uploaded podcast files before they are published so this class process podcast implements sh Q you can use dispatchable interacts with Q cuble execute the job public function handle in this example note that we were able to pass an eloquent model directly into the queued jobs

  840. Constructors in this case public function construct public podcast dollar side podcast because of the serializes models trait that the job is using eloquent models and their loaded relationships will be gracefully serialized and unserialize when the job is processing if your Q job accepts an eloquent model and its Constructor only the identifier for the model will be serialized onto the que when the job is

  841. actually handled the Q 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 Q driver handle method dependency injection the handle method is invoked when the job is processed by theq note that we are able to typin dependencies on the handle

  842. method of the job the lirell 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 containers bind method method the bind method method accepts the call back which receives this job and the container within the call back you are free to invoke the handle method however you wish typically you should call this method from the boot method of your

  843. application app service provider service provider warning binary data such as raw image contents should be passed through the base 64 encode function before being processed being passed to Q job otherwise the job may not properly serialize to Json when being placed on the Q cued relationships because all loaded uh eloquent model relationships also get

  844. serialized when a job is cued the serialized job string can sometimes become quite large furthermore when a job is deserialized a model relationships are re- retrieved from the database they will be retrieved in their entity entirety any pre 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

  845. given uh relationship you should reconstraction 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 PR motion and would like to indicate that an eloquent model should not have its relations serialized you may use the without relations

  846. 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 larger numbers of models unique jobs sometimes you may want to ensure that only one instance of a specific job is

  847. on the Queue at any point and 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 CU 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 cases you may want to

  848. 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 jav is unique by product ID so any new dispatches of the job within the

  849. same with the same product ID will be ignored until the existing job has completed uh processing in addition if the existing job is not processed within 1 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

  850. 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 larel attempts to acquire a lock with a unique ID key if the lock is

  851. 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 larl will use the default C cash 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 cach driver that should be used so public function unique via encrypted jobs larvo allows you to ensure the privacy and integrity of a job's data the encryption to get started

  852. simply add the should be encrypted interface to the job class once this interface has been added to the class Lille would automatically encrypt your job before pushing it onto a que job middleware job middleware allows you to wrap custom logic around the execution of Q jobs reducing boiler plate in the jobs themselves for example consider the following handle method which leverages which leverages lel's reddest rate

  853. limiting features to allow only one job to process every 5 seconds so public function handle redus 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 hand on method becomes noisy since it is cluttered with redus rate limiting logic in addition this rate limiting logic must be duplicated for any other jobs

  854. that we want to rate limit instead of rate limiting in the handle method we could Define a job middleware that handles rate limiting larel does have 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

  855. so public function handle right is throttle this is in the app jobs middleware as you can see the route like route middleware job middleware receives these job being uh job middleware receives the job being processed and a call back 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 a job Artisan command so you will

  856. 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 rate limited uh function rate limiting although we just just demonstrated how to write your own rate limiting job middleware larvo actually includes a rate limiting middleware that you may utilize to rate limit jobs like route

  857. rate limiters job rate limiters are find using the rate limiter facades 4 method for example You may wish to allow users to back up 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

  858. an hourly rate limit however you may easily Define a rate limit based on minutes using the per per minute method in addition you may pass any value you wish to the buy method of the rate limit however this value is mostly most often used to segment rate limits by customer once you have defined your rate limit you may attach the rate limiter to your job using the Q middleware rate limited middleware each time the job exceeds the rate limit this middleware will release the job back to the queue with an

  859. appropriate delay based on the rate limit duration releasing a rate limited back a rate limited job back into the queue will still in 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 unel 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

  860. method preventing job overlaps Layell includes an illuminate Cube middleware without overlapping middleware that allows you to prevent job overlaps based on an arbitrary key this can be helpful when a q job is modifying a resource that should only be modified by one job at a time for example let's imagine you have a CU 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

  861. middleware from your jobs middleware method any overlapping jobs of the same type will be released back to the queue you may also specify the number 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

  862. method the without overlapping middleware is powered by lal's atomic lock feature sometimes your job May unexpectedly fail or timeout in such a way that the lock is is not released therefore you may explicitly Define a lock expiration time using the expire after method for example this the for example the example below will instruct LEL to release the without overlapping lock three times or 3 minutes after the job has started processing so public

  863. 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 larel to apply the key across job classes using the shared method throttling

  864. exceptions larel includes a q middleware 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 specified time interval lapses this middleware is particularly useful for jobs that interact with thirdparty services that are unstable for example let's imagine a q job that interacts with a third party API that begins throwing exceptions to throttle

  865. exceptions you can return the throttle exceptions middleware 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 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 in the code example Above So

  866. public function middleware throttles exceptions 10 comma 5 if the job throws 10 exceptions within 5 minutes we will wait 5 minutes before attempting the job again when a job throws an exception but the exception threshold is 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 back off method when attaching the

  867. middleware to the job so return new thr exception back off five internally this middleware uses lille'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're multiple if you have multiple jobs interacting with these same thirdparty service and you would like them to share a common throttling

  868. bucket by default the middleware will th throttle every exception you can modify this Behavior by invoking the wind 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' 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

  869. exception will only be reported if the given closure returns true note if you're using redus you may use the throttles exceptions with redus middleware which is fine tuned for redus 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 meth method on the job itself the arguments passed the dispatch method will be given to the jobs Constructor

  870. 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 laral applications the sync driver is the default Q 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 queing jobs for background processing you may specify a different Q driver within your

  871. applications config slq 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 Q 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

  872. dispatched dispatching after the response is sent this Behavior 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 fast CGI this will still allow the user to begin using the application even though a q 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 process within the current HTTP request jobs

  873. dispatch in this fashion do not require a q worker to be run 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 2 send after

  874. response synchronous dispatching if you would like to dispatch a job immediately synchronously you may use the dis dispatch sync method when using this method the job will not be queed and will be ex executed immediately within the current process so public collection store process podcast dispatch sync jobs and database transactions while it is perfectly fine to dispatch jobs within data space transactions you should take special care to ensure that your job

  875. 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 within the transaction may not exist in the database thankfully LEL provides several

  876. methods of working around this problem first you may set the after commit connection option in your Q connection configuration array when the after commit option is true you may dispatch jobs within database transactions however L will wait until the open parent database transactions have been committed before actually dispatching the job of course if no databased transactions are currently open the job will be dispatched immediately if a transaction is rolled back due to Inception that occurs during

  877. the transaction the jobs that were dispatched during that transaction will be discarded specifying column dispatch or specifying commit dispatch behavior in line if you do not set the after commit Q 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

  878. dispatch operation process podcast 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 databased transactions to commit job chaining job chaining allows you to specify list of Cu jobs that should be run in sequence after the primary job has executed successfully if one job in the sequence fails the rest

  879. of the jobs will not be run to execute a q job chain you may use the chain method provided by the bus facade lille's command bus is a lower level component that cued job dispatching is built on top of so bus chain new process podcast new optimize podcast new release podcast dispatch in addition to chain chaining job class instances you may also chain closures so bus chain new process

  880. podcast new optimized podcast and then within closure function podcast update with some chaining there chain connection and Q if you would like to specify the connection and Q that should be used for the chain meth chain jobs you may use the on connection and on Q methods these methods specify the Q connection and Q name that should be used unless the Q job is explicitly assigned a different connection slq

  881. adding jobs to the chain occasionally you may need to prend or aend a job to an existing job chain from within another job in that chain you may accomplish this using the prend 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 call back will receive the throwable instance that caused the job failure customizing the queue uh customizing the queue

  882. connection dispatching to a particular queue by pushing jobs to different cues you may categorize your cued jobs and even prioritize how many workers you assign to various cues keep in mind this ises not push jobs to different Q connections as defined by your Q configuration file but only to specific cues within a single connection to specify the que use the onq method when dispatching the job alternatively you

  883. may specify the job's Q by calling the onq method method within the jobs Constructor so construct this on Q processing dispatching to a particular connection if your application interacts with multiple Q connections you may specify which connection to push a job to using the on connection method so process podcast process podcast dispatch on connection the sqs connection you may chain the on connection and on Q methods

  884. together to specify the connection and the queue for the job alternatively you may specify the jobs Connection by calling the on connection method within the jobs Constructor specifying Max attempts and timeout values if one of your cued 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

  885. attempted one approach to specifying 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 by I the number of times they may be attempted so PHP Artisan Q colon work-- tries equal three if a job exceeds maximum number of attempts it'll be considered a failed job for more information on handling failed jobs consult the failed job documentation

  886. if-- tries equals z 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 tempts is specified on the job it will take precedence over the-- tries value provided on the command line so if you need if you need Dynamic control over particular job's maximum attempts you may Define a tries method

  887. on the job so public function tries with an integer return five 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 until a within a given time frame to define the time at which a job should no longer be attempted add a retry un method to your job class so

  888. 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

  889. class so public Max exceptions equal three max exceptions in this example the job is released for 10 seconds if the application is unable to obtain a Rus lock so the handle function red is 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 own by

  890. the job timeout often you know roughly how long you expect your CU jobs to take for this reason larvo allows you to specify timeout value by default the timeout value is 60 seconds if a job is processed taking 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

  891. be specified using the-- timeout switch on the artisen command line if the job exceeds it 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

  892. 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 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

  893. 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 tempts of attempts is defined by the-- try switch used on the Q work Artisan command alternatively the maximum number of attempts may be defined on the job class itself more information on running the Q worker can be found below manually releasing a job

  894. 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 releases 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 AAP by passing an integer or

  895. date instance the release method occasionally you may need to manually Mark a job as fail 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 for convenience you may pass a string error message which will be converted to an exception for you so this fail something went wrong job batching lille's job batching feature allows you to easily execute a batch of jobs and

  896. 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 Q batches table Artis and commands defining batchable jobs to define a batchable job you should create a cable job as normal however you should add the

  897. illuminate bus 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 illuminate bus

  898. batch 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 then you can have before progress then catch finally dispatch the batches ID which may be access via the batch ID property

  899. may be used to query the Lille command but be bust for information about the batch after it has been dispatched naming batches some tools such as Lille Horizon and Lille telescope May provide more userfriendly 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 bus batch then and then at the prepending

  900. name batch connection and Q if you would like to specify the connection and Q that should be used for the batch jobs you may use the on connection and on Q methods all batch jobs must execute within the same connection and que chains and batches you may Define a set of chain 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 call

  901. back 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 uh 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

  902. 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

  903. completed successfully in this example we will use the load import batch job to to hydrate the batch with additional jobs to accomplish this we may use the ad method on the batch instance that may be accessed via the jobs batch method So within the um load import job batch this batch ad collection colon colon times a th000 warning you may only add jobs to a batch from within a job that belongs to

  904. the same batch inspecting batches the illuminate bus batch instance that's provided to batch completion callbacks is a variety of properties and methods to assist you in interacting with and inspecting a given batch of jobs returning batches from routes an illuminated bus batch instance are Json seral serializable meaning you can return them directly from one of your application routes to retrieve a Json

  905. payload containing information about the batch including its comp 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 fine match method fine batch method cancelling batches sometimes you may need to cancel a given Batch's execution this can be accomplished by calling the cancel method on the illuminate bus batch

  906. 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 their coresponding 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 lville to not process the job if its corresponding batch has been

  907. cancelled batch failures after when a when a batch job fails the catch call back if a sign will be invoked this call back is only invoked for the first job that fails within the batch so allowing failures when a job within a batch fails Lille will automatically Mark the batch as cancelled if you wish you may disable this Behavior so that the job failure does not automatically Mark the batches canceled this may be aom by calling the allow failures method while dispatching

  908. the batch so bus batch allow failures retrying failed fetch jobs for convenience Lille 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 UU ID of the batch whose failed job should be retried pruning batches without pruning the job batches table can accumulate

  909. 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

  910. command Q prun batches D- hours equal 48 daily sometimes your job batches May 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 QPR batches D- hours equal 48 D unfinish equal

  911. 72 likewise your job's 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 Dynamo DB Lille also provides support for storing BR batch meta information in Dynamo DB instead of a relational database however you will need to manually create a Dynamo DB table to store all the batch records typically typically this table should be named job

  912. batches but you should name the table based on the value of the q. batching dot configuration value within your application's Q configuration file Dynamo TB 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. file uh since the

  913. application name is part of the Dynamo Dynamo DB tables key you can use the same table to store job batches for multiple layerable applications in addition you may Define TTL attribute for a table if you would like to take advantage of automatic batch pruning Dynamo DV configuration next install the AWS SDK so that your Lille application can communicate with Amazon Dynamo

  914. DB then set the q. batching driver configuration options value to Dy DB in addition you should Define key secret and regen configuration options within the batching configuration array these options will be used to authenticate with an AWS when using the Dynamo DV driver the q. batching not database configuration option is unnecessary pruning batches in Dynamo DB when utilizing Dynamo DB to store job

  915. batching information the typical pruning commands used to prune batches stored in a relational database will not work instead you may utilize Dynamo dp's native TTL functionality to automatically remove records for old database old batches if you defined your Dynamo DB table with a TTL attribute you may define configuration parameters to instruct lville how to prune batch records the Q bing. TTL attribute configuration value defines the name of

  916. the attribute holding the TTL while the q. bing. TTL configuration value defines the number of seconds after which a batch record can be removed from the Dynamo DB 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 need to be executed outside of the current request cycle when dispatch enclosures to the queue the 's code content is

  917. crypto cryptographically signed so that it cannot be modified and Transit using the catch method you may provide a closure that cannot be executed if the queed closure fails to complete successfully after exhausting all of your cues configur R try attempts running the Q worker the Q work command larel includes an artist and command that will start a q worker and process new jobs they are pushed onto

  918. the queue you may run the worker using using the Q work Artisan command note that once the qor 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 qword command if you would like the process job IDs to be included in the command's output remember Q workers are longlived processes and store the boot booted application state in memory as a result they will not notice changes in your code base after they have been started

  919. so during your deployment process be sure to restart your Q workers in addition remember that any status State created or Modified by your application will not be automatically reset between jobs alternatively you may run the Q listen command when using the Q 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 Q work command running multiple Q workers to

  920. assign multiple workers q and process jobs concurrently you should simply start multiple Q work processes this can either be done locally via multip tabs in your terminal or in production using your process manager configuration settings when using supervisor you may use the num procs configuration value specifying the connection and Q you may also specify which Q connection the worker should utilize the connection name pass to the work command should

  921. correspond to one of the connections defined in your config q. PHP file PHP Artisan work RIS by default the two work command only processes jobs for the default queue on a given connection however you may customize your Q worker even further by only processing particular cues for a given connection for example if all of your emails are processed in an emails Q on your r q

  922. server or Q connection you may issue the following command to start a worker that only processes that cue so Artis Q work rdus d-q equals emails the D- want option may be used to instruct the worker to only process a single job from the queue Q work-- once the ma next job option may be used to instruct the worker to process the given number of jobs and then exit this option may be useful when combining with superv supervisor so that your work workers are automatically restarted after processing

  923. a given number of jobs releasing any memory they may have ACC accumulated processing all cued jobs and then exiting the-- stop when empty option may be used to instruct the worker to process all jobs and then exit gracefully this option can be useful when processing lville cues 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 for to

  924. process jobs for the given number of seconds and then exit this option may be useful when combined with supervisor 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

  925. worker will not process any new jobs maintenance mode and cues while your application is in maintenance mode no Q 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 Q workers to process Q jobs even in maintenance mode is enabled you may use the Das Das Force option resource configurations Damon Q workers do not Reb reboot the framework before

  926. processing each job therefore you should release any heavy resources after each job completes for example if you are doing uh image manipulation with the GD Library you should free the memory with image destroy when you're done processing the image qy priorities sometimes you may wish to priories how your cues are processed for example in your config q. PHP configuration file you may set the default cue for your redus connection to low however occasionally you may want to push wish

  927. to push a job to a high priority cue like so dispatch on Q High to start a worker that verifies that all the high Q jobs are processed before continuing to do any of the jobs on the low Q pass a comma eliminated list of q names to the work command so Artisan q work-- q equals high and then low Q workers and then deployment since Q workers are long lift processes they will not notice changes to your code without being restarted so the simplest way to deploy

  928. an application you can tell Q using Q workers is to restart the workers during your deployment process you may gracefully restart all of their workers by issuing the Q restart command this command will instruct all Q workers to gracefully exit after they finish processing the current job so that no existing jobs are lost since the Q workers will exit when the Q restart command is executed you should be running a process manager such as supervisor to automatically restart the

  929. Q workers note the Q uses the cash to store restart singles so you should verify that a cash driver is properly configured for your application before using in this feature job expirations and timeouts job expiration in your config q. PHP configuration file each Q connection defines a retry after option the option specifies how many seconds the Q connection should wait before retrying a job that is being processed

  930. 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 warning the only Q connection which does not contain a retry after value is Amazon sqs sqs will retry the job based on the default visibility timeout which

  931. is managed within the AWS console worker timeouts the Q work Artisan command exposes a-- timeout option by default the-- timeout value is 60 seconds if a job is processing for longer than the number of seconds specified by the timeout value the worker processing the job will exit with an error typically this worker will be restarted automatically by a process manager configured on your server PHP Artisan Q work timeout 60 the retry after

  932. configuration option and the timeout CLI option are different but work together to ensure the jobs are not lost and the jobs are not are only successfully processed once supervisor configuration in production you need a way to keep your Q work process is running a q work process may stop running for a variety of reasons such as exceeded work work timeout for the ex execution of the Q restart command for this reason you need to configure a process monitor that can

  933. detect when your Q work processes exit and automatically restart them in addition process monitors can allow you to specify how many Q work processes you would like to run concurrently supervisor is a process monitor commonly used in Linux environments and will dis and we will discuss how to configure it in the following documentation installing supervisor supervisor is a process monitor for the Linux op operating system and will automatically restart your Q work

  934. processes if they fail to install supervisor on Ubuntu you may use the following command pseudo app get install supervisor configuring supervisor supervisor configuration files are typically stored in the ETC supervisor C.D directory within this directory you may create any number of configuration files that instructs supervisor how your process should be monitor for example let's create a l-w worker.com file that starts a monitor's q work process

  935. processes in this example the num proc directive will instruct supervisor to run eight q- work or Q work processes and monitor all of them automatically restarting them if they fail you should change the command directive of the configuration to re to reflect your desired Q 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

  936. following commands for more information on supervisor consult the supervisor documentation dealing with failed jobs but sometimes your cued jobs will fail don't worry things don't always go as planned lelt includes a convenient way to specify the maximum number of times a job should be attempted after a synchronous an asynchronous job has exceeded this number of attempts it will be inserted into the failed jobs database table synchronously dispatched jobs that fail are not stored in this

  937. table and their exceptions are immediately handled by the application a migration to create the failed jobs table is typically already present in new larvo applications however if your application does not contain a migration for this table you may use the make Q fail table command to create the migration when running a q worker process you may specify the number of times a job should be attempted using the-- Tri switch on the qor command if

  938. 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 proper using the back off option you may specify how many seconds larel should wait before retrying a job that has encountered an applic 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 Lille should wait before ret tring a job that has

  939. 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 requ you may Define a backoff method on your job class you may easily configure exponential backoffs by returning an array values from the

  940. backoff method in this example the retry delay will be 1 second for the first retry 5 seconds for the second retry 10 seconds for the third retry and 10 seconds for every subsequent retry if there are more attempts remaining so public function back off with an array of 1 5 and 10 cleaning up after 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

  941. 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

  942. instance to retry a failed job that has an ID of U ID issue the command PHP Artisan to 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 CU so PHP Artisan Q retry D- Q equals name to retry all of their failed jobs Ute the Q retry

  943. command and pass all as the ID if you would like to delete a failed job you may use the Q forget command when using Horizon note you should use the Horizon forg command to delete a failed job instead of the Q forg command to delete all of your failed jobs from the failed jobs table you may use the Q 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-

  944. 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 you job 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 larvo will quietly discard the job without raising an exception pruning failed jobs you may prune the records in your applications failed jobs table by

  945. invoking the Q prune fash failed Artisan command by default all of the failed jobs that are more than 24 hours old will be pruned if you provide the-- hours option to the command only the failed job records that 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 Dynamo

  946. DB Lille also provides support for storing your failed jobs in nyv instead of a relational database table however you must man create a Dynamo DB 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 q. fail. configuration value within your application's Q configuration file the fail jobs table should have a string primary partition key named application and a string primary sort key named uid

  947. 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 Dynamo DB table's key you can use the same table to store failed jobs for multiple Lille applications in addition ensure that you install the AWS SDK so that your level application can continue or communicate with Amazon Dynamo DB next set the q. field. driver

  948. configuration options value to Dynamo DB 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 you using the Dynamo DB driver the q. fail. database configuration option is unnecessary disabling failed job storage you may instruct LEL to discard failed jobs without storing them by setting the

  949. q. fail. driver configuration options value to null typically this may be accomplished via the Q failed driver 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 Q 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

  950. larel so boot Q failing and then have the function there clearing jobs from Q's note when using Horizon you should use the Horizon clear command to clear jobs from the Q instead of the Q clear command if you would like to delete all jobs from the default Q of the default connection you may do so using the Q clear Artisan command you may also provide the connection argument and Q

  951. option to delete jobs from a specific connection and Q monitoring your cues if your queue receives a sudden influx of jobs they could become overwhelmed leading to a long wait time for jobs to complete if you wish Lille can alert you when your Q job count exceeds a specified threshold to get started you should schedule the Lille or the the Q monitor command to run um every minute this command accepts the names of the

  952. cues you wish to monitor as well as your desired job count threshold PHP Artisan Q Monitor and you can specify the cues scheduling this command alone is not enough to R trigger a notification alerting you of the q's overwhelm status when the command ENC encounters a queue that has a job count exceeding your threshold and Q busy event will be dispatched you may listen for this event within your application's app service provider in order to send a notification

  953. to you or your development team testing when testing Cod the dispatches jobs You may wish to instruct Lille to not actually execute the job itself since the jobs 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 Q facades fate method fake method to prevent Q jobs

  954. from actually being pushed to the Q after calling the Q facade FES fake method you may then assert that the application attempted to push jobs to theq 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

  955. 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 Q fake accept specific job testing job chains to test job chains you need to utilize the bus's fak facades faking capabilities the bus facad assert chain

  956. method may be used to assert that a chain of jobs is dispatched the assert chain method accept accepts an array of chain jobs as its first argument bus the SE chain ship order record shipment update in inventory then you have bus fake as you see in the example above the array of chain jobs may be an array of the jobs Class names however you may also provide an array of actual job instances when doing so larvo will ensure that the job instances are of the

  957. same class and they have the same property values of the chain jobs dispatched by your application you may use the assert dispatched without chain method to assert that a job was pushed without a chain of jobs testing chain modifications if a chain job prends 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

  958. 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 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

  959. 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 a certaint no aert nothing batch to assert that no batches were dispatched testing job batch interaction in addition you may occasionally need to test an individual jobs interaction with its

  960. 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 tupal containing the job instance and the fake batch so um job batch equals new ship order with fake batch testing job que interactions sometimes you may need to test that the que job releases itself back into the queue or you may

  961. need to test the job deleted itself you may test these Q interactions by instantiating the job and invoking the with fake Q interactions method once the jobs cu's interactions have been faked uh you may invoke the handle method on the job after invoking the job the assert uh yeah assert released assert deleted and assert failed methods may be used to make assertions against the job's Q

  962. interactions job events using the before and after methods on the Q facade you may specify callbacks to be executed before or after a q 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 Lille using the looping method of the Q facade you may specify call backs that

  963. execute before the worker attempts to fetch a job from a queue for example you may you might register a to roll back any transactions that were left open by a previously failed job before dive into rate limiting going to take a quick break get some more tea and uh we'll be right back so deep dive rate limiting

  964. [Music]

  965. for [Music]

  966. I

  967. 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

  968. application interacts with database LEL makes interacting with databases extremely simple across variety supported databases using raw SQL a fluent grade Builder and the eloquent orm currently larell provides first- party support for five databases Maran DV MySQL postes SQL light SQL server configuration the configuration for laravel's database Services is located

  969. 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 L supported database cons systems are provided in this file by default larel samples lel's

  970. sample environment configuration is ready to use with larel sale which is a Docker configuration for developing larel 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 SQL a database using the touch command in your

  971. terminal touch database database.sql light after the database has been created you may easily configure your environment variables to point to this database by placing the absolute path to the database in the DB database environment variable so DB connection SQL light DB database path by default forign key constraints are enabled for sqlite connections if you would like to disable them you should set the DB forign Keys

  972. environment variable to false note if you use the larvo installer to create larvo application and select sqlite as your database larvo 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 serve and PDO SQL serve PHP extensions installed as well as any

  973. 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

  974. 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 root password at1 127.0.0.1 Forge these URLs typically follow a standard schema convention for convenience laravel supports these URLs as an alternative to configuring your

  975. database with multiple configuration options if the URL or corresponding dbor URL environment variable configuration option is pre present it will be used to extract the database connection and credential information read and write connection nection sometimes you may wish to use one database connection for select statements and another for insert update and delete statements laral makes this a breeze and the proper connections will always be used whether you are using raw

  976. queries the query Builder or the eloquent omm 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 host 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 in the read and write

  977. 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 right host array will be used as the host for the read connection while 1 192.168.1.3 will be used for the write connection the database credentials prefix character set other options in the main MySQL array so in this case um and the maini SQL array will be shared across both connections when multiple

  978. values exist in the host configuration array a database hosts 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 life cycle so if the sticky option is enabled and a right operation has been performed against the database during the current request cycle any further read operations will

  979. use the right connection this ensures that any data written during the request 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 a desired behavior for your application running SQL queries once you have configured a database connection you may run queries using the DB facade the DB facade provides methods for each type of query

  980. select update insert delete and statement running a select query to run a basic select query you may use the select method on the DB facade the first argument passed to the select method to the SQL quer while the second argument is any parameter uh Bindings that need to be bound to the query typically these are the values of the wear Clause constraints parameter binding provides protection against SQL

  981. 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

  982. so Burger's DB scaler then you can select count case when food equals burger then one n is Burgers from menu selecting multiple result sets if your application calls store procedures that return multiple results sets you may use the return select result sets method to retrieve all the result sets returned by the stored procedure using named bindings instead of using uh question mark to represent your parameter

  983. bindings you may execute a query using named bindings so DB select uh 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 DP facade 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

  984. 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 dat 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 did not return any value for these types of operations you may use the statement method on the DB facade so DB statement drop table users running an unprepared statement sometimes you may want to

  985. execute uh a SQL statement without binding any values you may use the DB facades unprepared method to accomplish this so dbf prepared update user set votes equals 100 where name equals Dre implicit commit commits when using the DB facade statement and unprepared method within transactions you must be careful to avoid statements that cause implicit commits these statements will

  986. cause the database engine to indirectly commit the entire transaction leaving Lille 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

  987. 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 git PDO method on a connection instance listening for query events if you would like to specify a closure that is

  988. invoked for each SQL query executed by your application you may use the DB facades listen method this method can be useful for logging queries or debugging you may register your query listener closure in the boot method of a service provider monitoring cumulative query time a common performance bottleneck of modern web applications is the amount of time they spend quering databases thankfully lville can invoke a closure

  989. or call back of your choice when it spends too much time time querying the database during a single request to get started provide a query time threshold in milliseconds and closure to the Wi quering 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 DP facade to run a set of operations within the database transaction if an exception is thrown within the transaction closure the

  990. transaction will automatically be ruled back and the exception is rethrown 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

  991. thrown manually using transactions if you would like to begin a transaction manually and have complete control over Ro backs and commits you may use the begin transaction method provided by the DP facade you can roll back the transaction via the roll back method lastly you can commit a transaction via the commit method connecting to the database CLI if you would like to connect to your databases CLI you may use the DB Artisan command

  992. 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 DB table Artis 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

  993. be inspected by providing the database connection name to the command via the database options so-- 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-- counts and-- views options respectively on large databases retrieving row counts and view details can be slow in addition

  994. you may use the following schema methods to inspect your database so tables schema uh GI tables views schema get views if you like to inspect a database connection that is 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 DB table Artisan command this command provides a general overview of a database table including

  995. its columns types attributes keys and indexes monitoring your databases using the DB monitor Artisan command you can instruct LEL 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 connection configurations that you wish to monitor as well as the maximum number of open

  996. 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

  997. database query Builder introduction lille'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 laral query system uses PDO parameter binding to protect your application against SQL injection attacks there is no need to clean or stize strings passed to the query Builder as query bindings running

  998. 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 into the qu onto the query and then finally retrieve the results of the query using the git method so users DB table users git the git method returns an illuminate support collection

  999. 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 users's user Echo username larel collections provide an variety of extremely powerful methods for mapping and reducing data for more information on LEL collections check out the collection documentation thankfully

  1000. 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 DB fac sod's first method this method will return a single STD class object so user DB table 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 the Value method this method will return

  1001. the value of the common column directly to retrieve a single row by its ID column value use the find method so DB table 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 retrieve a collection of user titles so DB table users pluck title you may specify the column that the resultant collection should use as

  1002. its keys by providing a second argument to the pluck method so DB table users pluck title and name chunking results if you need to work with thousands of database records 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 retrieve the entire users table in chunks of 100 records at a time so DB table users order by ID

  1003. 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

  1004. the results based on the record's primary key streaming results lazily the lazy method Works similarly to the chunk method in the sense that it executes the query in chunks however instead of passing each chunk into a call back 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 retrieve results while iterating over them it is best to use the Lazy by ID or Lazy by ID description DEC methods instead these

  1005. 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 you aggregate how your aggregate value is calculated so DB table orders where finalized as

  1006. one average price determine if records exist instead of using the count method to determine if any records exist that match your queries constraints you may use the exists and doesn't exist methods select statements specifying to 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 debit table users select name and email as user email the distinct method allows

  1007. you to force the query to return distinct results so DB table users distinct git if you already have a query Builder instance and you wish to add a column to its existing select Clause you may use the add select 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

  1008. DB facade raw methods instead of using the DB raw method you may also use the methods to insert a raw expression into various parts of your query remember larel cannot guarantee that any query using raw Expressions is protected against seal injection vulnerabilities select raw can be used in place of add select DV raw this method accepts an optional array of bindings as its second argument wear raw and or wear raw methods can be used inject to inject a

  1009. raw wear Clause into your query these methods accept an optional array of bindings as their second argument having raw or or 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

  1010. 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 uh 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 pass to the join method is the name of the table you need to join to while the remaining

  1011. arguments specify the column constraints on the join you may even join multiple tables in a single query so dbut table 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 crossjoin Clause you may

  1012. use the crossjoin method to perform a crossjoin clause crossjoin generates a cartisian 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 joint Clause instance which allows

  1013. you to specify constraints on the joint Clause if you would like to use a wear clause on your joins you may use the wear and or wear methods provided by the join Clause instance instead of comparing two columns these methods will compare the column against the value so join contact function joint on user's ID is equal to contacts. 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

  1014. methods receives three arguments the subquery it'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 post so DB table post select user ID or DB ra is Max created at at last post created at and then where is published true Group by user ID and then can join sub for those

  1015. latest posts lateral joins you may use the join lateral and left joint 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 wear 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

  1016. users as well as the users three most recent blog posts each user can produce up to three row rows in the result set one for each of their most recent blog posts the join condition is specified with a wear 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

  1017. you may create an initial query and you 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 com 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 wear Clauses wear Clauses you may use the

  1018. query Builder wear method to add wear Clauses to the query the most basic call to the wear method requires three AR the first argument is the name of the column the second argument is an operator which can be any of the databases supported aru operators and the third AR 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

  1019. 35 so DB table users where votes is equal to 100 where age is greater than 35 get for convenience if you want to verify that a column is equal to a given value you may pass the value as the second argument to the wear method larabel will assume you would like to use the equal operator so users DB table users wear votes comma 100 get as previously mentioned you may use any

  1020. operator that is supported by your database system you may also pass an array of conditions to the wear function each element of the array should be an array containing the the three arguments typically passed to the wear method or wear Clauses when chaining together calls to the query Builder's wear method the wear Clauses will be joined together using the and operator

  1021. however you may use the orware method to uh join a clause to the query using the or operator the orwar method accepts the same arguments as the wear method if you need to group an or condition within parentheses you may pass a closure as the first argument to the orware 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

  1022. 500 the example above will produce the following sequel so select star from users where votes is greater than 100 or than the parentheses where not Clauses the we not and or where not methods may be used to negate a given group of query constraints for example the following query excludes provide es that are on clearance or which have a price that is

  1023. less than 10 so DB table products we 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 meth all records where any columns in a given list are like a given value you may accomplish this as you the where any

  1024. method where any name email phone like example the query above will result in the following SE uh SQL so select star from users where active equals true and name like example or email like example for EXC similarly the we all method may be used to retrieve records where all the given columns match a given constraint so post DB table uh where publish is true where all title content

  1025. is like larl the query above will result in the following SQL so select star from post where published equals true and title like larl and content like larl Json wear Clauses larl also supports querying Json column types on databases that provide support for Json

  1026. column types currently this includes MySQL 8.0 plus post SQL 12.0 plus SQL server and SQL light with the Json one extension squer a Json column use the Arrow operator so users DB table where preferences dining meal solad you may use where Json containers contains to query Json arrays if your application uses the MySQL or post SQL databases you may pass an array of values to the where

  1027. Json contains method you may use where Json length method to query Json arrays by their length additional wear Clauses we between or where between the we between method verifies that a column's value is between two values where not between method verifies that a column's value lies outside of 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

  1028. row so DB table where between columns weight minimum allowed weight and maximum allowed weight the wear not between columns method provides that a column's value lies outside the two values of two columns in the same table Row the wherein method verifies that 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

  1029. wearin method's second argument the example above will produce the following SQL select star so DB table user select ID where is active one and then DB table wherein user ID is the C is the dollar sign active users we null we not null or we null or we not

  1030. null the wear null method verifies that the value of the given column is null the wear not null method verifies that the column's value is not null the wear date method may be used to compare a column's value against a date the wear month method May used to be compare a valuee columns value against a specific month the we month uh we day method Maybe used to compare a column's value against a specific day of the month the

  1031. we year method may be used to compare a column's value against a specific year so we year created at 2016 the wear time method may be used to compare a column's value against a specific time wear column SL orwar column the wear column may be used to verify that two columns are equal you may also pass a comparison operator in the wear column method so greater than or less than

  1032. you may also pass an array of column comparisons to the wear column method these conditions will be joined using the and operator so DB table where column first name is equal to last name uh updated at is greater than created at logical grouping sometimes you may need to group several wear Clauses within parentheses in order to achieve your query's desired logical grouping in fact you should generally always group calls to the orware method in

  1033. parentheses in order to avoid unexpected query Behavior to accomplish this you may pass a closure to the wear method as you can see passing a closure into the wear method instructs the query Builder to begin a contra constraint group The 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 DB table where function query where or where will produce the

  1034. following sequels like star from users where name is John and votes is greater than 100 or title is equal to admin Advanced wear 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 re receive a query Builder instance allowing you to define the query that should be placed inside the exists

  1035. Clause alternatively you can you may provide a query object to the where exist method instead of a closure sometimes you may need to con construct a wear 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 wear method for example the following query will retrieve all users who have a recent membership of a given type so user wear query select from membership wear column

  1036. order by descending limit or you may need to construct a wear Clause that compares a column to the result of a subquery you may accomplish this by passing a column operator enclo to the wear method for example the sub following query will retrieve all income records where the amount is less than average so incomes where amount is less

  1037. than function Builder query query select raw average from incomes as I full text wear Clauses the wear full text or and or wear full text methods may be used to add full text wear Clauses to a query for columns that have full text indexes these methods will be transer for into the appropriate SQL for the underlying database system by larabel for example a match against Clause will be generated for

  1038. applications utilizing my SQL 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 DS DEC descending to sort by multiple columns you may simply invoked order by as many times as necessary the latest

  1039. 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 re reorder method removes

  1040. all of the order by Clauses that have previously been applied to the query you may pass a column and Direction when calling 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 wear method so DB table users Group

  1041. 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 having statements see the having raw method these Skip and take methods to limit the number of results returned from the query or to skip a given number

  1042. of results in the query so DB table users skip 10 take five 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 to con C 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 wear statement if a

  1043. 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 roll function query where Ro ID is role the closure given to the win method will only be invoked if the role field is present on the incoming requests and

  1044. 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

  1045. once by passing an array of record 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

  1046. ignored no for example insert or ignore will bypass my sqls 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 git 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

  1047. 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 associate 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 DBT

  1048. cable flights upsert departure array uh Oakland destination San Diego price in the example above lar attempt to insert two records if a record already exists with the same departure and destination column values lvo 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

  1049. 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 wear 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

  1050. an array of column and value pairs indicating the columns to be updated the update or insert method method we'll 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

  1051. appropriate key in the Json object this op operation is supported on my SQL 5.7 and post SQL postes 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 modify a second argument may

  1052. be provided to specify the amount by which the column should be incremented or decremented so DB table increment votes DB table increment votes by five if needed you may also specify additional columns to update during the increment or decrement operation in

  1053. addition you may increment or decrement oh um in addition you may increment or decrement multiple columns at once using the increment each and decrement each methods delete statements the query Builder delete method 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 using or by adding wear Clauses before calling

  1054. the delete method if you wish to truncate an entire table which will remove all records from the table and reset the AO Auto incrementing ID to zero you may use the truncate method table truncating and postgress when truncating a postgress 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

  1055. 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 selected records from being modified or from

  1056. 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 requests the dump method will still display the debug information but allow the request to continue executing the dump raw SQL and dump and DD raw SQL methods may be invoked on a query to

  1057. dump the query SQL with all parameter bindings properly substituted database pagination introduction in other Frameworks pagination can be very painful we hope lel's approach to pagination will be a breath of fresh air lille's paginator is integrated with a query Builder and eloquent omm and provides convenient easyto use pagination of database records with zero configuration by default the HTML

  1058. generated by the pageor is compatible with the Tailwind CSS framework however bootstrap pagination support is also available Tailwind jit if you are using Tailwinds default LEL or Lille lille's default Tailwind pagination views and the Tailwind jit engine you should ensure your applications tail one. config.js files content key references lel's pagination views so that their

  1059. Tailwind classes are not purged basic usage paginating query Builder results the 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

  1060. request this value is automatically detected by Lille and is also automatically inserted into links generated by the paginator in this example the only only argument passed to the paginate method is the number of items you would like display per page in this case let's specify that we would like to display 15 items per page so public function index view

  1061. return view users DB table users paginate 15 simple pagination the paginate method contains the total number of Records matched by the query before deleting or before retrieving the records from the database this this is done so the P 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 UI then the record count query is unnecessary therefore if you

  1062. only need to display simple next and previous links in your application's UI you may use these simple page inate method to perform a single efficient query paginating eloquent queries you may also page inate eloquent queries in this example we will paginate the app models user model and indicate that we plan to display 15 records per page as you can see a syntax is nearly identical identical to pagein query Builder results so user pagate 15 of course you

  1063. can call the paginate method after setting other constraints on the query such as wear 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 paginator on a single screen that is rendered by your application however if both paginator

  1064. instances use the page query string parameter to store the current page the two pagein nators will conflict to resolve this conflict you may pass the name of the query string parameter you wish to use to store the paginator 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 CLA cursor pagination works by constructing

  1065. wear Clauses that compare the values of the ordered columns contained in the query providing the most efficient database performance available amongst all of lal'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 url's generated by the paginator cursor-based pagination places a cursor string in the query string

  1066. the cursor is an encoded string containing the location the next paginated query should start paginating and the direction that it should page 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 DB table users order by ID cursor pagein 15 once you've retrieved a

  1067. cursor P paginator instance you may display display the optim 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

  1068. page of results for user's table ordered by ID so select star from users order by ID ascending limit 15 offset 15 but with the crush pagination it 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

  1069. columns are indexed this is because the offset Clause scans through all previously matched data for data sets with fre wrs 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 P page

  1070. 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 expression in order by Clauses are supported only if they are Alias and added to the select Clause as well query expressions with parameters are not supported manually creating a paginator sometimes you may wish to create a pagination instance manually passing it an array of items that you already have in memory

  1071. you may do so by creating either an illuminate pagination paginator uh length aware paginator or cursor aware paginator instance depending on your needs the paginator and cursor paginator classes do not need to know the 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 of we paginator accepts almost the same arguments as the paginator however it requires it count

  1072. 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 res requests URL however the paginator with path method allows you to customize the URI used by

  1073. the paginator when generating links for example if you want the paginator to generate links like HTTP example.com admin users question mark page equals n you should pass SL admin users to the with path method appending query string values you may append query string of pagination links using using the appends method for example to append uh sort equals votes

  1074. to each pagination link you should make the following call to appends user a route get users user paginate user appends sort votes you may use the with query string method if you would like to append all the current requests cre string values to the pagination links appending hash fragments if you need to append hash fragment to URLs generated by the

  1075. 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

  1076. these objects provides 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 pages the page links using blade so for each user ased user usern name and then in double quotes double uh curly brackets users links the links method will render the links to the result of the pages in

  1077. the result set each of these links uh will already contain the proper page query string variable remember the HTML generated by the links method is compatible with the ta1 CSS framework adjusting the p p 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

  1078. displayed on each side of the current page within the middle sliding window of links generated by the p paginator the Lille paginator classes implement the Json 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

  1079. 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

  1080. 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 applications vendor pagination directory the T twin. 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

  1081. default pagination view you may invoke the paginator default view and default simple view methods within the boot method of your app service provider class using bootstrap larel includes pagination views built into or built using bootstrap CSS to use these views instead of the default Tailwind views may call the paginator use bootstrap 4 or use bootstrap 5 methods within the boot method of your app service provider

  1082. class paginator and length aware paginator instance methods each paginator instance provides additional pagination information via the following methods uh paginator account paginator current page pageat 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 P previous page URL total URL get page

  1083. name set page name through which accepts the call back cursor paginated inst in 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

  1084. previous cursor previous page URL set cursor name URL which accepts the 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 have 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

  1085. problem that data manabase data base migrations solve the laravel schema facade provides data datase agnostic um support for creating and manipulating tables across all of lel's supported database systems typically migrations will use this facade to create and modify database tables and

  1086. 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 migrations directory each migration file name contains a timestamp that allows LEL to determine the order of the migrations there we 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 larl is able to determine the table name for the

  1087. migration name LL will pre-fill the generated migration file with the specified table otherwise you may simply specify the table in the migration file manually if you would like to specify a custom path for the generation migration you may use the Das Das path option when executing the make migration command the given path should be relative to your application base

  1088. 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 bloed 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 larvo will write a schema file to your applications database schema directory migration structure migration

  1089. 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 larel schema Builder to expressively create and modify tables to learn about all the methods available in the schema Builder check out its documentation for example the following migration creates a flights table so

  1090. table ID table string table string Airline and table timestamps and the up function setting the migration connection if your migration will be interacting with the database connection other than 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 artisent

  1091. command if you would like to see which migrations have run thus far you may use the migrate status artison command if you would like to see the sequel statements that will be executed by the migrations without actually running them you may provide the-- 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 to two service two servers attempting to migrate the database at the same time to avoid this you may use

  1092. the isolated option when invoking the migrate command when the isolated option is provided Lille will require an atomic lock using your uh acquire an atomic lock using your application's cash 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

  1093. and 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 to for confirmation before the commands are executed to force the commands to run without a prompt use the-- Force flag to roll back the latest migration operation you may use the roll back 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

  1094. providing the step option to the roll back command for example the following command will roll back the last five migrations D- step equals 5 you may roll back a specific batch of migrations by providing the batch option to the roll back command where the batch option corresponds to a batch value within your applications migrations database table for example the following command will roll back all migrations in batch three roll back d d back equals 3 if you would like to see the sequel statements it

  1095. will be executed by the migrations without actually running them you may provide the-- pretend flag to the migrate roll back 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 remigrate a limited number of migrations by providing the step option to the refresh command for example the following command will roll

  1096. back and remigrate the last five migrations so PHP Artis migrate refresh equals uh or D- step equals 5 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

  1097. 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 versus the D 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 custom

  1098. 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

  1099. be used to specify the table storage engine when using MySQL so table engine NB the car set and collation uh properties may be used to specify the character set and collation for the created table when using my SQL the temporary method may be used to indicate that the table should be temporary temporary tables are only visible to the current connections database session and are dropped automatically when the connection is closed if you would like to add a

  1100. comment to a database table you may invoke the comment method on the table instance table comments are currently only supported by MySQL and postgress the table method on the schema facade may be used to update existing tables like the create method the table method accepts two arguments ments 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

  1101. the rename method to drop an existing table you may use the drop or drop if exists methods renaming tables with foreign Keys 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 layer assign a convention based name otherwise the forign key constraint name will refer to the old table name

  1102. creating columns the table method on the schema facade may be used to update existing column tables like the create method the table method accepts two arguments the name of the table and a closure that receives a blueprint instance so you may use 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 uh schema Builder

  1103. 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 auto auto incrementing onside big int primary key equivalent column big integer creates a big int equivalent

  1104. column B inary creates a blob equivalent column utilizing MySQL Mari DB or SQL Server you may pass length and fixed arguments to create varbinary or binary equivalent column Boolean 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

  1105. 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

  1106. creates a float equivalent column with the given Precision the 49 method creates an unsign big int equivalent column the 4 and id4 Method has a column ID equivalent column for a given model class the column type will be unside big int Char of 36 or Char 26 depending on the model key type foreign uid method creates a UL ID equivalent column the foreign U uuid method creates a uuid

  1107. equivalent column the geography method creates a geography equivalent column with the given spatial types and srid spatial reference system identified the geometry method creates a geometry equivalent column with the given spatial type and Sr ID 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

  1108. column the increments method creates an auto incrementing on 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 postc an inet column will be created the Json method creates a Json equivalent column the Json B method creates a Json B equivalent column long text creates a long text

  1109. equivalent column utilizing MySQL or my rdb you may apply 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 medium increments method creates an auto incrementing unsigned medium int equivalent column as a primary key the medium integer method

  1110. creates a medium int equivalent column the medium text method creates a medium text equivalent column when utilizing my SQL idb 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 vchart equivalent column the column type for for the column ID will be unsigned big int charart 36 or charart 26 depending on the model key

  1111. car 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 would be created so table morphs taggable the nullable time stamps method is an alias of the time stamps method the method is similar to the Morse method in nullable nors nullable morph however the columns that are created will be nullable nullable U uid morphs however the

  1112. columns are created will be nullable nullable uuid morphs is like uid but they will be nullable remember token method creates a nullable varar 100 equivalent column that is intended to store the current remember me authentication token Auto incrementing unsigned small in equivalent column as a primary key

  1113. small integer meth creates a small int equivalent column the soft [Applause] delete a 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 soft delete functionality soft delete methods adds the nullable deleted at timestamp equivalent column with an optional fractional seconds Precision this column

  1114. is intended to store the deleted at Tim stamp needed for eloquent soft delete functionality the string method creates a varar equivalent column of the given length the test text method creates a text equivalent column when using MySQL or myb you may apply a binary character set to the column in order to create a blob equivalent column the time TZ method creates a time with time Stone equivalent column with an optional fractional seconds Precision the time method creates a time equivalent column

  1115. with an optional seconds Precision the time stamp TZ method creates a time stamp with time zone equivalent column with an optional fractional seconds Precision the time stamp method creates a time stamp equivalent column with an optional fractional seconds Precision the time stamp TZ method creates treated at created at an updated at timestamp with time zone equivalent columns with an optional fractional seconds prision the time stamps method creates created at and updated at timestamp equivalent columns with an optional fractional seconds Precision the tiny increments

  1116. 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 myor orb 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 an equivalent column unsigned integer creates an unsigned equivalent column

  1117. the unsigned big the unsigned medium integer creates an unsigned medium in uh equivalent column the unsigned small in creates a unsigned small in equalent column the unsign tiny integer method creates an unsign tiny in equivalent column the ulid morphs method is a convenience method that adds a column ID car 26 equivalent column and a column type of RAR equivalent column the UL uu

  1118. ID mors method is a convenience method with a column ID Char 36 equivalent column and a column type varchar equivalent column the UL ID method creates a UL ID equivalent column the uid 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

  1119. column nullable you may use the nullable method the following table contains all 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

  1120. default Expressions the default modifier accepts a value or an illuminate database query expression instance using an expression instance will prevent Lille from wrapping the value in quotes and allow you to use database specific functions one situation where this particular useful is where you need to assign default values to Json columns column order when using the MySQL dat 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

  1121. 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

  1122. 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 mean drop multiple columns from the table by passing an array of column

  1123. names to the drop column method larel provides several convenient methods related to dropping column types of columns each of these methods is described in the table below so table drop morphs drop remember token drop soft deletes drop soft deletes TZ drop time stamps drop time stamps TZ indexes creating indexes the LEL schema Builder supports several types of indexes the following example creates a new email column and spe specifies that

  1124. 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 uh when creating an

  1125. index L will automatically gener an index name based on the column uh 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 larel schema Builder blueprint class provides methods for creating each type of index supported by larabel 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

  1126. of the table and columns used for the index as well as the index type each of the available index method is described in the table below so 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

  1127. 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 Lille automatically assigns an index name uh based on the table name the name of the index column and the index type here are some examples table drop primary table drop unique table drop index table drop full text table drop spatial index if you pass an array of columns into a method that drops indexes

  1128. the conventional index name will be generated based on the table name columns and index type foreign key constraints Lille also provides support for creating foreign key constraints which are used to force referential referential integrity at the database label level for example let's define a user ID column on the post table that references the ID column on a user table so table inside in big integer user ID table forign user ID references ID on users since this syntax is rather ver

  1129. Bose larel provides additional terer 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 t forign ID user ID constrain the forign ID method creates an unsigned big integer equivalent column while the constraint method will use conventions uh to determine the table

  1130. 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 onupdate properties of the constraint and alter alternative expressive syntax is also provided for these actions so table Cascade on update restrict on update on

  1131. no action on update Cascade on delete restrict on delete or null on delete any additional column modifiers must be called before the constrained 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 uh as indexes in other words the foreign key constraint name is based on the name of the table and the columns

  1132. in the constraint followed by aore forign 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 lille's constraint naming conventions you may enable or disable forign key constraints within your migrations by using the following methods uh so that's schema enable foreign key constraints or disable

  1133. forign key constraints events for convenience each migration operation will dispatch an event all the following events extend the base migration event class uh events migration started events migrations ended events migrations started events migrations ended events

  1134. schema dumped and events schema loaded database seating larel includes the ability to seed your database with data using seed classes all seed classes are stored in the database seedar directory by default a database Cedar 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 Cedars to generate a cedar execute the make Cedar Artisan

  1135. command all Cedars generated by the framework will be plac in the database Cedar directory a cedar class only contains one method by default run this method is called when the DBC 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 Cedar class and add a database insert statement to the run

  1136. method so public function run DB table 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 conveniently gener generate large amounts of database records first review the model Factory documentation to learn how to define your factories

  1137. for example let's create 50 users that each H has one related post so user Factory count of 50 has post one create calling additional Cedars within the database Cedar class you may use the call call method to execute additional seed classes using the call method allows you to break up your database seating into multiple files so that no single seed or class becomes too large the call method accepts an array of Cedar classes that should be executed so

  1138. this call user Cedar Post seeder common seeder muting model events when 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 without model events trait ensures no model events are dispatched even if additional seed classes are executed via the call method running seedar you may execute the DB seed Artisan command to seed your database by default the DBC command runs

  1139. the database Cedar class which may turn in uh May in turn invoke other seed classes however you may use the-- class option to specify a specific seedar class to run individually you may also seed your database using the migrate fresh command in combination with the-- seed option which will drop all tables and rerun all of your migrations this command is useful for completely rebuilding your database the rece the

  1140. cedar option may be used to specify a specific Cedar to run forcing Cedar to run in production some seating operations may cause you to alter or lose data in order to protect you from running seating commands against your production database you'll be prompted for confirmation before the seeders are executed in the production environment to for Force the seeders to run without a prompt use the force

  1141. 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 list sets and sorted sets before using Redd with larvo we encourage you to install and use the PHP reddis PHP extension via Pele the extension is more complex to install compared to userland PHP packages but may yield better performance for applications that make heavy use of reddis if you are using Lille sale the extension is already

  1142. installed in your application's Docker container if you are unable to install the PHP redus extension uh you may install the predus predus package via composer predus is redus client written entirely in PHP and does not require any additional extensions configuration you may configure your application's Rd settings via the config database PHP configuration file within this file you will see a reddis array containing the

  1143. redus servers utilized by your application uh so reddis client options array default array and cach array each reddis 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 reddest connection so reddis client options default cache configuring the data connection scheme by default reddis clients will use the

  1144. top scheme or TCP scheme when connecting to your redus servers however you may use tls/ssl encryption by specifying a scheme configuration in your reddest servers configuration array clusters if your application is utilizing a cluster of Redd servers you should Define these clusters within a cluster key of your redus configuration this configuration key does not exist by default so you will need to create it within your application's config database.php

  1145. configuration file by default Lille will use native redus clustering since the options. cluster configuration F value is set to reddis redus clust in is a great default option as it gracefully handles failover Lille 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

  1146. instead of native reddish clustering you may remove the options. cluster configuration value within your application config database.php configuration file predice if you would like your application to interact with reddis via the predus package you should ensure the reddis client environment variables value is predus in addition to the default configuration options predus supports additional connection parameters that

  1147. may be defined for each of your reddis servers to utilize these additional configuration options add them to your reddest server configuration in your application database.php configuration file by default larel will use the PHP redus extension to communicate with redus the client that Lille will use to communicate with reddis is dictated by the value of the rus. client configuration option which typically reflects the value of the redis client environment variable in addition to the

  1148. default configuration options PHP reddis supports the following additional connection parameters name persistent persistent ID prefix R timeout retry interval timeout and context you may add any of these options to your R server configuration in the config database.php configuration file PHP redus serialization and compression the PHP redus extension may also be configured to use a variety of

  1149. serializers and compression algorithms these algorithms can be configured via the options array of your redus configuration currently supported serializers include redis serializer reddis sterilizer PHP sterilizer Json sterilizer uh IG binary and serializer MSG pack supported compression algorithms include redus compression compression lzf compression L zstd and compression

  1150. lz4 interacting with redus you may interact with redus by calling various methods on the redis facade the redus facade supports Dynamic methods meaning you may call any redis command on the facade and the command will be passed directly to redis in this example we will call the reddis git command by calling the git method on the redus facade so uh return View user profile

  1151. user redus git user colon profile as mentioned above you may call any of Reedus's commands on the redis facade Lille uses magic methods to pass the commands to the redis server if a redus command expects arguments you should pass those to the faad corresponding method uh use illuminate support facades reddis reddis set named Taylor alternatively you may pass commands to

  1152. the server using the reddis 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 connect configuration file allows you to Define multiple reddis Connections in servers you may obtain a connection to a specific reddis connection using the reddis facade connection method to obtain an instance of the default reddis connection you may call the connection method without any additional arguments

  1153. transactions the reddis facad transaction method provides a convenient wrapper around Red's native multi and exec commands the transaction method accepts a closure as its only argument the closure will receive a redus connection instance and May issue any commands it would like to uh it would like to this instance all of the reddis commands issued within the closure will be executed in a single Atomic

  1154. transaction uh Luis scripts the eval method provides another method of executing multiple reddis commands in a single Atomic operation however the aval method has been benefit of being able to interact with and inspect reddis key values during that operation reddis 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 leis

  1155. 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 reddis eval Lua local

  1156. counter reddis call if counter is greater than five then rd. call increment keys to end pipelining commands sometimes you may need to execute dozens of reddest commands instead of making a network trip to your Reedus server for each command you may use the pipeline method the pipeline method accepts one argument a closure that receives a reddis instance you may issue all of your commands to this reddis instance and they will all be sent to the Redd server at the same time

  1157. to reduce Network trips to the server the commands will still be executed in the order they were issued Pub sub laravel provides a convenient interface to the reddis publish And subscribe commands these reddish commands allow you to listen for messages on a given Channel you may public messages to the channel from another application or even using another programming language allowing easy communication between applications

  1158. and processes first let's set up a channel listener using the Subscribe method we'll place this method call with 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 wildar subscriptions using the P subscribe method you may subscribe to a wild card Channel which may be useful for catch in all messages on all channels the channel name will be passed

  1159. as the second argument to the provided [Applause] closure all right another bathroom break e

just you here