Laravel and Vue.js: How to Display Validation Errors with Example
Published: 2024-01-05 04:38:39

Web development is a dynamic field, and creating applications with Laravel and Vue.js has become a popular choice among developers. In this guide, we'll explore the process of displaying validation errors seamlessly in a Laravel and Vue.js project. We'll walk through the steps with a practical example to illustrate the concepts.

### Understanding Laravel's Validation System
Laravel simplifies the process of validating user input through its built-in validation system. Let's start by defining some validation rules in a Laravel controller. Consider the following example where we validate a simple form submission:
```php
namespace App\Http\Controllers\Api;
 
use App\Http\Controllers\Controller;
 
class UserController extends Controller
{
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users|max:255',
            'password' => 'required|string|min:8',
        ]);

        // Logic to store data in the database
    }
}
```

In this example, if the validation fails, Laravel automatically redirects back to the form with the validation errors.

Define API route.

`routes/api.php`

```php
use App\Http\Controllers\Api\UserController;
 
Route::post('/users', [UserController::class, 'store']);
```

### Passing Validation Errors to Vue.js

To provide a seamless user experience, we want to display these validation errors without a page reload. Let's integrate Vue.js to achieve real-time validation feedback.

Firstly, ensure you have Vue.js set up in your project. You can use Laravel Mix or include Vue.js through a CDN. Now, let's create a Vue component to handle the form and display validation errors.

```html
<!-- resources/views/welcome.blade.php -->
@extends('layouts.app')

@section('content')
    <div id="app">
        <FormComponent></FormComponent>
    </div>
@endsection

```

### Real-Time Display Validation Feedback with Vue.js

Now, let's create the Vue component to handle the form and perform real-time validation.

```html
// resources/js/components/FormComponent.vue
<template>
    <div>
        <!-- Form HTML goes here -->
        <form @submit.prevent="submitForm">
            <input type="text" v-model="formData.name" placeholder="Name">
            <span class="text-red-600" v-if="errors?.name">{{ errors.name[0] }}</span>

            <input type="email" v-model="formData.email" placeholder="Email">
            <span class="text-red-600" v-if="errors?.email">{{ errors.email[0] }}</span>

            <input type="password" v-model="formData.password" placeholder="Password">
            <span class="text-red-600" v-if="errors?.password">{{ errors.password[0] }}</span>

            <button type="submit">Submit</button>
        </form>
        
    </div>
</template>

<script>
export default {
    name:"FormComponent",
    data() {
        return {
            formData: {
                name: '',
                email: '',
                password: '',
            },
            errors: {},
        };
    },
    methods: {
        submitForm() {
            axios.post('/api/users', this.formData)
                .then(response => {
                    // Handle success
                })
                .catch(error => {
                    if (error.response.status === 422) {
                        this.errors = error.response.data.errors;
                    }
                });
        },
    },
};
</script>
```

In this example, when the form is submitted, a request is sent to the server. If the validation fails, the server responds with a 422 Unprocessable Entity status and includes the validation errors. The Vue component then updates the  `errors`  data property, which is bound to the template to display the errors in real time.

### Conclusion

Integrating Laravel and Vue.js for real-time validation errors provides a smoother user experience. This example serves as a starting point, and you can customize it based on your project's requirements. Experiment with these concepts and adapt them to your specific use cases.