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 >
<label>
<input type="checkbox" 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.
CodePudding user response:
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 orWhere
s 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