Uncategorized

Laravel 11 Ajax

Laravel 11 AJAX CRUD Example for Products

In this guide, you’ll learn how to build a Product Management System using Laravel 11, jQuery AJAX, and Bootstrap 5. This CRUD system includes fields like Product Name, Description, and Price.

1. Create Laravel Project

composer create-project laravel/laravel laravel11-ajax-crud

2. Configure Database

Edit your .env file:

DB_DATABASE=ajax_crud
DB_USERNAME=root
DB_PASSWORD=

3. Create Model and Migration

php artisan make:model Product -m

Edit the migration file:

<?php
public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description');
        $table->decimal('price', 8, 2);
        $table->timestamps();
    });
}

4. Define Routes

In routes/web.php:

use App\Http\Controllers\ProductController;

Route::get('/', [ProductController::class, 'index']);
Route::resource('products', ProductController::class)->except(['create', 'edit', 'show']);

5. Create ProductController

php artisan make:controller ProductController

Inside ProductController.php:

<?php
namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index()
    {
        return view('products.index');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required',
            'description' => 'required',
            'price' => 'required|numeric'
        ]);

        return response()->json(Product::create($data));
    }

    public function show(Product $product)
    {
        return response()->json($product);
    }

    public function update(Request $request, Product $product)
    {
        $data = $request->validate([
            'name' => 'required',
            'description' => 'required',
            'price' => 'required|numeric'
        ]);

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

    public function destroy(Product $product)
    {
        $product->delete();
        return response()->json(['success' => true]);
    }
}

6. Blade Layout (app.blade.php)

<!DOCTYPE html>
<html>
<head>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="container mt-5">
    @yield('content')
  </div>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  @yield('scripts')
</body>
</html>

7. Blade View (index.blade.php)

Here is the front-end form and product table:

<form id="productForm">
  <input type="hidden" id="product_id">
  <input type="text" id="name" placeholder="Product Name" class="form-control mb-2">
  <textarea id="description" placeholder="Description" class="form-control mb-2"></textarea>
  <input type="number" id="price" placeholder="Price" class="form-control mb-2">
  <button type="submit" class="btn btn-primary">Save</button>
  <button type="reset" class="btn btn-secondary" id="resetBtn">Reset</button>
</form>

<table class="table mt-4" id="productTable">
  <thead>
    <tr><th>ID</th><th>Name</th><th>Description</th><th>Price</th><th>Actions</th></tr>
  </thead>
  <tbody></tbody>
</table>

8. JavaScript AJAX Code

<script>
$(document).ready(function() {
  fetchProducts();

  function fetchProducts() {
    $.get("/products", function(data) {
      let rows = '';
      $.each(data, function(i, item) {
        rows += `
          <tr>
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${item.description}</td>
            <td>${item.price}</td>
            <td>
              <button class="btn btn-sm btn-warning editBtn" data-id="${item.id}">Edit</button>
              <button class="btn btn-sm btn-danger deleteBtn" data-id="${item.id}">Delete</button>
            </td>
          </tr>`;
      });
      $('#productTable tbody').html(rows);
    });
  }

  $('#productForm').submit(function(e) {
    e.preventDefault();
    let id = $('#product_id').val();
    let method = id ? 'PUT' : 'POST';
    let url = id ? `/products/${id}` : '/products';

    $.ajax({
      url: url,
      type: method,
      data: {
        _token: $('meta[name="csrf-token"]').attr('content'),
        name: $('#name').val(),
        description: $('#description').val(),
        price: $('#price').val()
      },
      success: function() {
        $('#productForm')[0].reset();
        $('#product_id').val('');
        fetchProducts();
      }
    });
  });

  $(document).on('click', '.editBtn', function() {
    let id = $(this).data('id');
    $.get(`/products/${id}`, function(product) {
      $('#product_id').val(product.id);
      $('#name').val(product.name);
      $('#description').val(product.description);
      $('#price').val(product.price);
    });
  });

  $(document).on('click', '.deleteBtn', function() {
    if (!confirm('Delete this product?')) return;
    let id = $(this).data('id');
    $.ajax({
      url: `/products/${id}`,
      type: 'DELETE',
      data: { _token: $('meta[name="csrf-token"]').attr('content') },
      success: fetchProducts
    });
  });
});
</script>

✅ Done!

This CRUD app is now ready! You can extend it with features like authentication, pagination, or file uploads.

Leave a Reply

Your email address will not be published. Required fields are marked *