Basically I am completely stumped with this problem. I have a model in Laravel defined like this
class BlogCategory extends Model
{
protected $table = 'blog_categories';
protected $fillable = [
'parent_id',
'title',
'slug'];
public function parent()
{
return $this->belongsTo('App\Models\BlogCategory','parent_id','blog_category_id');
}
public function children()
{
return $this->hasMany('App\Models\BlogCategory','blog_category_id','parent_id');
}
}
Now as you can see this model can have parent child relationship to itself.
Now what the bootstrap treeview I am using wants is my data to be formatted as follows:
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1"
},
{
text: "Grandchild 2"
}
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
{
text: "Parent 3"
},
{
text: "Parent 4"
},
{
text: "Parent 5"
}
];
How can I achieve the desired outcome?
You don't have to use relations to make this tree. Just select all BlogCategory
models and iterate them recursively to make a tree.
For example, you can use answer from here Recursive function to generate multidimensional array from database result and adopt it for your needs.
What I had came up with similar situation with L-5.2, if you want to display the categories in multiple level, where single table is maintained for multi-level categories, I guess this will be useful.
id | category_id | name
1 NULL Main Category
2 1 -Sub-Category
3 1 -Sub Child
4 Null Second Main
5 4 -Second Sub
In Category model
public function subcategory()
{
return $this->hasMany(Category::class);
}
then in Controller or where ever you need listing:
$categories = \App\Category::where('category_id', null)->get();
Then, this you can use in you view:
<ul>
@foreach($categories as $category)
<li>{{ $category->name }}
@if(count( $category->subcategory) > 0 )
<ul>
@foreach($category->subcategory as $subcategory)
<li>{{ $subcategory->name }}</li>
{{-- If you want upto 3 level, then you can repeat above code with if condition here --}}
@endforeach
</ul>
@endif
</li>
@endforeach
</ul>
This will Look something like this in view:
Let me know if this was helpful. Thanks