• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

PHP, Programming TagsLaravel

Hierarchical Tree view Category Example in Laravel

May 3, 2020 Editorial Staff 2 Comments

Share
Tweet
Share

For most of the projects you work on in PHP or in any language, there you have to encounter categories and subcategories. When comes to categories, the tree view is the best listing method that we can use in our web apps.

In this article, we are showing you how to create a Laravel tree view for multi-level data. In this Laravel tree example tutorial we won’t use any third-party packages, but just Eloquent ORM and blade views.

Let’s dive deeper into Laravel tree view model. Here we have used Laravel 7, as it is the latest version when writing this article.

Step 1: Install Laravel 7 Application

Run the below command in the shell script. This will install the latest version of Laravel in your development environment.

composer create-project --prefer-dist laravel/laravel categoryApp

Step 2: Create Category Model with the migration file

The -m is helping us to create a migration along with the Model file.

php artisan make:model Category -m

Step 3: Add the necessary fields to the migration file

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTaxonomyTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('category', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedInteger('parent_id')->nullable(); $table->string('title'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('category'); } } 

Step 4: Modify the Category model to add the relationship

app/Category.php

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Category extends Model { public function subcategory(){ return $this->hasMany('App\Category', 'parent_id'); } }

This says a parent_id will have many child categories. This relationship is pointing to the same table. In some cases, you will have to point this to a different table and Models.

Step 5: Create the route to view the page

Route::get('/category','CategoryController@index');

Step 6: Create the controller

app/Http/Controllers/CategoryController.php

namespace App\Http\Controllers; use Illuminate\Http\Request; class CategoryController extends Controller { public function index() { $parentCategories = \App\Category::where('parent_id',0)->get(); return view('category.index', compact('parentCategories')); } }

Step 7: Create views

Create a folder resources/views/category and below listed files.

1. index.blade.php
2. sub_category_list.blade.php

The above files will help us to render the categories in the desired tree view.

resources/views/category/index.blade.php

 @foreach($parentCategories as $taxonomy) <ul> <li><a href="{{ action('Admin\CategoryController@edit',$taxonomy->id) }}">{{$taxonomy->title}}</a></li> @if(count($taxonomy->subcategory)) @include('admin.category.sub_category_list',['subcategories' => $taxonomy->subcategory]) @endif </ul> @endforeach

resources/views/category/sub_category_list.blade.php

@foreach($subcategories as $subcategory) <ul> <li>{{$subcategory->title}}</li> @if(count($subcategory->subcategory)) @include('admin.category.sub_category_list',['subcategories' => $subcategory->subcategory]) @endif </ul> @endforeach 

The above views are recursive views, so one will load inside the other. If we have all the setup in place, you will see the desired result from the below table

Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
  • Just want to thank us? Buy us a Coffee
  • May be another day? Shop on Amazon using our links.
    Your prices won't change but we get a small commission.

Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Reader Interactions

Comments

  1. Marcello Pato says

    Oct 25, 2021 at 8:34 pm

    WOW! Perfect, great job dude!

    Reply
  2. Mani Khan says

    Mar 18, 2023 at 12:28 pm

    Undefined variable: subcategories (View: E:\Luqman Ul Haq\Laravel\newProj\resources\views\subCategoryList.blade.php) (View: E:\Luqman Ul Haq\Laravel\newProj\resources\views\subCategoryList.blade.php)
    Giving This Error

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

Search Here

Share

   

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube

Copyright © 2025 · Planet on Genesis Framework · Powered By BunnyCDN . Network oneweb.tools