Summer Sale! All accounts are 50% off this week.

Norbertho's avatar

How to return response 422 status and custom error message

Hi i would like to return a response 422 status code and a custom message to axios from laravel controller. How can i do that? I know i can do this but how to attach the 422 status code?

return response()->json([
    'errors' => 'Password does't match',
]);
0 likes
6 replies
alanholmes's avatar

hi @norbertho

you just need to pass it as the second param of ->json()

eg:

return response()->json([
            'errors' => "Password does't match",
        ], 422);

Or instead of the 422 you could do this, so you (in future) dont have to remember what 422 is (useful for other areas too)

return response()->json([
            'errors' => "Password does't match",
        ], Response::HTTP_UNPROCESSABLE_ENTITY);
2 likes
Norbertho's avatar

Hi @alanholmes I have tried both, but for some reson i am not able to console.log(errors) in the axios .catch

Norbertho's avatar

when i console.log i see this in my console:

Error: Request failed with status code 422
    at createError (app.js:699)
    at settle (app.js:960)
    at XMLHttpRequest.handleLoad (app.js:168)
Norbertho's avatar

so I have used axios to make a post request to my controller:

saveData(){
            let data = new FormData();
            data.append('password', this.password);
            data.append('password1', this.password1);
            data.append('password2', this.password2);
            axios.post('changePassword', data).then(()=>{

            }).catch((errors)=>{
                console.log(errors);

            })
        }

Then I process it in my controller:

 public function changePassword(Request $request)
    {
        $user = Auth::user();
        if(!Hash::check($request->password, Auth::user()->password)){
            return response()->json(['errors' => 'Paasword does not match'], 422);
        }else{
            return( 'good boy');
        }
        $user->update();
        return $user;
    }

how can I console log the errors?

alanholmes's avatar
Level 35

Hi @norbertho

I have done this on an axios request before

window.axios.put('url', {
}).catch(error => {
    console.log(error.response);
});

so error.response has the actual response rather than just the 422 error thrown

1 like
Norbertho's avatar

for some reason i had to go deeper: so this is my catch

.catch((errors)=>{
                console.log(errors.response.data.errors);

            })

now i get the error message

Please or to participate in this conversation.