DEV Community

Cover image for Laravel and Vue.js: How to Display Validation Errors with Example
Suresh Ramani
Suresh Ramani

Posted on • Originally published at techvblogs.com

4

Laravel and Vue.js: How to Display Validation Errors with Example

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:

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Define API route.

routes/api.php

use App\Http\Controllers\Api\UserController;

Route::post('/users', [UserController::class, 'store']);
Enter fullscreen mode Exit fullscreen mode

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.

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

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

Enter fullscreen mode Exit fullscreen mode

Real-Time Display Validation Feedback with Vue.js

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

// 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>
Enter fullscreen mode Exit fullscreen mode

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay