Throughout Laravel 10 Ajax Form submit using Ajax example tutorial, you will learn how to submit form data with validation (server side) in laravel application.
In this Laravel 10 form submit with Ajax we are going to create a contact us form and post the form data on the controller using jQuery Ajax from the blade file, and validate the form data using laravel validation before saving it to the database.
Step 1: Install Laravel App
First, you need to install a fresh Laravel application using the following command:
composer create-project --prefer-dist laravel/laravel laravel-app
Next, go inside the app directory
cd laravel-app
Step 2: Setup Database Credential
Next, open the .env file which is located in your project root directory and update your database credential such as database name, username, password or your DB.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
Step 3: Make Model and Migration
Now generate a model and migration file by just adding the below command in your terminal which generates a model file and migration.
php artisan make:model Contact -m
After this open the newly created file database\migrations\2020_09_14_120412_create_contacts_table.php and add the below code on it.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateContactsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contacts', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->string('mobile'); $table->string('subject'); $table->text('message'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contacts'); } }
Next, we need to run the migrate command to generate database tables. So open your terminal and run the below command.
php artisan migrate
Next, open the app\Models\Contact.php file and add fillable properties in your contact model.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Contact extends Model { use HasFactory; protected $fillable = [ 'name', 'email', 'mobile', 'subject', 'message' ]; }
Step 5: Make Routes
First, you need to open the routes/web.php file and add two routes for implementing the Laravel form submit using ajax. One route will show the form and another is to save the data to the database using ajax request.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;
Route::get('contact-us', [ ContactController::class, 'create' ]);
Route::post('contact-us', [ ContactController::class, 'store' ]);
Route::get('/', function () {
return view('welcome');
});
Step 6: Create Controller
Now create a ContactController to handle your request in the backend. In this controller, we add two methods one for displaying contact form and another is submitting data in database.
php artisan make:controller ContactController
After creating the now constroller now open the app/Http/Controllers/ContactController.php file and update the following code on it.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Contact; class ContactController extends Controller { public function create() { return view('contact_form'); } public function store(Request $request) { Contact::create([ 'name' => $request->name, 'email' => $request->email, 'subject' => $request->subject, 'mobile_number' => $request->mobile_number, 'message' => $request->message ]); return response()->json(['success'=>'Form is successfully submitted!']); } }
Step 7: Create Blade File for Ajax Request
Now navigate the resources/views directory and create a file named as “contact_form.blade.php” file. Next, open the resources/views/contact_form.blade.php and update the below code on it.
<html lang="en"> <head> <title>Laravel Ajax jquery Validation Tutorial</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> </head> <body> <div class="container panel panel-default "> <h2 class="panel-heading">Laravel Form Submit Using Ajax jquery</h2> <form id="contactForm"> <div class="form-group"> <input type="text" name="name" class="form-control" placeholder="Enter Name" id="name"> <span class="text-danger" id="name-error"></span> </div> <div class="form-group"> <input type="text" name="email" class="form-control" placeholder="Enter Email" id="email"> <span class="text-danger" id="email-error"></span> </div> <div class="form-group"> <input type="text" name="mobile_number" class="form-control" placeholder="Enter Mobile Number" id="mobile_number"> <span class="text-danger" id="mobile-number-error"></span> </div> <div class="form-group"> <input type="text" name="subject" class="form-control" placeholder="Enter subject" id="subject"> <span class="text-danger" id="subject-error"></span> </div> <div class="form-group"> <textarea class="form-control" name="message" placeholder="Message" id="message"></textarea> <span class="text-danger" id="message-error"></span> </div> <div class="form-group"> <button class="btn btn-success" id="submit">Submit</button> </div> </form> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> <script type="text/javascript"> $('#contactForm').on('submit',function(e){ e.preventDefault(); let name = $('#name').val(); let email = $('#email').val(); let mobile_number = $('#mobile_number').val(); let subject = $('#subject').val(); let message = $('#message').val(); $.ajax({ url: "/contact-form", type:"POST", data:{ "_token": "{{ csrf_token() }}", name:name, email:email, mobile_number:mobile_number, subject:subject, message:message, }, success:function(response){ console.log(response); if (response) { $('#success-message').text(response.success); $("#contactForm")[0].reset(); } }, error: function(response) { $('#name-error').text(response.responseJSON.errors.name); $('#email-error').text(response.responseJSON.errors.email); $('#mobile-number-error').text(response.responseJSON.errors.mobile_number); $('#subject-error').text(response.responseJSON.errors.subject); $('#message-error').text(response.responseJSON.errors.message); } }); }); </script> </body> </html>
Learn Also: Laravel AJAX CRUD Example Tutorial from Scratch
That’s all the Laravel Form Submit using ajax Tutorial example is over now. Hope you have learned new things today.
how to make custom validation ? any idea ?