Skip to content
Advertisement

Category filtering in Laravel

Hey guys I’m currently trying to resolve why my legacy code doesn’t work the way it was intended to do so. It’s a basic category filter. My current problem is that I don’t really know what to fix.

I tried changing up whereHas, whereIn, orWhere query statement. When I changed orWhere to just simply where, the filter worked only if one category was selected.

If anyone has any ideas to fix my problem, help would be gladly appreciated.

My code is below :

Backend(InternController.php) :

$intern = Intern::query()->with('category');
if ($request->categories) {
    $intern->whereHas('category', function ($query) use ($intern, $request) {
        foreach ($request->categories as $category) {
            $query->orWhere('category_id', $category);
        }
        $query->whereIn('category_id', $request->categories);
    });
}
$intern = $intern->get();
$categories = Category::all();
$category_intern = CategoryIntern::all();
return view('intern')->with($viewData)->with([
    'intern' => $intern,
    'categories' => $categories,
    'category_intern' => $category_intern,
]);

Frontend(intern.blade.php):

 <form method="GET">
    <div class="mx-4">
        <label for="select2Multiple" class="h3 pt-5 ml-auto">
        Categories
        </label>
        <div class="row">
            <div class="col-xl-2 mt-xl-1">
                <select
                    class="select2-multiple form-control"
                    style="min-height: 70px"
                    name="categories[]"
                    multiple="multiple"
                    id="select2Multiple"
                    >
                @foreach($categories as $category)
                <option
                value="{{ $category->id }}" {{ collect(request()->categories)->contains($category->id) ? "selected": ''}}>
                {{ $category->name }}
                </option>
                @endforeach
                </select>
            </div>
            <div class="col-xl-2">
                <button type="submit"
                    class="btn btn-primary btn-sm text-uppercase font-semibold mt-1 "
                    style="background-color: #0d5eff; min-height: 32px"
                    >Choose category
                </button>
            </div>
        </div>
    </div>
</form>

Advertisement

Answer

Fixed, finally.

Deleted the foreach statement in the whereHas body.

final code looks like this

$intern = Intern::query()->with('category');
        if ($request->categories) {
            $intern->whereHas('category', function ($query) use ($intern, $request) {
                $query->whereIn('category_id', $request->categories);
            });
        }
        $intern = $intern->get();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement