Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

abkrim's avatar
Level 13

Filter query relation belongsToMany for column on related table

I've database with a 3 tables.

  • Campaigns
  • Subscribers
  • Campaign_subscribers (pivot table)

campaign

public function subscribers(): BelongsToMany
{
    return $this->belongsToMany(Subscriber::class);
}

subscriber

public function campaigns(): BelongsToMany
{
    return $this->belongsToMany(Campaign::class);
}

CampaingSubscriber

public function campaigns()
{
    return $this->belongsTo(Campaign::class);
}

public function subscribers()
{
    return $this->belongsTo(Subscriber::class);
}

migration

$table->unsignedBigInteger('campaign_id');
$table->foreign('campaign_id', 'campaign_id_fk_4864216')->references('id')->on('campaigns')->onDelete('cascade');
$table->unsignedBigInteger('subscriber_id');
$table->foreign('subscriber_id', 'subscriber_id_fk_4864216')->references('id')->on('subscribers')->onDelete('cascade');

tries

$subscribers = Campaign::with('subscribers')->where('id', 127)->get();

This returns collection with Campaign, with another collection of all subscribers of this campaign

I've tried several ways for search any subscriber, with = and like, buit not work,.

use Illuminate\Database\Eloquent\Builder;
 $subscribers = Campaign::with('subscribers')->where('id', 127)->whereHas('subscribers', function($q) { $q->where('email','like', '%mateos@mydomain%');})->get();

This return the same result that original query.

Also, below fails, and showing all records of de campaing.

$subscribers = Campaign::with('subscribers')->where('id', 127)->whereHas('subscribers', function($q) { $q->where('email','=', 'email@included_:in_results');})->get();

Apreciate help.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You do not need a CampaingSubscriber model if the database table is only for the association (i.e. no other behaviours)

If you want the Subscribers associated with a Campaign (id = 127); and where the subscriber email is like %mateos@mydomain%:

$subscribers = Subscriber::whereHas('campaign', fn ($q) => $q->where('id', 127))
    ->where('email', 'like', '%mateos@mydomain%')
    ->get();
1 like
abkrim's avatar
Level 13

@tykus I didn't have time to thank you for your help. She could not find the way, and she needed this tip, so as not to do a lot of loading the query at once to do it via array. Thanks a lot.

Please or to participate in this conversation.