Laravel Ajax CRUD Tutorial with Example for Bigginers

If you are looking Laravel Ajax crud operation then you land a perfect place. In this guide, we’ll explore how to implement CRUD (Create, Read, Update, Delete) operations using Laravel and AJAX. We’ll cover the necessary steps to set up your Laravel project and how to implement Laravel AJAX CRUD operations.

Step 1: Download Laravel App

To get started, make sure you have Laravel app installed on your local machine. If not install a fresh laravel app using the following command.

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

Next, go into your installed app directory:

cd laravel-ajax-crud

Step 2: Configure Database Credentials

Next, configure your database connection in the .env file with the appropriate credentials for your environment. Create a new database for your project, if you haven’t already.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=#db_name
DB_USERNAME=#db_username
DB_PASSWORD=#db_password

Step 3: Generate Model and Migration

To create a model and migration for your CRUD operations, use the following Artisan command.

php artisan make:model Product -m

Next opent the database\migrations\2023_04_06_061025_create_products_table.php file and update the below code on it.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('sku');
            $table->string('amount');
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

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

Now, run the migrate command to generate the table in the database.

php artisan migrate

Now open your model app\Models\Product.php and add the fallible properties same as below.

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    public $fillable = ['title', 'sku', 'amount', 'description'];
}

Step 4: Create Routes

In the routes/web.php file, define the routes for your CRUD operations.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::resource('products', ProductController::class);


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

Step 5: Create Controller for Laravel Ajax CRUD

Now create a new controller as ProductController just running the below command.

php artisan make:controller ProductController --resource

After successfully creating the controller, now open the app/Http/Controllers/ProductController.php file and put the methods on it.

<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $products = Product::orderBy('id','desc')->paginate(10);

        if ($request->ajax()) {
            return response()->json([
                'html' => view('product-list', compact('products'))->render()
            ]);
        }

        return view('products', compact('products'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|max:255',
            'sku' => 'required',
            'amount' => 'required',
        ]);
 
        $products = Product::updateOrCreate(['id' => $request->id], [
            'title' => $request->title,
            'sku' => $request->sku,
            'amount' => $request->amount,
            'description' => $request->description
        ]);
 
        return response()->json(['code'=>200, 'message'=> 'Product Created successfully', 'data' => $products], 200);
    }

    public function show(string $id)
    {
        $product = Product::find($id);

        return response()->json($product);
    }

    public function edit(string $id)
    {
        $product = Product::find($id);

        return response()->json($product);
    }

    public function destroy(string $id)
    {
        $product = Product::find($id)->delete();

        return response()->json($product);
    }
}

Step 6: Create Blade Files

In this step create a products.blade.php blade file in your resources/views directory and then open the resources\views\products.blade.php file and update the below code on it.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdn.datatables.net/r/bs-3.3.5/jq-2.1.4,dt-1.10.8/datatables.min.css"/>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script>
</head>
  <style>
  .alert-message {
    color: red;
  }
</style>
<body>
    <div class="container">
        <h2 style="margin-top: 12px;" class="alert alert-success">Ajax CRUD with Laravel App</h2><br>
        <div class="row">
            <div class="col-12 text-right">
                <a href="javascript:void(0)" class="btn btn-success mb-3" id="create-new-product" onclick="addProduct()">Add Product</a>
            </div>
        </div>
        <div id="product-list" class="row" style="clear: both;margin-top: 18px;">
            @include('product-list', $products);
        </div>
        
        // bootstrap modal code update here 

    </div>

  //add javascript code here 
</body>
</html>

Next, create another file named as product-list.blade.php in your routes/views directory. This will be shown in the ajax render case when you create or update data this page will show the list of products.

So, open the resources\views\product-list.blade.php file and update the below code on it.

<divclass="col-12">
    <tableid="laravel-ajax-crud"class="table table-striped table-bordered">
        <thead>
            <tr>
                <th>Title</th>
                <th>Sku</th>
                <th>Amount</th>
                <th>Description</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($products as $product)
                <trid="row_{{$product->id}}">
                <td>{{ $product->title }}</td>
                <td>{{ $product->sku }}</td>
                <td>{{ $product->amount }}</td>
                <td>{{ $product->description }}</td>
                <td>
                    <ahref="javascript:void(0)"data-id="{{ $product->id }}"onclick="editProduct(event.target)"class="btn btn-info">Edit</a>
                    <ahref="javascript:void(0)"data-id="{{ $product->id }}"class="btn btn-danger"onclick="deleteProduct(event.target)">Delete</a>
                <td>
                </tr>
            @endforeach
        </tbody>
    </table>
