Form Validation in vue js with laravel show you how to validate a Vue.js form and submit it to the server with proper validation:
Step 1: Integrate Vue.js into Laravel 11
First, set up Vue.js in your Laravel project by executing these commands:
composer require laravel/ui
php artisan ui vue
npm install
npm run dev
Step 2: Develop a Vue.js Form Component
Create a Vue component named FormComponent.vue
inside the resources/js/components/
directory. Include validation rules and error messages as shown below:
<template>
<div>
<form @submit.prevent="handleSubmit">
<div>
<label for="name">Name</label>
<input type="text" v-model="formData.name" />
<span v-if="validationErrors.name">{{ validationErrors.name[0] }}</span>
</div>
<div>
<label for="email">Email</label>
<input type="email" v-model="formData.email" />
<span v-if="validationErrors.email">{{ validationErrors.email[0] }}</span>
</div>
<button type="submit">Submit</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
formData: {
name: '',
email: ''
},
validationErrors: {}
};
},
methods: {
async handleSubmit() {
try {
const response = await axios.post('/api/handle-form', this.formData);
// Handle successful response
} catch (error) {
if (error.response && error.response.status === 422) {
this.validationErrors = error.response.data.errors;
}
}
}
}
};
</script>
Step 3: Generate a Controller
Create a controller by running:
php artisan make:controller FormHandlerController
Update the app/Http/Controllers/FormHandlerController.php
file with the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class FormHandlerController extends Controller
{
public function handleForm(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|email|max:255',
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()], 422);
}
// Process the form data
return response()->json(['message' => 'Form successfully submitted']);
}
}
Step 4: Set Up Routes
Edit your routes/web.php
file to include:
use App\Http\Controllers\FormHandlerController;
Route::post('/api/handle-form', [FormHandlerController::class, 'handleForm']);
Step 5: Import and Use the Component
Update resources/js/app.js
to import and register your form component:
import Vue from 'vue';
import FormComponent from './components/FormComponent.vue';
new Vue({
el: '#app',
components: {
FormComponent
}
});
Then, edit resources/views/welcome.blade.php
to include your Vue component:
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Vue.js Form Validation Example</title>
</head>
<body>
<div id="app">
<form-component></form-component>
</div>
<script src="{{ mix('js/app.js') }}"></script>
</body>
</html>
Step 6: Run and Test
Start the Laravel development server with:
php artisan serve
Open your browser and navigate to:
http://127.0.0.1:8000