Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is validate() method accessible via request()?

Quoting the Laravel documentation:

By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules

It's true, reading the code, App\Http\Controllers\Controller actually uses ValidatesRequests trait. And ValidatesRequests has a validate method.

What is really strange for me is that everywhere else in the documentation, the validate method is called on $request object. And it works this way. I can validate a form with this code:

public function store()
{
    $attributes = request()->validate([
        'name' => 'required|string|max:255',
    ]);
    // ...
}

But I don't see any presence of a validate method on the Request class. Just a strange comment line at the beginning of the file:

/**
 * @method array validate(array $rules, array $messages = [], array $customAttributes = [])
 */

So there are two things:

  • I don't know what to trust in Laravel documentation.
  • And I don't understand how the validation works on the $request object.

And my actual question is:

Is the initial quote I pasted from the documentation still true if I use the validate method through $request object? If so, how does it works?

like image 427
rap-2-h Avatar asked Nov 16 '17 16:11

rap-2-h


People also ask

What is request validation in laravel?

When using the validate method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

How does laravel validation work?

The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.

How do I validate a request in laravel API?

You can set any key / pair values in the json, “$validator->errors()” send the error with attribute name in the response. Step 6 : Add “LoginRequest. php” file in the API's controller file. Step 7 : Add “LoginRequest”as a parameter in the controller which you will call from API.

What is form request in laravel?

Form requests are custom request classes that encapsulate their own validation and authorization logic. Let's create our own form request class, all you need is to run this command: php artisan make:request StoreUserRequest.


2 Answers

That "strange comment" was removed a couple days ago.

I believe Request gets its validate function from the Request::macro('validate', ...) call in FoundationServiceProvider.php. See this article for more on macros.

like image 120
ceejayoz Avatar answered Sep 24 '22 07:09

ceejayoz


Well, validate method is there, but it's not in FormRequest directly but in ValidatesWhenResolvedTrait trait so it's usable without any problem in FormRequest so documentation is fine.

Let's look at the beginning of this trait:

trait ValidatesWhenResolvedTrait
{
    /**
     * Validate the class instance.
     *
     * @return void
     */
    public function validate()
    {
        $this->prepareForValidation();

        $instance = $this->getValidatorInstance();

        if (! $this->passesAuthorization()) {
            $this->failedAuthorization();
        } elseif (! $instance->passes()) {
            $this->failedValidation($instance);
        }
    }

so when you are running in controller:

request()->validate

you are running the method from trait and ValidatesRequests has nothing in common with this.

Alternatively if you would like to use "Controller way" validation you could do:

$this->validate(request(), [
        'name' => 'required|string|max:255',
    ]);

and now you would be using validate method from ValidatesRequests requests.

As you see there are multiple ways of running validation in Laravel. I personally use only Form Request validation instead.

like image 20
Marcin Nabiałek Avatar answered Sep 22 '22 07:09

Marcin Nabiałek