In Laravel 11 Vue JS, form validation is the process that allows users to submit forms and send properly validated data to the server.
Let’s start validating the vue js form and submit it to the server with validation:
Step 1: Set Up Vue.js in Laravel 11
Run the following commands to set up vue.js in laravel applications:
composer require laravel/ui
php artisan ui vue
npm install
npm run dev
Step 2: Create a Form Component in Vue.js
Create form component named FormComponent.vue
in resources/js/components/
directory and add validation rules with error messages in it:
<template>
<div>
<form @submit.prevent="submitForm">
<div>
<label for="name">Name</label>
<input type="text" v-model="form.name" />
<span v-if="errors.name">{{ errors.name[0] }}</span>
</div>
<div>
<label for="email">Email</label>
<input type="email" v-model="form.email" />
<span v-if="errors.email">{{ errors.email[0] }}</span>
</div>
<button type="submit">Submit</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
form: {
name: '',
email: ''
},
errors: {}
};
},
methods: {
async submitForm() {
try {
const response = await axios.post('/api/submit-form', this.form);
// Handle success
} catch (error) {
if (error.response && error.response.status === 422) {
this.errors = error.response.data.errors;
}
}
}
}
};
</script>
Step 3: Create Controller
Run the following command to create a controller class:
php artisan make:controller FormController
Edit app/Http/Controllers/FormController.php
file and build some method in it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class FormController extends Controller
{
public function submitForm(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 form data
return response()->json(['message' => 'Form submitted successfully']);
}
}
Step 4: Define Routes
use App\Http\Controllers\FormController;
Route::post('/api/submit-form', [FormController::class, 'submitForm']);
Step 5: Import Component and View
Edit resources/js/app.js
file, and import form component in it:
import Vue from 'vue';
import FormComponent from './components/FormComponent.vue';
new Vue({
el: '#app',
components: {
FormComponent
}
});
And edit resources/views/welcome.blade.php
file, and import form component view file in it:
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Vue.js Form Validation Example - itcodStuff.com</title>
</head>
<body>
<div id="app">
<form-component></form-component>
</div>
<script src="{{ mix('js/app.js') }}"></script>
</body>
</html>
Step 6: Test Application
Run the following command on cmd to start application development server:
php artisan serve
Open browser and type the following url in it:
http://127.0.0.1:8000