public function scopeWithMedia(Builder $q, $tags = [], $match_all = false) { $tags = (array) $tags; if (empty($tags)) { return $q->with('media'); } if ($match_all) { return $q->withMediaMatchAll($tags); } $q->with(['media' => function (MorphToMany $q) use($tags) { $q->wherePivotIn('tag', $tags); }]); }