user3810794
user3810794

Reputation: 273

dynamic menu in laravel

Im trying to create dynamic menu. Basically,I have two tables :Category and pages.Not sure how should I do this but following is something I have tried

<nav class="navbar navbar-inverse">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="{{url('/',null)}}" class="pull-left">Consulate</a>
        </div>
    <div>
    <ul class="nav navbar-nav">
        <li class="active"><a href="{{url('/',null)}}">Home</a></li>
        @foreach($categories as $category )
        <li class="dropdown">
            <a  class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{$category->title}}<span class="caret"></span></a>
            <ul class="dropdown-menu">
            @foreach($pages as $page)
                <li><a href="{{action('publicpagecontroller@show',[$page->id])}}">{{$page->title}}</a></li>
            @endforeach
            </ul>
        </li>
        @endforeach

With above code, I got the same drop down menus in all the categories.I require dropdown only if the category have pages. example1 example2

My models looks like following: Pages model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Pages extends Model
{
    protected $fillable=[
        'title',
        'details',
        'image',
        'category_id',
    ];

    //A page has a category

    public function category()
    {
        return $this->belongsTo('App\Categories');
    }
}

categories model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Categories extends Model
{
    protected $fillable=[
        'title',
        'details',
    ];
    public function pages()
    {
        return $this->hasMany('App\Pages');
    }
}

Upvotes: 0

Views: 2110

Answers (1)

Matt Inamdar
Matt Inamdar

Reputation: 146

You could store your categories in a database table called categories (id, name, url). You could then also have another table called pages (id, name, url, category_id).

Create a Category and Page model.

Define a one-to-many relationship (one category-to-many pages).

You could then do:

@foreach( $categories as $category )
  <!-- display your category html -->

  @foreach( $category->pages as $page )
    <!-- display your page html -->
  @endforeach

@endforeach

Have a look at one-to-many relaitonships in Laravel: Eloquent: Relationships - one-to-many

Upvotes: 1

Related Questions