Laravel gets data from many to many relationships

For a school project, I am creating a website in Laravel framework. I cannot work with 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 loop over all tags from my elements in the 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's wrong with my code? How can I handle tags from my elements?

FYI: I'm building a search engine. If the user inserts an input value such as "mana", all items tagged with "control" should be shown.

+3


source to share


2 answers


Laravel's belongsToMany

method queries related models and does not receive them. This is because you may have some additional restrictions in your request. What you need to do:

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

      



Or simply:

$tags = $item->Tags;

      

+8


source


A call to the relationship function returns a relationship object (in this case, an instance BelongsToMany

). You can use this to trigger adding additional components to your request before running it.
For example:

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

      



If you want the result of your relationship, call get()

or easier, just use the magic property:

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

      

+4


source







All Articles