</div>

Step 7: Add Bootstrap Modal

After adding the posts blade file, now add the bootstrap model code in your “products.blade.php” after the last closing div.

<div class="modal fade" id="product-modal" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">Add/Edit Product</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"  onclick="closeModal()">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
                <form name="userForm" class="form-horizontal">
                <input type="hidden" name="product_id" id="product_id">
                    <div class="form-group">
                        <label for="name" class="col-sm-2">title</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="title" name="title" placeholder="Add title">
                            <span id="titleError" class="alert-message"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="sku" class="col-sm-2">SKU</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="sku" name="sku" placeholder="Add sku">
                            <span id="skuError" class="alert-message"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="amount" class="col-sm-2">Amount</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="amount" name="amount" placeholder="Add amount">
                            <span id="amountError" class="alert-message"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2">Description</label>
                        <div class="col-sm-12">
                            <textarea class="form-control" id="description" name="description" placeholder="Add description" rows="4" cols="50"></textarea>
                            <span id="descriptionError" class="alert-message"></span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" onclick="closeModal()">Close</button>
                <button type="button" class="btn btn-primary" onclick="createProduct()">Save</button>
            </div>
        </div>
    </div>
</div>

Step 8: Add JS code and send Ajax request

Now add jquery and Ajax code in your “products.blade.php” file after closing in the body tag for Laravel Ajax crud operation.

<script>
    $('#laravel-ajax-crud').DataTable();

    function addProduct() {
      $("#product_id").val('');
      $('#product-modal').modal('show');
    }

    function editProduct(event) {
      let id  = $(event).data("id");

      $('#titleError').text('');
      $('#skuError').text('');
      $('#amountError').text('');
      $('#descriptionError').text('');

      $.ajax({
        url: `/products/${id}`,
        type: "GET",
        success: function(response) {
          if (response) {
              $("#product_id").val(response.id);
              $("#title").val(response.title);
              $("#sku").val(response.sku);
              $("#amount").val(response.amount);
              $("#description").val(response.description);
              $('#product-modal').modal('show');
          }
        }
      });
    }

    function createProduct() {
      let title = $('#title').val();
      let sku = $('#sku').val();
      let amount = $('#amount').val();
      let description = $('#description').val();
      let id = $('#product_id').val();

      $.ajax({
          url: `/products`,
          type: "POST",
          data: {
            id: id,
            title: title,
            sku: sku,
            amount: amount,
            description: description,
            _token: $('meta[name="csrf-token"]').attr('content')
          },
          success: function(response) {
              if (response.code == 200) {
                getProducts();
                closeModal();
            }
          },
          error: function(response) {
            $('#titleError').text(response.responseJSON.errors.title);
            $('#skuError').text(response.responseJSON.errors.sku);
            $('#amountError').text(response.responseJSON.errors.amount);
            $('#descriptionError').text(response.responseJSON.errors.description);
          }
        });
    }

    function getProducts() {
      $.ajax({
        url: `/products`,
        type: "GET",
        success: function(response) {
          console.log(response);
          $("#product-list").html(response.html);
        }
      });
    }

    function deleteProduct(event) {
      let id = $(event).data("id");

      $.ajax({
          url: `/products/${id}`,
          type: 'DELETE',
          data: {
            _token: $('meta[name="csrf-token"]').attr('content')
          },
          success: function(response) {
            $("#row_"+id).remove();
          }
        });
    }

    function closeModal() {
      $('#title').val('');
      $('#sku').val('');
      $('#amount').val('');
      $('#description').val('');
      $('#product-modal').modal('hide');
    }

  </script>

See Also: Laravel Datatables Example with AJAX Search and Sort

So your products.blade.php file full code looks like this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdn.datatables.net/r/bs-3.3.5/jq-2.1.4,dt-1.10.8/datatables.min.css"/>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script>
</head>
  <style>
  .alert-message {
    color: red;
  }
