M
M
Muhammad2015-03-29 18:51:20
Online shopping
Muhammad, 2015-03-29 18:51:20

Recursive Laravel category output?

Hello. I am making an online store on Laravel and already at the initial stage there was a snag: I don’t know how to display a list of categories. There is a categories table:
id - int
title - varchar
url - CNC
parent_id - parent ID and a Category
model class that has a getSubCategories method :

public function getSubCategories($categoryId)
{
  return Category::where('parent_id', '=', $categoryId);
}

In view layout/navigation.blade.php I also wanted to make a recursive output. Can you please tell me how this can be implemented?
PS I tried to make a function in the navigation file, but Laravel swears at curly braces.
Example:
<Ul>
  <li>Категория 1</li>
  <li>Категория 2
  <ul>
    <li>Подкатегория 1</li>
    <li>Подкатегория 2</li>
    <li>Подкатегория 3
    <ul>
      <li>Подкатегория 1</li>
      <li>Подкатегория 2</li>
      <li>Подкатегория 3</li>
    </ul>
    </li>
  </ul>
  </li>
  <li>Категория 3</li>
</Ul>

UPD.: Stopped at nested sets

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vyacheslav Plisko, 2015-03-29
@muhammad_97

Get rid of the method, use link to yourself
public function children()
{
return $this->hasMany('Category', 'parent_id', 'id');
}
When sampling for optimization, you can use Category::with('children'). For output, it's better to write a recursive blade helper, or use a recursive include to check for children.

// template_name.blade.php
@foreach($items as $item)
@if ($item->children)
    @include('template_name', ['items' => $item->children])
@endif
@endforeach

U
uam, 2015-03-29
@uam

There should be no curly braces in a blade other than double or triple. Everything else, such as conditions or loops, is kissed without brackets through the dog

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question