Insert Data using Ajax Request Example in Laravel 7

Hey Artian

In this tutorial we are going to learn how to insert data using ajax in laravel 7. We will insert our data into database without refreshing our web page. For doing it we will use ajax request.

In today's tutorial insert data using ajax in laravel 7 tutorial, you will learn it from scratch. If you don't know how to insert data using ajax in laravel with datatables then you are the right place.

In this tutorial i will discuss about ajax request. For doing ajax insert dara in laravel app , just follow the bellow instruction. So let's start insert data using ajax in laravel 7 tutorial.

I already made a tutorial Laravel 7 ajax form submit with jQuery validation. You can read it to learn jQuery ajax form validation before form submit. 

Read also : Laravel 6 Ajax Form Submit With jQuery Validation

ajax-insert-data-in-laravel

Lets start to complete it. Let's download a fresh laravel application.

Step 1: Install Laravel 7

First of all, we need to get fresh Laravel 7 version application using bellow command because we are going from scratch, So open your terminal OR command prompt and run bellow command:

 

Read Also What is CSRF Protection in Laravel

 

composer create-project --prefer-dist laravel/laravel blog

 

Step 2: Database Configuration

In this step, we need to add database configuration details on .env file. So let's create username, password etc. So let's add.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Ajax
DB_USERNAME=root
DB_PASSWORD=

 

After added database configuration , we need a table to insert our data into database.

 

Step 3: Create  database table

For creating database table with model , just run below command

php artisan make:model Post -m

 

here -m for creating migration to corresponding model . Hope you understand. after running this command we have posts table in our database/migrations folder. So open this posts table and paste below code to two table.

database/migrations

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('details');
            $table->timestamps();
        });
    }

   
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

 

Our table is completed. Run below command to migrate those table into our database.

 

php artisan migrate

 

Step 4 :  Setup route

Now time to setup our route. to create route just paste the following code.

routes/web.php

Route::get('postinsert', '[email protected]');
Route::post('postinsert', '[email protected]');

 

Now we need HomeController to insert our data. But no need to create HomeController, we will use laravel default HomeController

app/Http/Controllers/HomeController.php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class HomeController extends Controller
{

    // public function __construct()
    // {
    //     $this->middleware('auth');
    // }

    public function index()
    {
        return view('home');
    }

    public function ajaxRequest()
    {

        return view('welcome');
    }

    public function ajaxRequestPost(Request $request)
    {

        \DB::table('posts')->insert([
            'title' => $request->Code, //This Code coming from ajax request
            'details' => $request->Chief, //This Chief coming from ajax request
        ]);

        return response()->json(
            [
                'success' => true,
                'message' => 'Data inserted successfully'
            ]
        );
    }
}

 

Here $request->Code and $request->Chief data coming from ajax request. to understand , see below code.

 

Step 5 :  Create Blade File

Now we have to create our blade file to see insert form. But we will use laravel default welcome page. So open welcome page and paste the following code.

Here  e.preventDefault(); use to restrict page reload. You can catch all the data using jQuery serialize() method.

 $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $(".btn-submit").click(function(e){

        e.preventDefault();

        var data = $(this).serialize();
        console.log(data);
        var url = '{{ url('postinsert') }}';

        $.ajax({
           url:url,
           method:'POST',
           data:data,
           success:function(response){
              if(response.success){
                  alert(response.message) //Message come from controller
              }else{
                  alert("Error")
              }
           },
           error:function(error){
              console.log(error)
           }
        });
	});

 

Look this procedure we don't have below code

var title = $("input[name=title]").val();
var details = $("input[name=details]").val();

data:{
       Code:title, 
       Chief:details
 },

 

So if you use this procedure we can insert data using below method,

\DB::table('posts')->insert([
     'title' => $request->input('title'), //$request->title
     'details' => $request->input('details'), //$request->details
]);
return response()->json(
     [
       'success' => true,
       'message' => 'Data inserted successfully'
     ]
);

 

Read also : Laravel 6 Ajax CRUD Example with Sweet Alert

 

Hope it will help you.