Paul
Paul

Reputation: 124

Dynamic menu laravel

I am starting with laravel, and made an integration with bootstrap. I want to make a menu bar to access to the information by year, the menu is made I this way to the view

<li class="dropdown-submenu">
    <a tabindex="-1" href="#">2007</a>
    <ul class="dropdown-menu">
        <li><a tabindex="-1" href="<?php echo url('/convenios/2007/registrar', $parameters = array(), $secure = null); ?>">Registrar</a></li>
        <li><a href="#">Consultar</a></li>
    </ul>
</li>

I made this on a view called base.blade.php, there is a better way to make the menus or I made this in the right way?

Upvotes: 1

Views: 11806

Answers (1)

Mahmoud Khalil
Mahmoud Khalil

Reputation: 344

menus table

id - parent_id - title - url - order - created_at - updated_at

Make Menu model

class Menu extends Model
{

  public $timestamps = false;

  protected $table = 'menus';

  protected $fillable = array('parent_id','title','url','order');

  public function parent()
  {
    return $this->belongsTo('App\Menu', 'parent_id');
  }

  public function children()
  {
    return $this->hasMany('App\Menu', 'parent_id');
  }
}

in View

@foreach(App\Menu::orderBy('order','asc')->get() as $menuItem)

  @if( $menuItem->parent_id == 0 )
     <li {{ $menuItem->url ? '' : "class=dropdown" }}>
     <a href="{{ $menuItem->children->isEmpty() ? $menuItem->url : "#" }}"{{ $menuItem->children->isEmpty() ? '' : "class=dropdown-toggle data-toggle=dropdown role=button aria-expanded=false" }}>
        {{ $menuItem->title }}
     </a>
  @endif

  @if( ! $menuItem->children->isEmpty() )
    <ul class="dropdown-menu" role="menu">
      @foreach($menuItem->children as $subMenuItem)
          <li><a href="{{ $subMenuItem->url }}">{{ $subMenuItem->title }}</a></li>
      @endforeach
    </ul>
  @endif
  </li> 

@endforeach

you can make controller as you like

this way i spent all day trying to get this working code, when i finished i decide to search for anybody ask for that issue

Have fun :)

Upvotes: 11

Related Questions