Decoding Laravel Validation : $this->validate()
Jul 31, 2017Recently, while working on one of my project, I was wondering how laravel $this->validate()
works under the hood. So I decided to dig deep into laravel core to find its implementation. Upon finding, it persuaded me to start a series called “Decoding Laravel”. So from now on, I’m planning to publish once in a while explaining about core functionalities of laravel. Today, we are going to decode laravel validation ($this->validate()) method. I’m using laravel 5.4 for this article.
$this->validate()
In order to understand its implementation, first we need to know what does $this->validate()
do. So lets start with its function definition on Illuminate\Foundation\Validation\ValidatesRequests
trait file. You can see this trait being imported and used on App\Http\Controllers\Controller
file so that you can access it with $this
It has four parameters.
- The Request object
- List of rules for validation
- List of custom errors messages if any.
- List of custom attributes (To know more about custom attributes implementation, check this stackoverflow answer)
Now inside, you can see it calls the getValidationFactory()
method. So lets go to its definition on same file.
getValidationFactory()
returns the instance of contract class Illuminate\Contracts\Validation\Factory
which is binded with laravel’s Validation Factory class on Illuminate\Foundation\Application
the core file.
After calling getValidationFactory()
it calls make()
method. Which is nothing but calling the original Validator::make()
.
$this->validate()
is nice wrapper around the Validator::make()
method.
Now, if validation passes, it doesn’t do anything but if it fails, it throws Exception
Here, you can see it throws Illuminate\Validation\ValidationException
exception after calling the buildFailedValidationResponse
method and this is passed with request object and list of errors that is returned from formatValidationErrors
method.
On buildFailedValidationResponse method, it is generates failed validation response along with Redirect URL, Old inputs and Error messages.
Handling Exception
ValidationException class on Illuminate\Validation
accepts two params on construct method, validator instance and redirect response instance that is returned from buildFailedValidationResponse
Now thrown exception is caught and handled by laravel’s Handler class on Illuminate\Foundation\Exceptions\Handler
class.
Here you can see it checks for ValidationException and returns the response from convertValidationExceptionToResponse
method.
This method checks whether the response variable on ValidationException has any value(in our case we already have redirect response stored on response variable), if so, it simply returns it. If not, it fetches the error messages and returns the redirect response accordingly.
This is how laravel validation using $this->validate()
method works.