How to Add Records by Sending Ajax Request in Laravel?

Ajax is a very important method in jQuery when it comes to changing view without refreshing. Laravel provides us out of the box Ajax input validation mechanism which filters input and sends appropriate error messages on runtime. It is super easy to implement. So, let’s start

1. Installing Laravel

First we need to install Laravel 8 by running this command.

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

2. Database Configuration

In order to configure the database we need to add these credentials in my .env file.

  • Database name
  • Database password
  • Database username
  • Database host

In order to do so, we will add the following lines in the .env file.


3. Creating model and migration

First we will create a model and migration by running this command in our shop-app project which we have just created.

php artisan make:model Product -m

-m will create a migration file in your migration folder.

After running that command we will add this code in the migration file mentioned below. (Name of the file will be unique for everyone but location will be same).



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

class CreateProductsTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('products', function (Blueprint $table) {

     * Reverse the migrations.
     * @return void
    public function down()

Then we will run following command for migration. It will create products table in the database.

php artisan migrate

Then we will have to add following code in our Image Model. app/Product.php


namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
	protected $fillable = [

4. Adding Routes

We will add 2 routes in our “routes/web.php” file. One to show products and other to send Ajax request to add Product.

Route::get('products', '[email protected]')->name('products');
Route::post('store-product', '[email protected]')->name('');

5. Creating Controller

Then we will create ProductsController by running following Laravel command in our terminal.

php artisan make:controller ProductsController

Then we will add following code to ImagesController. app/Http/Controllers/ProductsController.php 


namespace App\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;

class ProductsController extends Controller {
	public function ajaxRequest() {
		return view( 'products.index' );

	public function ajaxRequestStore( Request $request ) {
		$validator = Validator::make( $request->all(), [
			'name'  => 'required',
			'price' => 'required|numeric'
		] );

		if ( $validator->passes() ) {
			Product::create( $request->all() );

			return response()->json( [ 'success' => 'Added new product.' ] );

		return response()->json( [ 'error' => $validator->errors() ] );

6. Creating View

Then we will add following code in our view file to show and upload products. resources/views/products/index.blade.php

<!DOCTYPE html>
<html lang="en">
<title>Adding Products using Ajax Request -</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<script src=""></script>
<script src=""></script>
<script src=""></script>
<style type="text/css">
    body {
        background: #f2f2f2;

    .section {
        padding: 50px;
        background: #fff;
<div class="container" style="margin-top: 100px;">
    <div class="row">
        <div class="offset-md-3 col-md-6 section">
            <h2>Adding Products using Ajax Request -</h2>
            <div class="alert alert-success alert-block" style="display: none;">
                <button type="button" class="close" data-dismiss="alert">×</button>
                <strong class="success-msg"></strong>
                <div class="form-group">
                    <label for="pwd">Name:</label>
                    <input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
                    <span class="text-danger error-text name_err"></span>
                <div class="form-group">
                    <label for="pwd">Price:</label>
                    <input type="text" class="form-control" id="price" placeholder="Enter price" name="price">
                    <span class="text-danger error-text price_err"></span>
                <div class="form-group">
                    <label for="address">Description:</label>
                    <textarea class="form-control" name="description" id="description"
                    <span class="text-danger error-text description_err"></span>
                <button type="submit" class="btn btn-primary btn-submit">Submit</button>
<script type="text/javascript">
    $(document).ready(function () {
        $(".btn-submit").click(function (e) {

            var _token = $("input[name='_token']").val();
            var name = $("#name").val();
            var price = $("#price").val();
            var description = $("#description").val();

                url: "{{ route('') }}",
                type: 'POST',
                data: {_token: _token, name: name, price: price, description: description},
                success: function (data) {
                    $('.alert-block').css('display', 'block').append('<strong>' + data.success + '</strong>');
                error: function (data) {
                    let errors = data.responseJSON.errors;
                    $.each(errors, function (key, value) {
                        $('.' + key + '_err').text(value);

Now run the following command to serve Laravel site. 

php artisan serve

Here is how it will appear in your browser.