Laravel 11 Ajax Post Request Example

Using this Laravel Ajax Post Request Example you will learn how to use ajax request in the Laravel 11 application to save or submit data to the database. Ajax post or get request is the primary requirement of all admin backend or frontend applications.

Using this Laravel AJAX request we submit data in the database using the post request with validation error messages or success messages from the backend and show them in the front.

How to Send Ajax Request in Laravel 11

An AJAX request is a request made by an AJAX application. Typically, it is an HTTP request made by (browser-resident) Javascript that uses XML to encode the request data and/or response data. Follow the following steps to implement how to send the Ajax Request in Laravel.

  • Download Laravel App
  • Setup Database Credentials
  • Make Model and Migration
  • Make Routes
  • Create Controller
  • Create Blade File
  • Send Ajax Request

#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

#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

#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 which will show your database table after running the migration command.

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->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', 'message'
];
}

#4 Add Routes

Now, open the routes/web.php file and add two routes for implementing the Laravel ajax post request. 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('contacts', [ ContactController::class, 'create' ]);
Route::post('contacts', [ ContactController::class, 'store' ]);


Route::get('/', function () {
    return view('welcome');
});

#5 Create New Controller

Now, create a new controller in your application using the following command in your terminal.

php artisan make:controller ContactController

After getting the new controller, open the app/Http/Controllers/ContactController.php file and update the below code on it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contact;

class ContactController extends Controller
{
    public function create()
    {

      return view('contacts');
    }

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

        Contact::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'mobile'   => $request->mobile,
            'message'  => $request->message,
        ]);

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

#6 Create Blade File

Next, create a new blade file named contacts.blade.php, which shows the form where we send the ajax request for showing form validations and etc functionalities. So, open the resources\views\contacts.blade.php file and update the below code on it

<!DOCTYPE html>
<html>
<head>
    <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 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 id="contact-form">
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="name" class="form-control" placeholder="Enter Name">
                <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">
                <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">
                <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">
                <span class="text-danger" id="messageError"></span>
            </div>
            <div class="form-group">
                <button class="btn btn-success save-data">Save</button>
            </div>
        </form>
    </div>
</body>
</html>

#7 Send Ajax Request

After creating 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. Here we are using the jQuery submit function and use the CSRF for send request.

<script>

  $('#contact-form').on('submit', function(event){
      event.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: "/contacts",
        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);
            $("#contact-form")[0].reset();
          }
        },
        error: function(error) {
         console.log(error);
          $('#nameError').text(response.responseJSON.errors.name);
          $('#emailError').text(response.responseJSON.errors.email);
          $('#mobileError').text(response.responseJSON.errors.mobile);
          $('#messageError').text(response.responseJSON.errors.message);
        }
       });
  });
</script>

Conclusion:

Great! So the Laravel Ajax post request example tutorial is completed now. I hope this is work for you. You can use this example of Ajax post request in

  • Laravel 8
  • Laravel 9
  • Laravel 10

Leave a Comment