Handling form submissions with validation in Laravel and Vue.js involves a combination of server-side validation using Laravel and client-side validation using Vue.js. Below are the steps to achieve this:
Make sure you have Laravel installed and set up. You can use Laravel Mix to manage your assets, including Vue.js.
bash# Install Laravel Mix and Vue.js
composer require laravel/ui
php artisan ui vue
npm install && npm run dev
Create a Vue component for your form. This component will handle the form data and client-side validation.
javascript// resources/js/components/ExampleForm.vue
<template>
<form @submit.prevent="submitForm">
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>
</template>
<script>
export default {
data() {
return {
formData: {
// Define form fields and their initial values here
},
errors: {}
};
},
methods: {
validateForm() {
// Implement your client-side validation logic here
// Update the 'errors' object with validation results
},
submitForm() {
this.validateForm();
if (Object.keys(this.errors).length === 0) {
// Send form data to Laravel backend
axios.post('/submit-form', this.formData)
.then(response => {
// Handle successful submission
})
.catch(error => {
// Handle submission error
});
}
}
}
};
</script>
In your Laravel controller, validate the form data using Laravel's validation.
php// app/Http/Controllers/FormController.php
use Illuminate\Http\Request;
class FormController extends Controller
{
public function submitForm(Request $request)
{
$validatedData = $request->validate([
// Define your validation rules here
]);
// Process form data and return a response
}
}
Define routes for your form in web.php
:
php// routes/web.php
use App\Http\Controllers\FormController;
Route::get('/form', function () {
return view('form');
});
Route::post('/submit-form', [FormController::class, 'submitForm']);
Include the Vue component in your Blade view.
php<!-- resources/views/form.blade.php -->
@extends('layouts.app')
@section('content')
<example-form></example-form>
@endsection
Run your Laravel application and visit the form page. The form component will handle both client-side and server-side validation.
bashphp artisan serve
This is a basic setup, and you might need to customize it based on your specific requirements. Make sure to check Laravel and Vue.js documentation for more advanced features and options.