Search code examples
phplaraveleloquentlaravel-7

Laravel where condition in relationship


I have a problem for sometime.. I have a list of anime_shows and each one of them have multiple genres and I want to create a filter where a user can select only the ones that contains some specific genres.

I have 3 tables: anime_shows, genres and anime_show_genres (in the last one I have 2 columns anime_show_id, genre_id).

The problem with my current code is that I get all anime_shows where I have at least 1 genre, so I am using OR insted of AND. I also tried to do a forEach inside of whereHas but is not working.

$anime = AnimeShow::select('id', 'slug', 'status', 'title_eng', 'title_jap', 'description', 'episodes', 'premier_date', 'status')
        ->with('media:anime_show_id,image_path');

if($request->genres){
    $genres = $request->genres ? $request->genres : [];
    $anime->whereHas('genres', function($q) use($genres){
        $q->whereIn('id',$genres);
    });
}

if($request->airing){
    $anime->whereIn('status', $request->airing);
}

$anime->search($request->search);
        
return response($anime->paginate($request->perPage, ['*'], 'page', $request->currentPage));

Solution

  • Try to loop the genres like this:

    $genres = $request->genres ?: [];
    
    foreach ($genres as $genre) {
        $anime->whereHas('genres', function($q) use ($genre) {
            $q->where('id', $genre);
        });
    }
    

    It would be animes that have genere A and have genre B and so one.