To create an Ajax validation in Laravel, use the “default validation with jQuery Ajax.”
Here is the step-by-step guide:
Step 1: Set up Laravel Configuration
composer create-project laravel/laravel laravelajaxvalidation --prefer-dist
After setting up the configuration, we can define routes, models, and a controller for the next step.
Step 2: Define the model and controller
Type the following command to generate a model and controller.
php artisan make:model Form
php artisan make:controller FormController
It will create two files.
- Form.php
- FormController.php
Create a create.blade.php file inside the views folder.
<html lang="en"> <head> <title>Laravel Ajax Validation Tutorial</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> </head> <body> <div class="container"> <h2 class="jumbotron">Laravel Ajax Validation</h2> <form> <div class="form-group"> <label>Footballer Name</label> <input type="text" name="footballername" class="form-control" placeholder="Enter Footballer Name" id="footballername"> </div> <div class="form-group"> <label>Club</label> <input type="text" name="club" class="form-control" placeholder="Enter Club" id="club"> </div> <div class="form-group"> <strong>Country</strong> <input type="text" name="country" class="form-control" placeholder="Enter Country" id="country"> </div> <div class="form-group"> <button class="btn btn-success" id="submit">Submit</button> </div> </form> </div>
Step 3: Define a function in FormController
In the FormController.php, define a function, and write the following code.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class FormController extends Controller { public function create() { return view('create'); } }
Now, we can define routes.
Follow routes >> web.php file and define the following routes.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\FormController; Route::get('/', function () { return view('welcome'); }); Route::get('form/create', [FormController::class, 'create'])->name("form.create");
Go to the terminal and start the development server:
php artisan serve
Move to the browser and hit this URL: http://localhost:8000/form/create
Step 4: Add jQuery code
Include jQuery.ajax() function to submit the request to the server with all input fields in that click event.
//create.blade.php <html lang="en"> <head> <meta name="_token" content="{{csrf_token()}}" /> <title>Laravel Ajax Validation Tutorial</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.js" integrity="sha512-+k1pnlgt4F1H8L7t3z95o3/KO+o78INEcXTbnoJQ/F2VqDVhWoaiVml/OEHv9HsVgxUaVW+IbiZPUJQfF/YxZw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </head> <body> <div class="container"> <h2 class="jumbotron">Laravel Ajax Validation</h2> <div class="alert alert-danger" style="display:none"></div> <form> <div class="form-group"> <label>Footballer Name</label> <input type="text" name="footballername" class="form-control" placeholder="Enter Footballer Name" id="footballername"> </div> <div class="form-group"> <label>Club</label> <input type="text" name="club" class="form-control" placeholder="Enter Club" id="club"> </div> <div class="form-group"> <strong>Country</strong> <input type="text" name="country" class="form-control" placeholder="Enter Country" id="country"> </div> <div class="form-group"> <button class="btn btn-success" id="submit">Submit</button> </div> </form> </div> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#submit').click(function(e){ e.preventDefault(); jQuery.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') } }); jQuery.ajax({ url: "{{ url('/form') }}", method: 'POST', data: { footballername: jQuery('#footballername').val(), club: jQuery('#club').val(), country: jQuery('#country').val() }, success: function(data){ if(data.errors) { jQuery('.alert-danger').html(''); jQuery.each(data.errors, function(key, value){ jQuery('.alert-danger').show(); jQuery('.alert-danger').append('<li>'+value+'</li>'); }); } else { console.log(data.success) } } }); }); }); </script> </body> </html>
Now, we can add code in the store() function to validate all input fields.
public function store(Request $request) { $validator = \Validator::make($request->all(), [ 'footballername' => 'required', 'club' => 'required', 'country' => 'required', ]); if ($validator->fails()) { return response()->json(['errors'=>$validator->errors()->all()]); } }
Add post route in web.php file.
Route::post('/form', [FormController::class, 'store'])->name("form.store");
Step 5: Display Error
If you click the submit button and all fields are blank, then display an error.
Step 6: Set up a MySQL database
Configure the database in the .env file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=8889 DB_DATABASE=laravelform DB_USERNAME=root DB_PASSWORD=root
Hit the following command in your terminal to create a migration file.
php artisan make:migration create_forms_table
Now, we need to add the database column name. So navigate to database >> migrations >> [timestamp].create_forms_table.
public function up(): void { Schema::create('forms', function (Blueprint $table) { $table->id(); $table->string('footballername'); $table->string('club'); $table->string('country'); $table->timestamps(); }); }
Migrate the table to the database.
php artisan migrate
In the database, you can see the forms table.
Step 7: Add code in store function to store the data
First, we need to change in create.blade.php file:
<html lang="en"> <head> <meta name="_token" content="{{csrf_token()}}" /> <title>Laravel Ajax Validation Tutorial</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.js" integrity="sha512-+k1pnlgt4F1H8L7t3z95o3/KO+o78INEcXTbnoJQ/F2VqDVhWoaiVml/OEHv9HsVgxUaVW+IbiZPUJQfF/YxZw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </head> <body> <div class="container"> <h2 class="jumbotron">Laravel Ajax Validation</h2> <div class="alert alert-danger" style="display:none"></div> <div class="alert alert-success" style="display:none"></div> <form> <div class="form-group"> <label>Footballer Name</label> <input type="text" name="footballername" class="form-control" placeholder="Enter Footballer Name" id="footballername"> </div> <div class="form-group"> <label>Club</label> <input type="text" name="club" class="form-control" placeholder="Enter Club" id="club"> </div> <div class="form-group"> <strong>Country</strong> <input type="text" name="country" class="form-control" placeholder="Enter Country" id="country"> </div> <div class="form-group"> <button class="btn btn-success" id="submit">Submit</button> </div> </form> </div> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#submit').click(function(e){ e.preventDefault(); jQuery.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') } }); jQuery.ajax({ url: "{{ url('/form') }}", method: 'POST', data: { footballername: jQuery('#footballername').val(), club: jQuery('#club').val(), country: jQuery('#country').val() }, success: function(data){ if(data.errors) { jQuery('.alert-danger').html(''); jQuery('.alert-success').hide(); jQuery.each(data.errors, function(key, value){ jQuery('.alert-danger').show(); jQuery('.alert-danger').append('<li>'+value+'</li>'); }); } else { jQuery('.alert-success').html(''); jQuery('.alert-danger').hide(); jQuery('.alert-success').show(); jQuery('.alert-success').append('<li>'+data.success+'</li>'); } } }); }); }); </script> </body> </html>
Now add code in the FormController.php file:
public function store(Request $request) { $validator = \Validator::make($request->all(), [ 'footballername' => 'required', 'club' => 'required', 'country' => 'required', ]); if ($validator->fails()) { return response()->json(['errors'=>$validator->errors()->all()]); } $footballer= new Form(); $footballer->footballername=$request->get('footballername'); $footballer->club=$request->get('club'); $footballer->country=$request->get('country'); $footballer->save(); return response()->json(['success'=>'Record has been successfully added']); }
When you click on the submit button, a success message will print:
Our forms table looks like this:
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
hey 🙂 this is awesome stuff <3 I just wanted to know if you are aware that that when the submit button is clicked(without filling the inputs) many times consecutively, the error message is keep on repeating below the other. How to overcome this?
Hi, We have updated this article and solved all the bugs you face in this tutorial.
Please go through all the steps mentioned in this article and fix your bug.
Also, we added a new functionality where you can store the data in the database.
I hope this will help you!