query scope is not working, i'm doing dd()
but can't solve the issue this way
queryscope method in model
public function scopeFilter($query, array $filters)
{
$query->when($filters['search'] ?? false, fn($query, $search) => $query
->where('title', 'like', '%' . $search . '%')
->orWhere('body', 'like', '%' . $search . '%')
);
$query->when($filters['category'] ?? false, fn($query, $category) => $query
->whereExists(fn($query) => $query
->from('categories')
->whereColumn('categories.id', 'posts.category_id')
->where('category.slug', $category)
)
);
}
index (show all posts with filter) method in controller
public function index()
{
return view('posts', [
'posts' => Post::latest()->filter(request(['search', 'category']))->get(),
'categories' => Category::all()
]);
}
when i do like this 127.0.0.1:8000/?categories=nihil-est-odit-nam-provident-omnis
, it has to work and filter the posts with categories with given slug, but it is showing all the posts, even in the clockwork
browser extension, it also showing the categories' => Category::all()
line, and this is executed, not the actual filtered query
return
two times?scopeFilter
, to return the query builder.Scopes should always return the same query builder instance or void
this is from documentation,return
isn't necessary.$query->when($filters['category'] ?? false, fn($query, $category) => $query ->whereHas('category', fn($query) => $query->where('slug', $category)));
i did this, but still not working, what might be the issue in there?