</style>
<body>
    <div class="container">
        <h2 style="margin-top: 12px;" class="alert alert-success">Ajax CRUD with Laravel App</h2><br>
        <div class="row">
            <div class="col-12 text-right">
                <a href="javascript:void(0)" class="btn btn-success mb-3" id="create-new-product" onclick="addProduct()">Add Product</a>
            </div>
        </div>
        <div id="product-list" class="row" style="clear: both;margin-top: 18px;">
            @include('product-list', $products);
        </div>

        <div class="modal fade" id="product-modal" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                      <h5 class="modal-title">Add/Edit Product</h5>
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close"  onclick="closeModal()">
                        <span aria-hidden="true">&times;</span>
                      </button>
                    </div>
                    <div class="modal-body">
                        <form name="userForm" class="form-horizontal">
                        <input type="hidden" name="product_id" id="product_id">
                            <div class="form-group">
                                <label for="name" class="col-sm-2">title</label>
                                <div class="col-sm-12">
                                    <input type="text" class="form-control" id="title" name="title" placeholder="Add title">
                                    <span id="titleError" class="alert-message"></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="sku" class="col-sm-2">SKU</label>
                                <div class="col-sm-12">
                                    <input type="text" class="form-control" id="sku" name="sku" placeholder="Add sku">
                                    <span id="skuError" class="alert-message"></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="amount" class="col-sm-2">Amount</label>
                                <div class="col-sm-12">
                                    <input type="text" class="form-control" id="amount" name="amount" placeholder="Add amount">
                                    <span id="amountError" class="alert-message"></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2">Description</label>
                                <div class="col-sm-12">
                                    <textarea class="form-control" id="description" name="description" placeholder="Add description" rows="4" cols="50"></textarea>
                                    <span id="descriptionError" class="alert-message"></span>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" onclick="closeModal()">Close</button>
                        <button type="button" class="btn btn-primary" onclick="createProduct()">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
  <script>
    $('#laravel-ajax-crud').DataTable();

    function addProduct() {
      $("#product_id").val('');
      $('#product-modal').modal('show');
    }

    function editProduct(event) {
      let id  = $(event).data("id");

      $('#titleError').text('');
      $('#skuError').text('');
      $('#amountError').text('');
      $('#descriptionError').text('');

      $.ajax({
        url: `/products/${id}`,
        type: "GET",
        success: function(response) {
          if (response) {
              $("#product_id").val(response.id);
              $("#title").val(response.title);
              $("#sku").val(response.sku);
              $("#amount").val(response.amount);
              $("#description").val(response.description);
              $('#product-modal').modal('show');
          }
        }
      });
    }

    function createProduct() {
      let title = $('#title').val();
      let sku = $('#sku').val();
      let amount = $('#amount').val();
      let description = $('#description').val();
      let id = $('#product_id').val();

      $.ajax({
          url: `/products`,
          type: "POST",
          data: {
            id: id,
            title: title,
            sku: sku,
            amount: amount,
            description: description,
            _token: $('meta[name="csrf-token"]').attr('content')
          },
          success: function(response) {
              if (response.code == 200) {
                getProducts();
                closeModal();
            }
          },
          error: function(response) {
            $('#titleError').text(response.responseJSON.errors.title);
            $('#skuError').text(response.responseJSON.errors.sku);
            $('#amountError').text(response.responseJSON.errors.amount);
            $('#descriptionError').text(response.responseJSON.errors.description);
          }
        });
    }

    function getProducts() {
      $.ajax({
        url: `/products`,
        type: "GET",
        success: function(response) {
          console.log(response);
          $("#product-list").html(response.html);
        }
      });
    }

    function deleteProduct(event) {
      let id = $(event).data("id");

      $.ajax({
          url: `/products/${id}`,
          type: 'DELETE',
          data: {
            _token: $('meta[name="csrf-token"]').attr('content')
          },
          success: function(response) {
            $("#row_"+id).remove();
          }
        });
    }

    function closeModal() {
      $('#title').val('');
      $('#sku').val('');
      $('#amount').val('');
      $('#description').val('');
      $('#product-modal').modal('hide');
    }

  </script>
</body>
</html>

Step 9: Start your app

In the last step, open the command prompt and run the following command to start the development server:

php artisan serve

Then open your browser and hit the following URL on it:

https://localhost:8000/products

6 thoughts on “Laravel Ajax CRUD Tutorial with Example for Bigginers”

  1. A o A
    sir,
    you prepared a great tutorial of ajax
    but Problem is that it is not work on insert data and update and delete
    only fetch data
    and generate no error

    Reply

Leave a Comment