diff --git a/src/Channel/Traits/Channelable.php b/src/Channel/Traits/Channelable.php index 6fb90c05..b3d85b7c 100644 --- a/src/Channel/Traits/Channelable.php +++ b/src/Channel/Traits/Channelable.php @@ -14,6 +14,7 @@ namespace Vanilo\Channel\Traits; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphToMany; use Illuminate\Support\Collection; @@ -22,6 +23,7 @@ /** * @property-read \Illuminate\Database\Eloquent\Collection $channels + * @method static Builder withinChannels(Collection|Channel|array $channels) */ trait Channelable { @@ -49,4 +51,18 @@ public function removeFromAllChannels(): void { $this->channels()->detach(); } + + public function scopeWithinChannels(Builder $query, Collection|Channel|array $channels): Builder + { + $ids = []; + if ($channels instanceof Channel) { + $ids[] = $channels->getKey(); + } else { + foreach($channels as $channel) { + $ids[] = $channel instanceof Channel ? $channel->id : $channel; + } + } + + return $query->whereHas('channels', fn ($query) => $query->whereIn('channel_id', $ids)); + } }