Laravel 9 Ajax Post Request Example with Validation

Throughout this Laravel Ajax Post Request Example, you will understand how to send a ajax post request in Laravel application to store record in database and how to validate data using ajax jquery request.

Ajax post or get request is the primary requirement of all admin backend or frontend projects. Ajax post request in laravel can be implement in laravel 5, laravel 6, laravel 7, laravel 8 or laravel 9 apps.

Laravel Ajax Post Request Example

Follow the following steps to send ajax post request in laravel application;

  • Step 1: Download Laravel 9 App
  • Step 2: Configure Database Credentials
  • Step 3: Generate Model & Migration
  • Step 4: Add Routes
  • Step 5: Create Ajax Controller
  • Step 6: Create Blade File
  • Step 7: Send ajax request in laravel
  • Step 8: Run Laravel Application

Download Laravel 9 App

First run the following command in terminal to download laravel fresh app:

composer create-project --prefer-dist laravel/laravel laravel-ajax-app

Go into the app:

laravel-ajax-app

Configure Database Credentials

Open the .env file and add your database credentials such as database name, username equally important password:

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

Create Model & Migration

Here we create new model and migration file using the below command:

php artisan make:model Contact -m

Now open the contacts migration database\migrations\2021_12_06_025934_create_contacts_table.php and upate 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')->unique();
            $table->string('mobile');
            $table->text('message');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

Run the migrate command for generating contacts table.

php artisan migrate

We need to update fillable or guardian for storing in database. Just add the fillable property in your Contact model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;
    protected $fillable = [
        'name', 'email', 'mobile', 'message'
    ];
}

Add Routes

In this step, open web.php file from routes direcotry. And update the following routes into web.php file:

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;

Route::get('contact', [ContactController::class, 'create']);
Route::post('contact', [ContactController::class, 'store'])->name('contact');

Create Controller

In this step, run the following command on command prompt to create controller file:

php artisan make:controller ContactController

After successfully created controller, next opent the app\Http\Controllers\ContactController.php file add below code on it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function create()
    {

      return view('contacts');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'    => 'required',
            'email'   => 'required|email',
            'mobile'  => 'required',
            'message' => 'required'
        ]);

        // echo "<pre>"; print_r($data); die;
        #create or update your data here


        return response()->json(['success'=>'Ajax request submitted successfully']);
    }
}

Create Blade File

Next, you need to add a blade file contacts.blade.php in your views directory. Next open the resources\views\contacts.blade.php file and put the following code on it.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Ajax Post Request Example</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>

<body>
    <div class="container">
        <h1>Laravel 9 Ajax Post Request Example with <a href="https://codingdriver.com/">Coding Driver</a></h1>
          <span class="success" style="color:green; margin-top:10px; margin-bottom: 10px;"></span>
        <form>
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="name" class="form-control" placeholder="Enter Name" required="">
                <span class="text-danger" id="nameError"></span>
            </div>

            <div class="form-group">
                <label>Email:</label>
                <input type="email" name="email" class="form-control" placeholder="Enter Email" required="">
                <span class="text-danger" id="emailError"></span>
            </div>

            <div class="form-group">
                <strong>Mobile Number:</strong>
                <input type="text" name="mobile" class="form-control" placeholder="Enter Mobile" required="">
                <span class="text-danger" id="mobileError"></span>
            </div>
            <div class="form-group">
                <strong>Message:</strong>
                <input type="text" name="message" class="form-control" placeholder="Enter Your Message" required="">
                <span class="text-danger" id="messageError"></span>
            </div>
            <div class="form-group">
                <button class="btn btn-success save-data">Submit</button>
            </div>
        </form>
    </div>
</body>
</html>

Send Ajax Request

After create the blade file now add the ajax jquery code after the last closing div of your blade file and send the post request to your controller via ajax.

<script>

  $(".save-data").click(function(e){
      e.preventDefault();

      let name = $("input[name=name]").val();
      let email = $("input[name=email]").val();
      let mobile = $("input[name=mobile]").val();
      let message = $("input[name=message]").val();
      let _token   = $('meta[name="csrf-token"]').attr('content');

      $.ajax({
        url: "/contact",
        type:"POST",
        data:{
          name: name,
          email: email,
          mobile: mobile,
          message: message,
          _token: _token
        },
        success:function(response){
          console.log(response);
          if(response) {
            $('.success').text(response.success);
            $("#ajaxform")[0].reset();
          }
        },
        error: function(error) {
            $('#nameError').text(error.responseJSON.errors.name);
            $('#emailError').text(error.responseJSON.errors.email);
            $('#mobileError').text(error.responseJSON.errors.mobile);
            $('#messageError').text(error.responseJSON.errors.message);
        }
       });
  });
</script>

Thats it for now; the Laravel Ajax Request Tutorial is over. Now we have a basic understanding of ajax post request in Laravel application with jquery.

Leave a Comment