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

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Write For US
  • News
  • About Us
  • Tools
You are here: Home / Programming / Hierarchical Tree view Category Example in Laravel

Hierarchical Tree view Category Example in Laravel

May 3, 2020 by Editorial Staff Leave a Comment

Most of the projects you work in PHP or in any language, there you have to encounter with categories and sub categories. When comes to categories, 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 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 in to 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 same table. In some cases you will have to point this to different table and Model.

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

 


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

Filed Under: PHP, Programming Tagged With: Laravel

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

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

Primary Sidebar




Quick Links

  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Word Set 01
  • Convert PNG to JPG Online

Subscribe

* indicates required

Share

   

Hot topics

  • A Simple YouTube Video Downloader Script in PHP 13.3k views
  • Open a URL in a new tab using JavaScript 10.7k views
  • Using Third-Party Libraries in Codeigniter 8.4k views
  • Add FTP/SFTP in Visual Studio Code 6.1k views
  • Replace “\n” with new line characters, using Notepad++ 4.8k views
  • Manually Install APK Files In Android Studio Emulator 4.7k views
  • Upload Multiple Images and Store in Database using PHP and MySQL. 4.5k views
  • How To Install And Use CKEditor In Laravel? 4.2k views
  • Simple PHP Shopping Cart 4k views
  • Spout, an awesome library for reading and writing in Excel. 3.3k views

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 © 2021 · TutsPlanet Gene Theme on Genesis Framework · Powered By BunnyCDN