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.
source to share
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;
source to share