11

For a school project, I'm creating a website in the Laravel framework. I can't work with the data from a many-to-many table in my controller.

Here are my models:

class Item extends Eloquent {
    public function Tags()
    {
        return $this->belongsToMany('Tag', 'items_has_tags', 'items_id', 'tags_id');
    }
}

class Tag extends Eloquent {
    public function LearningMaterials()
    {
        return $this->belongsToMany('LearningMaterial', 'learning_materials_has_tags', 'tags_id', 'learning_materials_id');
    }
}

I want to iterate all tags from my items in my controller:

//get all items
$all = Item::where('public', '1')->get();

foreach($allLm as $item){
     $tags = $item->Tags();

     var_dump('will iterate');

     foreach($tags as $t){
         var_dump('will not iterate');
     }
}

What is wrong with my code? How can I handle the tags from my items?

FYI: I'm creating a search engine. If the user inserts an input value like "mana", all items with tag "management" should be shown.

Jasper Poppe
  • 481
  • 2
  • 7
  • 16

2 Answers2

21

Laravel's belongsToMany method queries related models and doesn't get them. That's because you might want to have some additional constraints in your query. What you need to do is:

$tags = $item->Tags()->get();

Or simply:

$tags = $item->Tags;
Robo Robok
  • 21,132
  • 17
  • 68
  • 126
9

Calling the relationship function will return a relation object (in this case an instance of BelongsToMany). You can use this to run add further components to your query before running it.
For example:

$only4Tags = $item->Tags()->take(4)->get();

If you want the result of your relation, call get() or simpler, just use the magic property:

$tags = $item->Tags()->get();
$tags = $item->Tags;
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • How would you do it for specific Tags IDs (that come from an array)? – Pathros May 24 '17 at 15:26
  • @Pathros would you even need a relation then? You could just query them like `Tag::find([1, 2, 3])` if you have the ids. – lukasgeiter May 24 '17 at 15:29
  • Thanks. It helped me to find out that I can use `->whereHas()` and then `->whereIn()` as shown [here](https://stackoverflow.com/q/36593847/1883256). – Pathros May 24 '17 at 16:53
  • Thanks, it also works for what I was looking for: `$onlyOneTag = $item->Tags()->take(1)->first()` – Pathros Apr 21 '23 at 19:29