Hard to describe this in the title so this image might clarify:
I have a recursive view which outputs the above:
@foreach($pages as $page)
<option value="{{$page->id}}"
@if($selected == $page->id) selected @endif
>@for($i=0; $i<$levels; $i++)↪@endfor {{$page->title}} (#{{$page->id}})
</option>
@if($page->children->count())
@include('cms::admin.partials.page-selector-option', ['pages' => $page->children, 'levels' => $levels + 1])
@endif
@endforeach
Let's say that a page has the following columns:
- id
- parent_id
- title
- content
- template_id
The problem is that the collection of pages passed to this view e.g:
$pages = Page::where('template_id', 10)->get()
Contains a page with a child page of 'test subcat' which is being output as a child page correctly, but it also contains the subpage itself being output as a new item below (see both #54 pages loading in the screenshot).
Doing something like this:
$pages = Page::where('template_id', 10)->where('parent_id', 0)->get()
Does help, however I still want to show pages here that are not necessarily top level pages so may not have a parent_id
of 0.
What I think I need to do is query the parent() relationship to see if the parent_id has the same template_id and if it does then do not return this item. Here's what I have so far which doesn't work:
public function scopeWithoutChildren($query)
{
return $query->with(
[
'parent' => function ($q) {
$q->where('template_id', '!=', 10);
}
]);
}
My Answer:
To create a recursive view in Blade that shows the parent of each item, you can use a recursive function in your Blade template. Here's an example of how you can achieve this:
First, create a Blade template file called `recursive.blade.php`:
php
@foreach($items as $item)
- {{ $item->name }}
@if(count($item->children))
@include('recursive', ['items' => $item->children])
@endif
@endforeach
Next, in your controller, pass the data to the view:
php
public function showRecursiveView()
{
$items = Item::whereNull('parent_id')->get();
return view('recursive', compact('items'));
}
In this example, we assume that you have an `Item` model with a `name` attribute and a `children` relationship that returns the child items of the current item.
When you visit the route that corresponds to the `showRecursiveView` method, the recursive view will be rendered, showing each item and its children in a nested list structure.
This approach allows you to display the parent of each item in a recursive manner using Blade templates in Laravel.
Rate this post
4 of 5 based on 2932 votesComments