Indexeddb Crud With Laravel And Jquery Step By Step Guide With Code Explanation

image
image
image
image
image
image
image
image
IndexedDB CRUD with Laravel and jQuery (Step-by-Step Guide with Code Explanation)

IndexedDB CRUD with Laravel and jQuery (Step-by-Step Guide with Code Explanation)

In modern web apps, offline-first functionality is becoming essential. IndexedDB allows you to store significant data on the client side, enabling offline access and faster read/write operations.

In this tutorial, you will learn:

βœ… What IndexedDB is

βœ… How to perform CRUD operations using jQuery

βœ… A clear explanation of key code snippets

βœ… Integration with Laravel Blade for frontend rendering

πŸš€ What is IndexedDB?

IndexedDB is a low-level, asynchronous, client-side storage API that allows you to store structured data in the browser, including files/blobs. It is ideal for:

  1. Offline apps
  2. PWAs (Progressive Web Apps)
  3. Apps requiring fast local data access

🧱 Step 1. Create Laravel Project

composer create-project laravel/laravel indexeddb-crud
cd indexeddb-crud
php artisan serve

✨ Step 2. Create Blade View

In resources/views/index.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>IndexedDB CRUD with Laravel and jQuery</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
<div class="card shadow-sm">
<div class="card-header bg-primary text-white">
<h4>IndexedDB CRUD Example</h4>
</div>
<div class="card-body">
<form id="addForm" class="row g-3">
<div class="col-md-5">
<input type="text" id="name" class="form-control" placeholder="Product Name" required>
</div>
<div class="col-md-5">
<input type="number" id="price" class="form-control" placeholder="Price" required>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-success w-100">Add</button>
</div>
</form>
<ul id="productList" class="list-group mt-4"></ul>
</div>
</div>
</div>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let db;
let request = indexedDB.open("ProductDB", 1);

request.onerror = function(event) {
console.log("Error opening DB", event);
};

request.onupgradeneeded = function(event) {
db = event.target.result;
let objectStore = db.createObjectStore("products", { keyPath: "id", autoIncrement: true });
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("price", "price", { unique: false });
console.log("DB setup complete");
};

request.onsuccess = function(event) {
db = event.target.result;
console.log("DB opened");
displayData();
};

$('#addForm').on('submit', function(e) {
e.preventDefault();
let name = $('#name').val();
let price = parseFloat($('#price').val());

// πŸ”₯ KEY CODE EXPLAINED BELOW πŸ”₯
let transaction = db.transaction(["products"], "readwrite");
let store = transaction.objectStore("products");
let product = { name: name, price: price };
let addRequest = store.add(product);

addRequest.onsuccess = function() {
$('#name').val('');
$('#price').val('');
displayData();
};
});

function displayData() {
$('#productList').empty();
let transaction = db.transaction(["products"], "readonly");
let store = transaction.objectStore("products");
let request = store.openCursor();

request.onsuccess = function(event) {
let cursor = event.target.result;
if (cursor) {
$('#productList').append(
`<li class="list-group-item d-flex justify-content-between align-items-center">
${cursor.value.name} - β‚Ή${cursor.value.price}
<button class="btn btn-sm btn-danger" onclick="deleteProduct(${cursor.value.id})">Delete</button>
</li>`
);
cursor.continue();
}
};
}

function deleteProduct(id) {
let transaction = db.transaction(["products"], "readwrite");
let store = transaction.objectStore("products");
store.delete(id).onsuccess = function() {
displayData();
};
}
</script>
</body>
</html>

πŸ“ Step 3. Define Route

In routes/web.php:

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

πŸ” Code Explanation

βœ… 1. Creating a Transaction

let transaction = db.transaction(["products"], "readwrite");
  1. What it does: Starts a transaction targeting the "products" object store with "readwrite" mode.
  2. Why: You need a transaction to perform read or write operations safely.

βœ… 2. Accessing the Object Store

let store = transaction.objectStore("products");
  1. What it does: Retrieves the products object store from the transaction.
  2. Why: It’s like selecting a table in SQL before running queries.

βœ… 3. Adding Data to IndexedDB

let product = { name: name, price: price };
let addRequest = store.add(product);
  1. What it does: Creates a product object and uses store.add() to insert it into the database.
  2. Why: Adds a new record to IndexedDB. The addRequest allows attaching onsuccess or onerror handlers.

⚑ Final Output

βœ… User can add products with name and price

βœ… Data is stored locally in IndexedDB (persists after page reload)

βœ… Products displayed with delete functionality

πŸ’‘ Why Use IndexedDB?

  1. Offline-first applications
  2. Quick local reads/writes
  3. Sync data later to Laravel backend if needed


πŸ”— GitHub Repository

You can find the full source code for this tutorial on GitHub:

➑️ https://github.com/codehunger-team/crud-using-indexed-db-php-laravel

🎯 Explore the Repository

βœ… Clone the project

βœ… Run it locally

βœ… Customize for your offline-first applications