New Features
 summary
Larave 5.5 is an LTS version, which will provide 2-year bug repair and 3-year security repair support. Larave 5.5 continues to optimize on the basis of Larave 5.4: automatic package detection function API resources/conversion, automatic registration of console commands, queue task chain, queue task rate limit, time-based task attempts, renderable mail, renderable and reported exceptions, more consistent exception handling, database test optimization, simpler validation rule customization, React front-end presets Route::view
and Route::redirect
Methods, Memcached and Redis cache driven "locks", on-demand notifications, Dusk painless support for Chrome, convenient Blade shortcut keys, proxy support for optimizing trust, etc. In addition, Laravel 5.5 also happens to meet Laravel Horizon This is a Laravel queue background management and configuration system based on Redis. Note: This document only refers to some important updates and optimizations. For more details, please refer to GitHub Details of the modification log on the.
Laravel Horizon
Horizon provides a beautiful background and code driven configuration for Laravel queue based on Redis. Horizon allows you to easily monitor key indicators of the queue system, such as task throughput, runtime, and failed tasks. All task process configurations are stored in a simple independent configuration file, thus allowing your configuration to be saved in the source control system for the collaboration of the whole team. For more information about Horizon, please refer to Full Horizon documentation 。 Package auto discovery
In previous versions of Larravel, installing an expansion package usually requires multiple steps, such as registering a service provider to app
And register the corresponding facade. However, starting from Larave 5.5, Larave can automatically discover and register service providers and facades for you. For example, you can install the famous barryvdh/laravel-debugbar
The expansion pack is used in the Larravel application to experience this new function. After installation through Composer, the debugging bar can take effect without any additional configuration: composer require barryvdh/laravel-debugbar
Extension package developers only need to add their own service providers and appearances to the composer.json
The file can: "extra": { "laravel": { "providers": [ "Laravel\\Tinker\\TinkerServiceProvider" ] } },
To learn more about how to use the automatic discovery function of service providers and facades when updating packages, refer to Expansion Pack Development Document 。 API Resources
When building an API, you may need to have a conversion layer between the Eloquent model and the JSON response that is actually returned to the application user. Larvel's resource class allows you to simply and elegantly convert models and model collections into JSON. A resource class represents a model that needs to be converted into JSON structure. For example, the following is a simple User
Resource class: <? php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\Resource; class User extends Resource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } }
Of course, this is only the most basic example of API resources. Larravel also provides a variety of methods to help you build resources and resource collections. For more information, please refer to the Full Documentation 。 Automatic registration of console commands
When creating a new console command, it is no longer necessary to manually add it to the $commands
In the attribute list, replace it in the kernel's commands
A new load
Method, which will retrieve all console commands under the given directory and automatically register them: /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); // ... }
New front-end presets
Larravel 5.5 still has the basic Vue scaffold built in. In addition, we have provided some front-end preset components. In a new Larravel application, you can use preset
Command to switch Vue scaffold to React scaffold: php artisan preset react
Alternatively, you can use none
The preset command removes the scaffolding of JavaScript and CSS frameworks. This preset command will leave the application with only some native Sass files and some simple JavaScript functions: php artisan preset none
Warning: These commands can only be used in the newly installed Laravel. Do not execute these commands in the existing application code, especially in the online application code, or you will be responsible for the consequences!
Queue task chain
The task chain allows you to specify the queue task list that needs to be run in a sequence. If a task in this sequence fails to run, the remaining tasks will not run again. To execute a queue task chain, you can use it in any distribution task withChain
method: ProvisionServer::withChain([ new InstallNginx, new InstallPhp ])->dispatch();
Queue task frequency limit
If your application queue uses Redis, you can now control the execution of queue tasks through time or concurrency. This function is useful when a queue task calls an API that also sets frequency limits. For example, you can set a specified type of task to run 10 times per minute: Redis::throttle( 'key' )->allow( ten )->every( sixty )->then( function () { }, function () {
return $this ->release( ten ); });
Note: In the above example, key
It can be any string used to uniquely identify the task type you want to limit the frequency. For example, you can build a key based on the Eloquent model ID of the task class name and its operation.
As an alternative, you can also specify the maximum number of task processes to simultaneously process a given task (multi process processing queue tasks), which is useful when queue tasks are designed to edit one resource one task at a time. For example, we can limit a given type of task to be processed by only one work process at the same time: Redis::funnel( 'key' )->limit( one )->then( function () { }, function () {
return $this ->release( ten ); });
Time based task attempts
As an alternative to defining the number of attempts before a task finally fails, you can now set the timeout for a task, so that the task can be tried many times within a given time range. To define such a time, you can add a retryUntil
Method to task class:
public function retryUntil ()
{ return now()->addSeconds( five ); }
Note: You can also define a retryUntil
method.
Validation Rule Object
The validation rule object provides a new and concise way to add custom validation rules to your application. In previous versions of Larravel, we used Validator::extend
Method adds custom validation rules through closures, but this is cumbersome. In Laravel 5.5, through the Artisan command make:rule
Will be app/Rules
Generate a new validation rule under the directory: php artisan make: rule ValidName
A rule object only contains two methods: passes
and message
。 passes
Method receives the property value and name, and then returns based on whether the property value is valid true
or false
。 message
The method will return the corresponding validation error message when the validation fails: <? php
namespace App \ Rules ; use Illuminate \ Contracts \ Validation \ Rule ; class ValidName implements Rule
{
public function passes ( $attribute , $value )
{ return strlen( $value ) === six ; }
public function message ()
{ return 'The name must be six characters long.' ; } }
After the rule is defined, it can be used by passing the rule object instance: use App \ Rules \ ValidName ; $request ->validate([ 'name' => [ 'required' , new ValidName], ]);
Integrated Trusted Proxy
When the application you are running is located after the load balancing that will terminate the TLS/SSL certificate, you may notice that the application sometimes does not generate HTTPS links. Usually this is because your application is forwarded traffic by the load balancer on port 80, and then you do not know that you should generate a security link. To solve this problem, many Larravel users choose to install Trusted Proxy Because this is such a common use case, we have directly integrated this expansion package in Larravel 5.5. A new one has been added in Larravel 5.5 App\Http\Middleware\TrustProxies
Middleware, which allows you to quickly customize agents that need to be trusted by applications: <? php
namespace App \ Http \ Middleware ; use Illuminate \ Http \ Request ; use Fideloper \ Proxy \ TrustProxies as Middleware ; class TrustProxies extends Middleware
{
protected $proxies ;
protected $headers = [ Request::HEADER_FORWARDED => 'FORWARDED' , Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR' , Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST' , Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT' , Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO' , ]; }
On demand notification
Sometimes you may need to send notifications to non user entities in the application and use new Notification::route
Method, you can specify a specially specified notification route before sending a notification: Notification ::route ( 'mail' , ' taylor@laravel.com ' ) -> route ( 'nexmo' , '5555555555' ) -> send( new InvoicePaid($invoice));
Renderable mail objects
Mail objects can now be returned directly from the route, allowing you to quickly preview the mail design in the browser: Route::get( '/mailable' , function () { $invoice = App\Invoice::find( one ); return new App\Mail\InvoicePaid( $invoice ); });
Renderable&Reportable Exception
In previous versions of Larravel, if you want to render a custom response for a given exception, you may have to resort to type checking in the exception handler. For example, you may find that render
This code has been written in the method: /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @ return \Illuminate\Http\Response */ public function render( $request , Exception $exception ) { if ( $exception instanceof SpecialException) { return response(...); } return parent::render( $request , $exception ); }
In Larravel 5.5, you can now directly define a render
In this way, you can directly set custom response rendering logic in this method to avoid piling up conditional judgment logic in the exception handler. If you also want to customize the reporting logic for exceptions, you can define a report
method: <? php
namespace App \ Exceptions ; use Exception ; class SpecialException extends Exception
{
public function report ()
{ }
public function render ( $request )
{ return response(...); } }
Request validation
Illuminate\Http\Request
Object now provides a validate
Method, which allows you to quickly validate input requests from routing closures or controllers: use Illuminate \ Http \ Request ; Route::get( '/comment' , function (Request $request ) { $request ->validate([ 'title' => 'required|string' , 'body' => 'required|string' , ]); });
Consistent exception handling
The processing of validation exceptions is now consistent throughout the framework. In previous versions, there were multiple locations in the framework that required customized code to change the default format of JSON validation error responses. In Laravel 5.5, the default format of JSON validation response follows the following conventions: { " message ": "The given data was invalid." , " errors ": { " field-1 ": [ "Error 1" , "Error 2" ], " field-2 ": [ "Error 1" , "Error 2" ], } }
All JSON validation error formats can be verified in the App\Exceptions\Handler
Class. For example, the following custom code will use the Laravel 5.4 convention to format the JSON validation response: use Illuminate\Validation\ValidationException; /** * Convert a validation exception into a JSON response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Validation\ValidationException $exception * @ return \Illuminate\Http\JsonResponse */ protected function invalidJson( $request , ValidationException $exception ) { return response()->json( $exception- >errors(), $exception- >status); }
Buffer lock
Redis and Memcached cache drivers now support the acquisition and release of atomic "locks". This function provides a simple way to acquire any lock without worrying about any competition conditions. For example, before executing a task, you may want to obtain a lock, so that no other process can try the task already being executed: if ( Cache ::lock ( 'lock-name' , sixty ) -> get()) {
Cache ::lock ( 'lock-name' ) -> release(); } else { }
Alternatively, you can pass a closure to get
Method, this closure will be executed only when the lock can be obtained, and the lock will be automatically released after the closure is executed: Cache :: lock ( 'lock-name' , sixty )-> get ( function () { // Lock obtained for sixty seconds... });
In addition, you will be in a "blocked" state until the lock is released: if ( Cache :: lock ( 'lock-name' , sixty )-> block ( ten )) { // Wait for a maximum of ten seconds for the lock to become available... }
Blade optimization
When you need to define simple custom condition statements, the complexity of writing custom instructions is often greater than the necessity. For this reason, Blade now provides a Blade::if
Method helps you quickly define custom conditional directives using closures. For example, let's define a custom condition to check the current application environment AppServiceProvider
Of boot
Method: use Illuminate \ Support \ Facades \ Blade ;
public function boot ()
{ Blade::if( 'env' , function ( $environment ) { return app()->environment( $environment ); }); }
After defining user-defined conditions, you can use them in the template: @env ( 'local' )
@else
@endenv
In addition to simplifying the instructions for customizing Blade conditions, we also added several shortcut instructions to quickly check the current user's authentication status (whether to log in or not): @auth
@endauth
@guest
@endguest
New routing method
If you need to define a route that redirects to another URI, you can use Route::redirect
To achieve. This method is very convenient. With it, you no longer need to define a complete route or controller to perform a simple redirection: Route :: redirect ( '/here' , '/there' , three hundred and one );
If your route only needs to return one view, you can use Route::view
Methods, and redirect
The method is similar. With this method, you no longer need to define a complete route or controller for a simple view. view
Method receives a URI as its first parameter and a view name as its second parameter. In addition, you can provide an array data to pass to the view as an optional third parameter: Route :: view ( '/welcome' , 'welcome' ); Route :: view ( '/welcome' , 'welcome' , [ 'name' => 'Taylor' ]);
"Sticky" database connection
sticky
option When configuring read/write database connections, a new configuration item is supported sticky
: 'mysql' => [ 'read' => [ 'host' => '192.168.1.1' , ], 'write' => [ 'host' => '196.168.1.2' ], 'sticky' => true , 'driver' => 'mysql' , 'database' => 'database' , 'username' => 'root' , 'password' => '' , 'charset' => 'utf8mb4' , 'collation' => 'utf8mb4_unicode_ci' , 'prefix' => '' , ],
sticky
Option is an optional value, which can be used to allow the record just written to the database to be read immediately during the current request life cycle. If sticky
When the option is enabled and a "write" operation is performed on the database in the current request lifecycle, any subsequent "read" operation will use a "write" connection, which can ensure that any data written in the current request lifecycle can be read from the database correctly and immediately in the same request lifecycle. This can be seen as a solution to the master-slave delay of distributed databases. Whether to enable this function is ultimately up to you.