DEV Community

Cover image for How to display laravel validation errors in vuejs
Chidiebere Chukwudi
Chidiebere Chukwudi

Posted on • Edited on • Originally published at jovialcore.tech

How to display laravel validation errors in vuejs

There are several resources that address this topic but I want to just share my solution for a situation where you have to display laravel validation errors in vuejs component not just with the traditional loop but, this time, a nested loop. You should understand better by the time we are done.

Note: I will not go into details on how to write an API in laravel or build a vuejs app frontend. I will just discuss this topic with code snippets that you are probably familiar with if you are used to writing laravel and Vuejs

Lets assume that we return error responses from our backend like so



  public function register(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => 'required|string',
            'email' => 'required|email|unique:users',
            'gender' => 'required',
        ]);

        if ($validator->fails()) {    
            return response()->json($validator->messages(), 400);
        }
}


Enter fullscreen mode Exit fullscreen mode

Lets say the user have some empty fields from the frontend, so in our browser network tab, the laravel validation error responses from our backend looks like this:

Laravel Vuejs

Now, in our Vuejs Component;
We have a state in the data object where we assign the response errors to.



export default {

  data() {
    return{

    notifmsg: ''
         }
    },


Enter fullscreen mode Exit fullscreen mode

While in our catch() function we are assigning laravel validation response like so:



.then(()=> {
// do some magic stuff here
    }).catch(e => {
       this.notifmsg = e.response.data
})


Enter fullscreen mode Exit fullscreen mode

Now here is the thing:
If you go by the traditional way of looping through the response we got from our backend, like so:....



<div v-for="(errorArray, index) in notifmsg" :key="index">
<span class="text-danger">{{ errorArray}} </span>
</div>


Enter fullscreen mode Exit fullscreen mode

...the output on the FE will look like this:

Laravel vuejs

Yeaaah...this is not what we want right ? Yes.

The reason is because validation error response from our laravel app being returned as an array of objects. So, to solve this we'll have to perform a nested loop like so:



<div v-for="(errorArray, idx) in notifmsg" :key="idx">
    <div v-for="(allErrors, idx) in errorArray" :key="idx">
        <span class="text-danger">{{ allErrors}} </span>
    </div>
</div>


Enter fullscreen mode Exit fullscreen mode

The output looks like this :

Laravel Vuejs

Boom...! And thats what we acctually want to achieve. Thanks for reading...

You can reach me out on Twitter. I'm on
Linked too

Please drop your contributions in the comment section if you have any...

Top comments (0)