简体   繁体   中英

How to filter products checkbox with Ajax Laravel?

I have seen many e-commerce sites in which users can filter products by clicking checkboxes. for example: let's say there are different brands of mobile: like Samsung, Nokia, Company, Company, etc. Different colors, sizes, memory.

When the user checks the Samsung checkbox pages display only Samsung mobile when the user further checks the 8Gb memory checkbox, the page display Samsung mobile with 8Gb memory and so on.

I want to implement such a feature with jQuery/Ajax and Laravel. Can you give me an idea of how this is done?

I have three tables, courses and categories and category_course .

categories table

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->string('title');
        $table->string('slug');
        $table->string('icon')->nullable();
        $table->timestamps();
    });
}

courses table

public function up()
{
    Schema::create('courses', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->string('title');
        $table->string('slug');
        $table->string('image');
        $table->string('price');
        $table->string('time');
        $table->text('body');
        $table->timestamps();
    });

    Schema::create('category_course', function (Blueprint $table) {
        $table->foreignId('category_id')->constrained()->cascadeOnDelete();
        $table->foreignId('course_id')->constrained()->cascadeOnDelete();
        $table->primary(['category_id', 'course_id']);
    });
}

ExploreController.php

<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Course;

class ExploreController extends Controller
{
    public function index()
    {
        $categories = Category::all();
        $courses = Course::query()->latest()->paginate(20);
        return view('Home.pages.explore', compact('courses', 'categories'));
    }

    public function show($id)
    {
        $data = Course::query()->selectRaw('SELECT * FROM categories')->whereRaw('category_id IN ('.$id.')' )->get();
        echo json_encode($data);
    }
}

explore.blade.php

@foreach($categories as $category)
    <div class="form-check">
        <input class="form-check-input" onclick="categoryCheckbox({{ $category->id }})" type="checkbox" value="" id="cat_{{ $category->id }}">
        <label class="form-check-label" for="cat_{{ $category->id }}">
            {{ $category->title }}
        </label>
    </div>
@endforeach

@push('script')
    <script>
        function categoryCheckbox(id) {
            $('.courseFilters').empty();
            $.ajax({
                type: 'GET',
                url: 'getCategoryCourse/' + id,
                success: function(response) {
                    console.log(response);
                },
            });
        }
    </script>
@endpush

web.php

Route::get('/explore', [App\Http\Controllers\ExploreController::class, 'index'])->name('explore');
Route::get('/getCategoryCourse/{id}', [App\Http\Controllers\ExploreController::class, 'show']);

Course.php

public function categories()
{
    return $this->belongsToMany(Category::class);
}

Category.php

public function courses()
{
    return $this->belongsToMany(Course::class);
}

First of all there is a problem with your code cause your sending just single category_id to the server so user can only select one category. For your purpose you must always pass all the data. Lets say you have passed all the selected categories to API. Now you can filter results using method below:

$categories = [...];
Course::whereHas('categories' => function($q) use ($categories) {
    $q->wherePivotIn('category_id', $categories);
})->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM