Filter products or data using ajax in laravel 11
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use App\Models\ProductsTwo;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function filterProduct(Request $request)
{
$query = ProductsTwo::query();
$categories = Category::all();
if ($request->ajax()) {
if (empty($request->category)) {
$products = $query->get();
} else {
$products = $query->where(["category_id" => $request->category])->get();
}
return response()->json(["products" => $products]);
}
$products = $query->get();
return view("product", compact("products", "categories"));
}
}
Above File is app\Http\Controllers\ProductController.php FileBelow File is app\Models\Category.php File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public $timestamps = true;
protected $table = "categories";
protected $fillable = ["name"];
}
Below File is app\Models\ProductsTwo.php File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProductsTwo extends Model
{
public $timestamps = true;
protected $table = "productstwo";
protected $fillable = ["name", "price", "description", "category_id"];
}
Below File is database\json\categories.php File
[
{
"name": "Shoes"
},
{
"name": "Clothes"
},
{
"name": "Sports"
}
]
Below File is database\json\productstwo.json File
[
{
"name": "Athletic shoes",
"price": 2500,
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"category_id": 1
},
{
"name": "Ballet flats",
"price": 3000,
"description": "sed do eiusmod tempor incididunt ut labore et",
"category_id": 1
},
{
"name": "Business attire",
"price": 1500,
"description": "dolore magna aliqua. Ut enim ad minim veniam",
"category_id": 2
},
{
"name": "Casual wear",
"price": 2500,
"description": "quis nostrud exercitation ullamco laboris nisi ut",
"category_id": 2
},
{
"name": "Lingerie",
"price": 3500,
"description": "aliquip ex ea commodo consequat",
"category_id": 2
},
{
"name": "Womenswear",
"price": 2400,
"description": "Duis aute irure dolor in reprehenderit in voluptate velit",
"category_id": 2
},
{
"name": "Brogue shoes",
"price": 5000,
"description": "esse cillum dolore eu fugiat nulla pariatur",
"category_id": 1
},
{
"name": "Basketball",
"price": 6000,
"description": "Excepteur sint occaecat cupidatat non",
"category_id": 3
},
{
"name": "Badminton",
"price": 3000,
"description": "proident, sunt in culpa qui officia",
"category_id": 3
},
{
"name": "Bodybuilding",
"price": 10000,
"description": "deserunt mollit anim id est laborum.",
"category_id": 3
},
{
"name": "Bat & Ball",
"price": 2300,
"description": "Sed ut perspiciatis unde omnis iste natus error sit",
"category_id": 3
}
]
Below File is database\migrations\2025_01_03_092442_create_categories_table File
<?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('categories', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('categories');
}
};
Below File is database\migrations\2025_01_03_092730_create_productstwo_table File
<?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('productstwo', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->integer("price");
$table->longText("description");
$table->unsignedBigInteger("category_id");
$table->foreign("category_id")->references("id")->on("productstwo")->onUpdate("cascade")->onDelete("cascade");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('productstwo');
}
};
Below File is database\seeders\CategorySeeder.php File
<?php
namespace Database\Seeders;
use App\Models\Category;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class CategorySeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database\json\categories.json");
$categories = collect(json_decode($json));
$categories->each(function ($categories) {
Category::create([
"name" => $categories->name
]);
});
}
}
Below File is database\seeders\DatabaseSeeder.php File
<?php
namespace Database\Seeders;
use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
// User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
$this->call([
ProductsTwoSeeder::class,
CategorySeeder::class
]);
}
}
Below File is database\seeders\ProductsTwoSeeder.php File
<?php
namespace Database\Seeders;
use App\Models\ProductsTwo;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class ProductsTwoSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database/json/productstwo.json");
$productstwo = collect(json_decode($json));
$productstwo->each(function ($productstwo) {
ProductsTwo::create([
"name" => $productstwo->name,
"price" => $productstwo->price,
"description" => $productstwo->description,
"category_id" => $productstwo->category_id
]);
});
}
}
Below File is resources\views\product.blade.php File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Product</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-10">
<div class="card">
<div class="card-header">
<h4>Categories</h4>
</div>
<div class="card-body">
<select name="category" id="category">
<option value="">Select Category</option>
@if(count($categories) > 0)
@foreach($categories as $category)
<option value="{{ $category['id'] }}">{{ $category->name }}</option>
@endforeach
@endif
</select><br><br>
<table class="table table-bordered table-striped table-hovered">
<thead>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th>Category ID</th>
</thead>
<tbody id="tbody">
@if(count($products) > 0)
@foreach($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->price }}</td>
<td>{{ $product->description }}</td>
<td>{{ $product->category_id }}</td>
</tr>
@endforeach
@endif
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#category").on("change",function(){
var category = $(this).val();
$.ajax({
url:"{{ route('filter') }}",
type:"GET",
data:{"category":category},
success:function(data){
var products = data.products;
var html = "";
if(products.length > 0) {
for(let i=0;i<products.length;i++) {
html += '<tr>\
<td>'+products[i]["id"]+'</td>\
<td>'+products[i]["name"]+'</td>\
<td>'+products[i]["price"]+'</td>\
<td>'+products[i]["description"]+'</td>\
<td>'+products[i]["category_id"]+'</td>\
</tr>';
}
} else {
html += '<tr>\
<td>No products found</td>\
</tr>';
}
$("#tbody").html(html);
}
});
});
});
</script>
</body>
</html>
Below File is routes\web.php File
.png)
.png)
.png)
.png)
.png)
.png)
Comments
Post a Comment