Latest Code Tutorials

Nested Set in Laravel: Complete Step by Step Guide

What is Nested Set

Nested sets or Nested Set Model(NSM) is the way to store the hierarchical data in a relational table efficiently.

The nested set model is to number the nodes according to a tree traversal, which visits each node twice, assigning numbers in the order of visiting and at both visits. That leaves two numbers for each node, which are stored as two attributes. Querying becomes inexpensive: hierarchy membership can be tested by comparing these numbers. Updating requires renumbering and is therefore expensive.


NSM shows good performance when the tree is rarely updated. It is created to be fast for getting related nodes.

It is ideally suited for building a multi-depth menu or categories for the shop.


Nested Set is a Tree structure filled with different nodes. So their relationships are the following with each other.

  • Node belongs to parent
  • Node has many children
  • Node has many ancestors
  • Node has many descendants

Nested Set in Laravel with an Example

We will start this Laravel 5.6 Nested Set Tutorial by installing the Framework using the following command.

Step 1: Install Laravel.

I am using Laravel Valet. So, I need to type the following command to create a project.

laravel new nestedset

If you are not using any of the Homestead or Valet, you can pull it using this command.

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

After installing, go into the project folder.

cd nestedset

Configure the database in the .env file.

Step 2: Install the laravel-nestedset composer package.

You can find the official Github Library here.

We need to type the following command to pull it through composer.

composer require kalnoy/nestedset

Okay, so that is done; now we need to configure it.

First of all, we are trying to build an e-commerce shop. So it is the perfect scenario where we can use the Nested Set because we have first Categories, then Subcategories and the sub-subcategories, and so on. So We are trying to make a list in which the root is the primary Category, and then all its children are a subcategory.

Step 3: Create a model and database migration.

In the terminal, type the following command.

php artisan make:model Shop -m

So, it will generate the model as well as the migration file. 

In the migration file, we need to add some extra columns that the Nested Set library provides.


use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Kalnoy\Nestedset\NestedSet;

class CreateShopsTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('shops', function (Blueprint $table) {

     * Reverse the migrations.
     * @return void
    public function down()

So, this shops table contains the category_name and Nested Set columns.

Now, migrate the table using the following command.

php artisan migrate

We can see that in our shops’ table there are three columns, which are related to Nested Set.

  1. _lft
  2. _rgt
  3. parent_id

Nested Set in Laravel


Step 3: Seed the Database.

For this example, I am not creating the Dynamic data, but I build the static data and then feed that into the database. 

So first, create the Seeder file using the following command.

php artisan make:seeder ShopTableSeeder

Okay, now write the following code inside the ShopTableSeeder.php file.


use Illuminate\Database\Seeder;

class ShopTableSeeder extends Seeder
    public function run()
        $shops = [
                'category_name' => 'Books',
                    'children' => [
                            'category_name' => 'Comic Book',
                            'children' => [
                                    ['category_name' => 'Marvel Comic Book'],
                                    ['category_name' => 'DC Comic Book'],
                                    ['category_name' => 'Action comics'],
                            'category_name' => 'Textbooks',
                                'children' => [
                                    ['category_name' => 'Business'],
                                    ['category_name' => 'Finance'],
                                    ['category_name' => 'Computer Science'],
                    'category_name' => 'Electronics',
                        'children' => [
                            'category_name' => 'TV',
                            'children' => [
                                ['category_name' => 'LED'],
                                ['category_name' => 'Blu-ray'],
                            'category_name' => 'Mobile',
                            'children' => [
                                ['category_name' => 'Samsung'],
                                ['category_name' => 'iPhone'],
                                ['category_name' => 'Xiomi'],
        foreach($shops as $shop)

We are inserting the static array into the Database. Of course, in the real-time project, we need to do it dynamically, but for this example, I am just using a static array.

Now, go to the DatabaseTableSeeder.php file and add the following code.


use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
     * Seed the application's database.
     * @return void
    public function run()

Go to the terminal and seed using the following command.

php artisan db:seed

Laravel Nested Set Tutorial

Step 4: Create Routes and Controller.

Okay, go to the terminal and create a ShopController.php file.

php artisan make:controller ShopController

So, it will create and now write the following code inside it.


namespace App\Http\Controllers;

use App\Shop;
use Illuminate\Http\Request;

class ShopController extends Controller
    public function index()
        $shops = Shop::get()->toTree();
        return view('shop', compact('shops'));

So, what it will do is we get all the data in the tree format, on which we can call the children method, and we can display the exact hierarchical data into the view. 

We have not created a shop view yet, but we will do that in a minute. But first, let us create the route inside the web.php file.

// web.php

Route::get('/', 'ShopController@index');

Step 5: Display the Hierarchical data into the View.

Now, we have got the data, and we just need to pass that data into the View and display the data according to a parent-child relationship.

Inside the views folder, create one folder called layout, and inside that folder, create one file called app.blade.php.

Write the following code inside the app.blade.php file.

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
    <div id="app">
    <main class="py-4">

We have not created the partials folder, so let us create that inside the layout folder.

Inside the partials folder, create a file called _head.blade.php file.

<!-- _head.blade.php  -->

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="">
    <link href=",400,600" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

Now, finally, create one file inside the views folder called shop.blade.php.


<div class="container">
    <div class="card">
        <div class="row">
            <div class="card-body">
                @foreach($shops as $shop)
                <div class="col-md-12">
                    <h3>{{ $shop->category_name }}</h3>
                    <hr />
                    <div class="row">
                        @foreach($shop->children as $cats)
                        <div class="col-md-4">
                            <h4>{{ $cats->category_name }}</h4>
                            <hr />
                            @foreach($cats->children as $cat)

Now, save the file and go to the browser, and hit the root URL and in my case, it is http://nestedset.test

You will see something like this.

Laravel 5.6 Nested Set Model Tutorial


So, that means you are now getting the data based on your parent category. See how cool it is that we do not have to write any extra code, use that package, and are done.

In our example, our main categories are two

  1. Books
  2. Electronics

Now, Books’ subcategories are the following.

  1. Comic Book
  2. Text Book

Electronics subcategories are the following.

  1. TV
  2. Mobile

We can further go into the recursion if there are more subcategories.

We can use this hierarchy to build the Megamenu for the Shopping Categories.

So this is the basic example of the Nested Set Model.

That’s it for this tutorial. Thanks for taking it.

  1. Morteza says

    Hi tnx for topic.
    when i run seed i got this error
    preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

  2. Morteza says

    In Shop.php

    use Kalnoy\Nestedset\NodeTrait;

    class Shop extends Model {
    use NodeTrait;

  3. Mohamed says

    Hello Sir , Can i make a dynamic dropdown list from a NestedSet model ?

  4. Mohamedhamidi94 says

    Can i make a dynamic dropdown list from a NestedSet model ?

  5. Mark says

    why I receive an error Seeding: ShopTableSeeder

    ErrorException : Array to string conversion

    when seeding?

    1. Arne De Belser says

      I’ve got the same error, we seem to be missing something, did you manage to solve this?

      1. Lidia says

        use NodeTrait in your model

        1. bastian says

          I have the same problem even if I use nodetrait in the model

          1. bastian says

            Here the working Model extention you need to bring the seeder to work:


            namespace App;

            use Illuminate\Database\Eloquent\Model;
            use Kalnoy\Nestedset\NodeTrait;

            class Shop extends Model
            use NodeTrait;

  6. Konc says

    Nice tutorial, but please how do you insert a new record or update, its very important

  7. maliarkun says

    +1 Please new tutorial about new record and update.

  8. vijay Rami says

    How to add link to category ?

  9. Hamza Khan says

    In database where you get lft rgt values?

Leave A Reply

Your email address will not be published.

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