mercredi 9 mars 2022

Manually throw Laravel ValidationException VS FormRequestValidationException

Is there any difference when I throw ValidationException manally and when ValidationException is thrown by laravel from FormRequest.

Following code will clear the problem

UserController.php

public function checkEmailExists(Request $request){
    try {
        $validation =  Validator::make($request->only('email'), [
            'email' => 'required|email|exists:users,email',
        ]);
        if ($validation->fails()) {
            throw (new ValidationException($validation));
        }
    } catch (\Exception $exception){
        return $exception->render(); //nothing is returned/displayed
    }
}

Handler.php

public function render($request, Throwable $exception)
{
    dd($exception instanceof Exception);
}

From the UserController I am throwing ValidationException manually and in Handler.php render method I am checking the $exception is an instance of Exception. So If I throw ValidationException manually then

dd($exception instanceof Exception); //gives false

But when I use UserStoreRequest (FormRequest)

UserController.php

public function checkEmailExists(UserStoreRequest $request){
    //Exception thrown by laravel if validation fails fro UserStoreRequest
}

then in Handler.php render() method

dd($exception instanceof Exception); //gives true

1:- Why it has different behavior when I throw ValidationException manally and when ValidationException is thrown by laravel from FormRequest?

2:- If I throw ValidationException manually then in the catch block I get the following error

Error {#3627
  #message: "Call to undefined method Illuminate\Validation\ValidationException::render()"
  #code: 0
  #file: "myproject/app/Http/Controllers/UserController.php"
  #line: 33


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/GyuLEmX
via IFTTT

Aucun commentaire:

Enregistrer un commentaire