Search code examples
laraveleloquentmany-to-manypivot-table

Laravel - whereHas query not returning correct records


I am currently writing a search query but I'm having issues joining a where with a whereHas

if I wanna search for categories only..

The below query works if I just search for categories solo

 $goals = $myGoals
        ->whereHas('categories', function ($q) use ($search) {
            $q->where('name', 'like', "%$search%");
        })->paginate(10);

if I wanna search for the title only..

Same as above if I wanna search for the title of goals solo

$goals = $myGoals->where('title', 'like', "%$search%" )->paginate(10);

both of the queries work if I want to search for them individually.

Query attempt

Below is the query I've written to allow a user to search for the title of a goal and the name of a category.

 $myGoals = $team->goals();

    $goals = $myGoals
        ->whereHas('categories', function ($q) use ($search) {
            $q->where('name', 'like', "%$search%");
        })->where('title', 'like', "%$search%" )->paginate(10);

I have tried the above query but the search results return empty when I enter an input. I've also tried swapping the where() to orWhere() which then returns a goal that doesn't belong to the $team model instance but it's a goal record linking to a different Team model id within the pivot table.

Can anyone spot where I am going wrong? thanks


Solution

  • You need to use it all inside where.

    $goals = $myGoals->where(function ($query) use ($search){
                    return $query->whereHas('categories', function ($q) use ($search) {
                        $q->where('name', 'like', "%$search%");
                    })->orWhere('title', 'like', "%$search%" );
                    })->paginate(10);