Support the ongoing development of Laravel.io →
Database Eloquent

I have a questions table, and a tags table. I want to fetch all questions from tags of a given questions. So, for example, I may have the tags "Travel", "Trains" and "Culture" attached to a given question. I want to be able to fetch all questions for those three tags. The tricky, so it seems, is that questions and tags relationship is a many-to-many defined in Eloquent as belongsToMany.

I thought about trying to merge the questions Collections as below:

foreach ($question->tags as $tag) {
    if (!isset($related)) {
        $related = $tag->questions;
    } else {
        $related->merge($tag->questions);
    }
}

It doesn't seem to work though. Doesn't seem to merge anything. Are I attempting this correctly? Also, is there perhaps a better way to fetch a rows of rows in a many-to-many relationship in Eloquent?

Last updated 3 years ago.
0

$related->merge() returns a new instance of Collection, it doesn't modify $related. So, the fix is simple:

foreach ($question->tags as $tag) {
    if (!isset($related)) {
        $related = $tag->questions;
    } else {
        $related = $related->merge($tag->questions);
    }
}
0

Sign in to participate in this thread!

Eventy

Your banner here too?

martynbiz martynbiz Joined 15 Feb 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.