OunknownO OunknownO - 3 months ago 31
PHP Question

Laravel recursive partials view categories

I want to be able to display infinitive ammount of subcategories in my view for example I have in my blade view

@if (count($projects) > 0)
<ul>
@foreach ($projects as $project)
@include('partials.project', $project)
@endforeach
</ul>
@else
@include('partials.projects-none')
@endif


partials.project

<li>{{ $project['name'] }}</li>
@if (count($project['children']) > 0)
<ul>
@foreach($project['children'] as $project)
@include('partials.project', $project)
@endforeach
</ul>
@endif


projects-none

You have no projects!


but after I enter I get error message

Undefined variable: projects but when I dd($projects) i get data from database

Controller code

$projects= Projects::all(); (I tried it even with pluck but it didn't work)
return view('projects')->with('projects', $projects);


I have added dd($projects) after if loop in view to see if I'm receiving it all and I was receiving it;

Answer

I. With your "messy way"
- Change

@include('partials.project', $project)

- To

@include('partials.project', ['project'=>$project])

II. Try this better way. I though
- All in partials.projects

<ul>
      @each ('partials.project', $projects, 'project', 'partials.projects-none')
</ul>

Similar to partials.project. I lot of code will be saved.

Comments