Laravel using Formrequest for form verification method and problem summary, laravelformrequest
In ' Laravel ', each request is encapsulated as a ' request ' object, and the ' Form request ' object is a custom ' request ' class that contains additional validation logic (and access control). This paper analyzes the processing flow of formrequest anomaly and puts forward the idea of custom processing formrequest verification failure.
All examples based on Laravel 5.1.39 (LTS)
It's a nice day, let's talk about forms validation.
Do form validation in controller
Some students write the form validation logic in the controller, such as the validation of the user's submission of comments:
<?php//validator;class commentcontroller{public function poststorecomment (Request $request) { $validator = Validator::make ($request->all (), [ ' comment ' = ' required ',//Just an instance, write a simple rule, If your website reads like this, please post the URL in the comments ]); if ($validator->fails ()) { return redirect () ->back () ->witherrors ($validator) Withinput (); } }
In this case, form validation and business logic are squeezed together, and our controller has too much code, and duplicate validation rules are basically copy-and-paste.
We can use form request to encapsulate the form validation code, thus streamlining the code logic in the controller and keeping it focused on the business. A separate form validation logic can even be reused for other requests, such as modifying comments.
What is form Request
In Laravel, each request is encapsulated as a request object, and the Form request object is a custom request class that contains additional validation logic (and access control).
How to do form validation using form request
Laravel provides the artisan command to generate form request:
$ php artisan make:request StoreCommentRequest
So we generated the app/http/requests/storecommentrequest.php, let's analyze the content:
<?phpnamespace App\http\requests;use app\http\requests\request; As you can see, this base class is in our project, which means we can modify it class Storecommentrequest extends request{ /** * Determine if the user is Authorized to make this request. * * @return BOOL * /Public Function authorize ()//This method can be used to control access rights, such as prohibit non-paid user comments ... { return false;//Note! Here the default is False, remember to change to True } /** * Get The validation rules, which apply to the request. * * @return Array * /Public Function rules ()//This method returns an array of validation rules, which is validator's validation rule { return [ // ]; }}
So it's easy to let the rules method return our validation rules in addition to the authorize method returning true:
<?php//... Public function rules () { return [ ]; } // ...
Then modify our controller:
<?php//... Before: Public function poststorecomment (Request $request) public function Poststorecomment (\app\http\requests\ Storecommentrequest $request) { //... } // ...
This laravel automatically calls storecommentrequest for form validation.
Exception handling
If the form validation fails, Laravel redirects to the previous page and writes the error to the session, and if it is an AJAX request, it returns a JSON data with an HTTP status of 422, similar to this:
{comment: ["The comment field is required."]}
Here do not elaborate on how to change the information, if anyone want to see the relevant tutorials, you can leave a message.
We mainly say how to customize the error handling.
In general, errors in Laravel are exceptions (Exception), and we can do this uniformly in app\exceptions\handler.php. The Form request does throw a illuminate\http\exception\httpresponseexception exception, but the exception is handled specifically in the routing logic.
Let's start by looking at how the form request is executed:
Illuminate\validation\validationserviceprovider:
<?phpnamespace Illuminate\validation;use Illuminate\support\serviceprovider;use Illuminate\Contracts\ Validation\validateswhenresolved;class Validationserviceprovider extends serviceprovider{ /** * Register The service provider. * * @return void */public function Register () { $this->registervalidationresolverhook ();// Look I see I $this->registerpresenceverifier (); $this->registervalidationfactory (); } /** * Register the "validateswhenresolved" container hook. * * @return void */ protected function Registervalidationresolverhook ()//Yes, that's me { // Here you can see that the implementation of ' validateswhenresolved ' has done a listening $this->app->afterresolving (function (validateswhenresolved $ Resolved) { $resolved->validate ();//And then calls its ' validate ' method for validation }); } // ...
You guessed it, the Form request implemented the Illuminate\contracts\validation\validateswhenresolved interface:
<?php namespace Illuminate\foundation\http;use illuminate\http\request;use illuminate\http\response;use Illuminate\http\jsonresponse;use Illuminate\routing\redirector;use Illuminate\container\container;use Illuminate\ Contracts\validation\validator;use Illuminate\http\exception\httpresponseexception;use Illuminate\Validation\ Validateswhenresolvedtrait;use illuminate\contracts\validation\validateswhenresolved; Is you use Illuminate\contracts\validation\factory as validationfactory;//we ' app\http\requests\request ' is inherited from this ' Formrequest ' class Formrequest extends Request implements validateswhenresolved//Is you {use validateswhenresolvedtrait; We'll have a look at this later.
The Validate method in the Formrequest base class is implemented by this illuminate\validation\validateswhenresolvedtrait:
Illuminate\validation\validateswhenresolvedtrait:
<?phpnamespace Illuminate\validation;use Illuminate\contracts\validation\validationexception;use Illuminate\ contracts\validation\unauthorizedexception;/** * Provides default implementation of validateswhenresolved contract. */trait validateswhenresolvedtrait{ /** * Validate the class instance. * * @return void * /Public Function validate ()//This implements the ' validate ' method { $instance = $this Getvalidatorinstance (); This gets the ' Validator ' instance if (! $this->passesauthorization ()) { $this->failedauthorization (); This is a failed process called Access authorization } elseif (! $instance->passes ()) { $this->failedvalidation ($instance); Here we call the processing of validation failure, we mainly see here } } //...
In validate, if the validation fails, it calls $this->failedvalidation () and continues:
Illuminate\foundation\http\formrequest:
<?php//... /** * Handle a failed validation attempt. * * @param \illuminate\contracts\validation\validator $validator * @return Mixed * * protected function failedvalidation (Validator $validator) { throw new Httpresponseexception ($this->response (// This throws the legendary anomaly $this->formaterrors ($validator)) ); }
Finally see the anomaly! But this anomaly was handled in another place:
Illuminate\routing\route:
<?php //... /** * Run the route action and return the response. * * @param \illuminate\http\request $request * @return Mixed * /Public Function run (Request $request) c8/>{ $this->container = $this->container?: New Container; try { if (! is_string ($this->action[' uses ')) { return $this->runcallable ($request); } if ($this->customdispatcherisbound ()) { return $this->runwithcustomdispatcher ($request); } return $this->runcontroller ($request); } catch (Httpresponseexception $e) {//Is here return $e->getresponse ();//return directly to the response to the client } } // ...
At this point, the whole idea is clear, but let's see how the response generated in the httpresponseexception exception generated here:
Illuminate\foundation\http\formrequest:
<?php//... 132 Line: if ($this->ajax () | | $this->wantsjson ()) {//processing of the AJAX request return new Jsonresponse ($errors, 422); c3/>} return $this->redirector->to ($this->getredirecturl ())//handling of normal form submissions ->withinput ($this- >except ($this->dontflash)) ->witherrors ($errors, $this->errorbag);
I'm sure you can see it.
How to implement custom error handling, here are two ideas to rewrite App\http\requests\request's failedvalidation:
Throw a new exception, inherit the httpresponseexception exception, re-implement the GetResponse method, the exception class we can put into app/exceptions/easy to manage, error return still to Laravel;
Throws a custom exception for us, which is handled in App\exceptions\handler.
The implementation is not written here (see the Laravel Documentation for error handling section, Chinese document portal), if you have other methods or ideas you can communicate with me in the comments.
Add
If your controller uses illuminate\foundation\validation\validatesrequests this trait validate method to verify, the same, Validation failures here also throw illuminate\http\exception\httpresponseexception exceptions, which can be handled by referring to the solution above.
http://www.bkjia.com/PHPjc/1136626.html www.bkjia.com true http://www.bkjia.com/PHPjc/1136626.html techarticle Laravel using Formrequest for form verification methods and problem summary, laravelformrequest in ' Laravel ', each request will be encapsulated as a ' request ' object, ' form Request ' object ...