Danish Mehmood
Danish Mehmood

Reputation: 151

query scope is not working, it is not showing filtered data in laravel 8.77 project

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

Upvotes: 1

Views: 890

Answers (1)

Hussain Afeef
Hussain Afeef

Reputation: 36

public function scopeFilter($query, array $filters)
{
    $search = $filters['search'] ?? false;
    $category = $filters['category'] ?? false;

    $query
        ->when($search, function ($query, $search) {
            $query
                ->where('title', 'like', '%' . $search . '%')
                ->orWhere('body', 'like', '%' . $search . '%');
        })
        ->when($category, function ($query, $category) {
            $query
                ->whereHas('categories', function ($query) use ($category) {
                    $query->where('slug', $category);
                });
       });
 }

Assuming you have a categories() relationship defined in Post Model, I believe this should work for you.

Also dd(request(['search', 'category'])) to check if you are getting the array you want.

Upvotes: 1

Related Questions