I have a Laravel database with a table for tags
, a table for items
and a table for item_tag
. The tags are hierarchical, and as a result, I'm trying to query which tags have been set inside a loop.
That's easy, I just use $item->tags
and it gives me my tags in an accessible object, ready to loop through.
The problem appears when I want to check if a specific object is set, when showing a list of all tags. I'm using the following code for testing:
function buildTree($tags, $selected = null) {
echo "<ul>";
foreach($tags as $tag) {
echo "<li>";
if($selected[$tag->id]) {
echo "<strong>";
}
echo $tag->name;
if($selected[$tag->id]) {
echo "</strong>";
}
if($tag->children) {
buildTree($tag->children);
}
echo "</li>";
}
echo "</ul>";
}
$item = Item::find(1);
$tags = Tag::whereNull('tag_id')->get();
buildTree($tags, $item->tags);
The expected output would be that each tag that is selected would come up as bold in the tree. Of course, if that had happened, I wouldn't be posting this. Instead, it just highlights the first item in the tree, even though it isn't selected. (That's because $selected
isn't supposed to be addressed that way).
What's the correct way to get this information?