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

cansozeri's avatar

Laravel BelongstoMany WhereIn pivot table returns only one column instead of all

I have channel - channel_streams(pivot table) and stream_targets tables.

On Channel Model I have created a belongstoMany relationship. I want to select channel_streams with status 0 or 1.

The sql query is true and when I try it on mysql it returns 3 rows. But Laravel give me just one row - the last row. I think this problem is about with collections, but I can not figured it out..

public function targets()
{
    return $this->belongsToMany(Target::class,'channel_streams','channel_id','stream_target')
                ->wherePivotIn('status', [0, 1])
                ->withPivot('stream_url','stream_key','id','status');
}

The sql builder create this query. It is ok..

select `stream_targets`.*, `channel_streams`.`channel_id` as `pivot_channel_id`, `channel_streams`.`stream_target` as `pivot_stream_target`, `channel_streams`.`stream_url` as `pivot_stream_url`, `channel_streams`.`stream_key` as `pivot_stream_key`, `channel_streams`.`id` as `pivot_id`, `channel_streams`.`status` as `pivot_status` from `stream_targets` inner join `channel_streams` on `stream_targets`.`id` = `channel_streams`.`stream_target` where `channel_streams`.`channel_id` = '5' and `channel_streams`.`status` in ('0', '1') and `stream_targets`.`deleted_at` is null
0 likes
2 replies
cansozeri's avatar

If I use it without WherePivotIn filter there is no problem.

public function targets() { return $this->belongsToMany(Target::class,'channel_streams','channel_id','stream_target') ->withPivot('stream_url','stream_key','id','status'); }

cansozeri's avatar
cansozeri
OP
Best Answer
Level 4

I have solved it, very interesting, because status is an enum field. It needs to use like this ->wherePivotIn('status', ['0', '1']) .. So it is working on sql without this, but laravel it is not working ..

Please or to participate in this conversation.