PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 17, 2022

[FIXED] How to filter posts by using multiple category?

 January 17, 2022     eloquent, laravel, php     No comments   

Issue

I tried everywhere but I can't find any solution :( , I want to search posts by using the category checkbox for example, if the user checks the photography and drawing category it only shows posts that have $category_slug=photography OR $category_slug=drawing but it only works if I check one category type if I select multiple category types it doesn't return anything. Please help

blade

@if (isset($categories))
  @foreach ($categories as $category)
    <div class="list-group-item checkbox">
      <label>
        <input type="checkbox" class="common_selector category" name="cate[]" value="{{ $category->slug }}">
        {{$category->name }}
      </label>
    </div>
  @endforeach
@endif

Controller

public function search(Request $request)
{
    $categories = Category::all();

    $txtSearch = $request->input('q');
    if (isset($txtSearch)) {
        $query = Post::where('title', 'LIKE', "%$txtSearch%")->orderBy('id', 'DESC');
    } else {       
        $query = Post::orderBy('id', 'DESC');
        if ($request->has('cate')) {
            $categoryType = $request->input('cate');
            foreach ($categoryType as $category) {
                $query->where('category_slug', $category);
            }
        }
    }

    $queryResults = $query->paginate(20);

    return view('searchPage, ['categories' => $categories, 'queryResults' => $queryResults]);
}

I appreciate your help.


Solution

Basically you want to say that you want to find any posts that belong to any of the categories that are selected. You could use a where with orWheres in it in a loop or use whereIn. Here is an example using whereIn:

if ($request->has('cate')) {
    $query->whereIn('category_slug', (array) $request->input('cate', []));
}

If you validate that the input cate is an array you can drop the (array) cast from that and the second argument to input.

Laravel 8.x Docs - Query Builder - Additional Where Clauses whereIn



Answered By - lagbox
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing