In this tutorial you will learn about the Laravel 7/6 Ajax Form Submit Validation Tutorial and its application with practical example.
In this Laravel 7/6 Ajax Form Submit Validation Tutorial I’ll show you how to submit form using ajax with validation in laravel 7 and 6. In this tutorial you will learn to submit form using ajax and to implement form validation in laravel.
Laravel 7/6 Ajax Form Submit Validation Tutorial
- Install Laravel Fresh Setup
- Configure .env file
- Create One Model and Migration
- Make Route
- Generate Controller by Command
- Create Blade View
- Start Development Server
Install Laravel Fresh Setup
1 |
composer create-project --prefer-dist laravel/laravel blog |
Configure .env file
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Create Model and Migration
Now, in this step we will create model and migration file for form. Please run the following command:
1 |
php artisan make:model Contact -m |
Once above command is executed there will be a migration file created inside database/migrations/ directory. Now, open contact migration file and put the below code here :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateContactsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contacts', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email'); $table->string('mobile_number'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contacts'); } } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Make Route
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 |
Route::get('ajax-form-submit', 'FormController@index'); Route::post('save-form', 'FormController@store'); |
Generate Controller by Command
Now, lets create a form controller. Create a controller named FormController using command given below –
1 |
php artisan make:controller FormController |
Now, we will create two methods in controller file. The first is index method to display contact form and second method to store data in the mysql database :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response; use App\Contact; class FormController extends Controller { public function index() { return view('ajax-form'); } public function store(Request $request) { request()->validate([ 'name' => 'required', 'email' => 'required|email|unique:users', 'mobile_number' => 'required|unique:users' ]); $data = $request->all(); $check = Contact::insert($data); $arr = array('msg' => 'Something goes to wrong. Please try again lator', 'status' => false); if($check){ $arr = array('msg' => 'Successfully submit form using ajax', 'status' => true); } return Response()->json($arr); } } |
Step 6: Create a blade view
In this step, we will create one blade file name ajax-form.blade.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>laravel 6 Ajax Form Submission Example</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script> <style> .error{ color:red; } </style> </head> <body> <div class="container"> <h2 style="margin-top: 10px;">laravel 6 Ajax Form Submission Example</h2> <br> <br> <form id="contact_us" method="post" action="javascript:void(0)"> @csrf <div class="form-group"> <label for="formGroupExampleInput">Name</label> <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name"> <span class="text-danger">{{ $errors->first('name') }}</span> </div> <div class="form-group"> <label for="email">Email Id</label> <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id"> <span class="text-danger">{{ $errors->first('email') }}</span> </div> <div class="form-group"> <label for="mobile_number">Mobile Number</label> <input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number" maxlength="10"> <span class="text-danger">{{ $errors->first('mobile_number') }}</span> </div> <div class="alert alert-success d-none" id="msg_div"> <span id="res_message"></span> </div> <div class="form-group"> <button type="submit" id="send_form" class="btn btn-success">Submit</button> </div> </form> </div> <script> if ($("#contact_us").length > 0) { $("#contact_us").validate({ rules: { name: { required: true, maxlength: 50 }, mobile_number: { required: true, digits:true, minlength: 10, maxlength:12, }, email: { required: true, maxlength: 50, email: true, }, }, messages: { name: { required: "Please enter name", maxlength: "Your last name maxlength should be 50 characters long." }, mobile_number: { required: "Please enter contact number", digits: "Please enter only numbers", minlength: "The contact number should be 10 digits", maxlength: "The contact number should be 12 digits", }, email: { required: "Please enter valid email", email: "Please enter valid email", maxlength: "The email name should less than or equal to 50 characters", }, }, submitHandler: function(form) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#send_form').html('Sending..'); $.ajax({ url: 'http://localhost/blog/save-form' , type: "POST", data: $('#contact_us').serialize(), success: function( response ) { $('#send_form').html('Submit'); $('#res_message').show(); $('#res_message').html(response.msg); $('#msg_div').removeClass('d-none'); document.getElementById("contact_us").reset(); setTimeout(function(){ $('#res_message').hide(); $('#msg_div').hide(); },10000); } }); } }) } </script> </body> </html> |
Step 7: Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 2 3 |
php artisan serve If you want to run the project diffrent port so use this below command php artisan serve --port=8080 |
Now, open the following URL in browser to see the output –
1 |
http://127.0.0.1:8000/ajax-form-submit |