Laravel 6 - Ajax Form Submit with Custom Validation
In this guide, you'll learn how to submit a form using Ajax in Laravel 6, along with custom validation for form fields.
1. Set Up Your Laravel Project
Ensure that your Laravel project is set up properly. In case you're starting from scratch, you can create a new project using:
2. Install jQuery
Since we are using Ajax for form submission, ensure that jQuery is available in your project.
You can include it by adding the following script to your resources/views/layouts/app.blade.php
or the specific Blade file you're using for the form.
Alternatively, you can install jQuery via npm and include it in your webpack configuration.
3. Create Controller and Route
Generate a controller for handling form submissions:
In the app/Http/Controllers/AjaxFormController.php
file, add the following code:
Next, define the routes in routes/web.php
:
4. Create Blade View with the Form
Create a new Blade view resources/views/ajax-form.blade.php
with the form and Ajax code:
5. Explanation of the Code
-
Form: The form contains three fields: Name, Email, and Age.
-
Ajax Script: The form submission is handled via Ajax using jQuery. When the form is submitted, the data is sent via a POST request to the
/ajax-form-submit
route. -
Validation: Laravel's Validator is used to validate the data on the server side:
-
Name: Required, minimum 3 characters.
-
Email: Required, must be a valid email.
-
Age: Required, must be an integer and at least 18.
-
-
Error Handling: If validation fails, the server will return validation errors in JSON format, which will be displayed dynamically in the view.
6. Run Your Application
Start the Laravel development server:
Now, visit the application in your browser:
Test the Form
-
Leave some fields empty or input invalid data to trigger validation errors.
-
On successful submission, a success message will appear.
7. Conclusion
With this approach, you’ve:
-
Set up an Ajax form submission in Laravel 6.
-
Validated form inputs on the server side using custom validation.
-
Handled form errors and success responses with Ajax.