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.

DB_HOST=localhost 
DB_DATABASE=shop_app_db 
DB_USERNAME=root 
DB_PASSWORD=secret

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).

/database/migrations/2021_01_01_122345_create_products_table.php

<?php

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) {
            $table->id();
            $table->string('name');
            $table->integer('price');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
	protected $fillable = [
		'name','price','description' 
	];
}

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('product.store');

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 

<?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">
<head>
<title>Adding Products using Ajax Request - Laramatic.com</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<style type="text/css">
    body {
        background: #f2f2f2;
    }

    .section {
        padding: 50px;
        background: #fff;
    }
</style>
</head>
<body>
<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 - Laramatic.com</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>
            <form>
                @csrf
                <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>
                <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>
                <div class="form-group">
                    <label for="address">Description:</label>
                    <textarea class="form-control" name="description" id="description"
                              placeholder="Description"></textarea>
                    <span class="text-danger error-text description_err"></span>
                </div>
                <button type="submit" class="btn btn-primary btn-submit">Submit</button>
            </form>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $(".btn-submit").click(function (e) {
            e.preventDefault();

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

            $.ajax({
                url: "{{ route('product.store') }}",
                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);
                    });
                }
            });
        });
    });
</script>
</body>
</html>

Now run the following command to serve Laravel site. 

php artisan serve

Here is how it will appear in your browser.