10

¿How i can capture errors from methos of controller in Laravel with Axios? The problem is the following, when the data passes through the validator of the myProfile method in the UserController in laravel and is correct, a json response is generated in the method and then Axios takes them and displays the toast Success message, but when i passes erroneous or empty data to the validor and this fails, Axios does not take the json with the error and shows me the empty toast and generates an error 422 in the console.

myProfile in User controller

public function myProfile(Request $request)
{
    $valido = $this->validate($request, [
        'firstname' => 'required|min:3|max:15',
        'lastname' => 'min:2|max:15',
        'gender' => 'numeric',
        'description' => 'max:200',
    ]);

    if($valido){
        return response()->json([
            'status' => 'success',
            'msg' => 'Ok',
        ], 201);
    }
    else{
        return response()->json([
            'status' => 'error',
            'msg' => 'Error',
        ], 422);
    }

}

Profile.vue (Axios section)

updateUser(){
        const value = {
            'id': this.user.id,
            'firstname': this.user.firstname,
            'lastname': this.user.lastname,
            'gender': this.user.gender,
            'description': this.user.description,
        } 

        axios.put('/dashboard/profile', value)
            .then((response) => {
                let title = response.data.status;
                let body = response.data.msg;
                this.displayNotificationSuccess(title, body);
            })
            .catch((error) => {
                let title = error.response.data.status;
                let body = error.response.data.msg;
                this.displayNotificationError(title,body);
            })
    }

Screenshot when Axios capture json Success fron controller

Screenshot when Axios capture Success request

Screenshot when Axios not capture json error from controller

Error

Screenshot from console for json error no capture by axios

Error 422 in console

¿How i can solved that problem? I used Laravel 5.6, Vuejs 2 and Axios

4
  • Controller request validation will throw an exception on failure and a response returned immediately. If you look at the 422 response in the console, you'll see that the structure differs from what you're expecting. Commented Apr 16, 2018 at 1:46
  • @fubar, Yes, I understand that, but ¿how can I solve what is happening? I new in Laravel and Vue Commented Apr 16, 2018 at 1:56
  • 1
    You can either capture the exception in your controller, and return your own error response. Or you adapt the Axios catch function to handle the 422 response currently being returned. Commented Apr 16, 2018 at 2:01
  • Ok and ¿how do you do that? Commented Apr 16, 2018 at 15:53

1 Answer 1

10

If you wrap the validate() method call in a try/catch block, then you can catch the ValidationException thrown when the request is invalid. This will allow you to return your own response.

I've shown you an example of this below, and included the validation errors too, should you wish to output these on the front-end.

<?php

use Illuminate\Validation\ValidationException;

public function myProfile(Request $request)
{
    try {
        $this->validate($request, [
            'firstname'   => 'required|min:3|max:15',
            'lastname'    => 'min:2|max:15',
            'gender'      => 'numeric',
            'description' => 'max:200',
        ]);

        return response()->json([
            'status' => 'success',
            'msg'    => 'Okay',
        ], 201);
    }
    catch (ValidationException $exception) {
        return response()->json([
            'status' => 'error',
            'msg'    => 'Error',
            'errors' => $exception->errors(),
        ], 422);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank very much @fubar!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.