Skip to content

Commit

Permalink
Added the withinChannels scope to the Channelable trait
Browse files Browse the repository at this point in the history
  • Loading branch information
fulopattila122 committed Sep 8, 2023
1 parent b8fbd5e commit 191be7a
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Channel/Traits/Channelable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -22,6 +23,7 @@

/**
* @property-read \Illuminate\Database\Eloquent\Collection $channels
* @method static Builder withinChannels(Collection|Channel|array $channels)
*/
trait Channelable
{
Expand Down Expand Up @@ -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));
}
}

0 comments on commit 191be7a

Please sign in to comment.