Laravel Polymorphic Many To Many Fetch By Specific Association

- 1 answer

Ad

I have a simple many-to-many polymorphic relationship (if such thing is possible):

Authors: On Blog we have Posts => Authorable On Magazine, Articles => Authorable

Both relationships work as expected/documented. What I need is to fetch All authors for a specific Post category

All I have is: Post::category('blue') Collection (category being a scope). Based on that, what is the best way to get Authors that wrote "Blue Posts" ?

Ad

Answer

Ad

You'll want to look into using the has() and whereHas() query methods within your scope. See Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? for a detailed explanation on using them.

Basically would look something like this:

$authorsOfBluePosts = Author::whereHas('posts', function ($postsQuery) {
    $postsQuery->whereHas('category', function ($categoryQuery) {
        $categoryQuery->where('name', 'blue');
    });
})->get();
Ad
source: stackoverflow.com
Ad