gfellainc's avatar

create navigation menu with subcategories

I'm a newbie to laravel framweork and i want to create a dynamic navigation menu with subcategories for my blog. i used navbar.blade.php for navigation in my shared folder in views.

and all parents categories and sub categories in same table with parent_id with 0 and not equal to zero accordingly. so please tell me what are the model, controller and view for this

0 likes
2 replies
tim_jespers's avatar
Level 3

You could actually create a Category model for this:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model{
    
    public function subcategories(){
        return $this->hasMany('\App\Category', 'parent_id');
    }

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

A controller for this is really not necessary, you can actually just make sure that the navbar view always receive a variable called $categories through a simple view composer within your AppServiceProviders register method.

//inside AppServiceProvider register method:

view()->composer('shared.navbar', function($view){
    //get all parent categories with their subcategories
    $categories = \App\Category::where('parent_id', 0)->with('subcategories')->get();
    //attach the categories to the view.     
    $view->with(compact('categories'));
});

in your navbar view you can now simply loop through them and do your magic:

@foreach ($categories as $category)
    {* PARENT CATEGORY DISPLAY LOGIC *}
    @foreach ($category->subCategories as $subCategory)
        {* SUBCATEGORY DISPLAY LOGIC *}
    @endforeach
@endforeach 
2 likes

Please or to participate in this conversation.