Laravel 5 nested category/menu generator

Overview

Laravel 5 Nestable

Laravel Nestable to work with recursive logic. Category level there is no limit but this may vary depending on your server performance. Allow the 100000 recursion process execution since PHP 5.2. More info

Build Status

Install

composer require atayahmet/laravel-nestable

Then

Add to app.php the Service Provider file.

Nestable\NestableServiceProvider::class

Then add app.php Facade file again.

'Nestable' => Nestable\Facades\NestableService::class

Finally run the artisan command:

php artisan vendor:publish --provider="Nestable\NestableServiceProvider"

That's it!

Basic Usage with Eloquent

Suppose that the data came from a database as follows.

Category table:

id parent_id name slug
1 0 T-shirts t-shirts
2 1 Red T-shirts red-t-shirts
3 1 Black T-shirts black-t-shirts
4 0 Sweaters sweaters
5 4 Red Sweaters red-sweaters
6 4 Blue Sweaters blue-sweaters

Example 1:

<?php

use Nestable\NestableTrait;

class Category extends \Eloquent {

    use NestableTrait;

    protected $parent = 'parent_id';

}

Note: $parent variable refers to the parent category (Default parent_id)

<?php

$categories = Category::nested()->get();

Query result:

<?php

array:6 [
      0 => array:5 [
        "id" => 1
        "name" => "T-shirts"
        "slug" => "t-shirts"
        "child" => array:2 [
          0 => array:5 [
            "id" => 2
            "name" => "Red T-shirts"
            "slug" => "red-t-shirts"
            "child" => []
            "parent_id" => 1
          ]
          1 => array:5 [
            "id" => 3
            "name" => "Black T-shirts"
            "slug" => "black-t-shirts"
            "child" => []
            "parent_id" => 1
          ]
        ]
        "parent_id" => 0
      ]
      1 => array:5 [
        "id" => 4
        "name" => "Sweaters"
        "slug" => "sweaters"
        "child" => array:2 [
          0 => array:5 [
            "id" => 5
            "name" => "Red Sweaters"
            "slug" => "red-sweaters"
            "child" => []
            "parent_id" => 4
          ]
          1 => array:5 [
            "id" => 6
            "name" => "Blue Sweaters"
            "slug" => "blue-sweaters"
            "child" => []
            "parent_id" => 4
          ]
        ]
        "parent_id" => 0
    ]
]

For html tree output:

<?php

Category::renderAsHtml();

Output:

<ul>
    <li><a href="">T-shirts
        <ul>
            <li><a href="red-t-shirt">Red T-shirt</a></li>
            <li><a href="black-t-shirts">Black T-shirts</a></li>
        </ul>
    </li>

    <li><a href="">Sweaters
        <ul>
            <li><a href="red-sweaters">Red Sweaters</a></li>
            <li><a href="blue-sweaters">Blue Sweaters</a></li>
        </ul>
    </li>
</ul>

For dropdown output:

<?php

Category::attr(['name' => 'categories'])
    ->selected(2)
    ->renderAsDropdown();

Output:

<select name="categories">
    <option value="1">T-shirts</option>
    <option value="2" selected="selected">  Red T-shirts</option>
    <option value="3">  Black T-shirts</option>

    <option value="4">Sweaters</option>
    <option value="5">  Red Sweaters</option>
    <option value="6">  Blue Sweaters</option>
</select>

Selected for multiple list box:

->selected([1,2,3])

Output methods

name Parameter output
renderAsArray() none array
renderAsJson() none json
renderAsHtml() none html
renderAsDropdown() none dropdown
renderAsMultiple() none Listbox

Usable methods with output methods

renderAsArray()

name paremeter description
parent() int Get childs of the defined parent

renderAsJson()

name paremeter description
parent() int Get childs of the defined parent

renderAsHtml()

name paremeter description
parent() int Get childs of the defined parent
active() callback/array/int Selected item(s) for html output
ulAttr() array/string Add attribute to parent ul element
firstUlAttr() array/string Add attribute to parent ul element
route() callback/array Generate url by route name
customUrl() string Generate custom url

renderAsDropdown()/renderAsMultiple()

name paremeter description
parent() int Get childs of the defined parent
selected() callback/array/int Selected item(s) for dropdown
attr() array Dropdown/listbox attributes

parent()

Get childs of the defined parent.

<?php

Category::parent(2)->renderAsArray();

Note: This methods usable all with output methods

active()

Selected item(s) for html output.

Example 1:

<?php

Menu::active('t-shirts')->renderAsHtml();

Example 2:

<?php

Menu::active('t-shirts', 'black-t-shirts')->renderAsHtml();

Example 3:

<?php

Menu::active(['t-shirts', 'black-t-shirts'])->renderAsHtml();

Example 4:

<?php

Menu::active(function($li, $href, $label) {

    $li->addAttr('class', 'active')->addAttr('data-label', $label);

})->renderAsHtml();

Example 5:

<?php

Menu::active(function($li, $href, $label) {

    $li->addAttr(['class' => 'active', 'data-label' => $label]);

})->renderAsHtml();

firstUlAttr()

Add attribute to first ul element

Example 1:

<?php

Menu::firstUlAttr('class', 'first-ul')->renderAsHtml();

Example 2:

<?php

Menu::firstUlAttr(['class' => 'first-ul'])->renderAsHtml();

ulAttr()

Add attribute to parent ul element

Example 1:

<?php

Menu::ulAttr('class', 'nav-bar')->renderAsHtml();

Example 2:

<?php

Menu::ulAttr(['t-shirts' => 'black-t-shirts'])->renderAsHtml();

Example 3:

<?php

Menu::ulAttr(function($ul, $parent_id) {

    if($parent_id == 10) {
        $ul->ulAttr('class', 'nav-bar');
    }

})->renderAsHtml();

route()

Generate url by route name

Example 1:

<?php

Menu::route(['product' => 'slug'])->renderAsHtml();

Note: product refer to route name and slug refer to paremeter name.

<?php

Route::get('product/{slug}', 'ProductController@show');

Example 2:

<?php

Menu::route(function($href, $label, $parent) {

    return \URL::to($href);

})->renderAsHtml();

customUrl()

Generate custom url with slug

Example 1:

<?php

Menu::customUrl('product/detail/{slug}')->renderAsHtml();

Example 1:

<?php

Menu::customUrl('product/{slug}/detail')->renderAsHtml();

Note: slug keyword belongs to html > href in config file.

selected()

Selected item(s) for dropdown.

Example 1:

<?php

Category::selected(1)->renderAsDropdown();

Example 2:

<?php

Category::selected(1,5)->renderAsMultiple();

Example 3:

<?php

Category::selected([1,3])->renderAsMultiple();

Example 4:

<?php

Category::selected(function($option, $value, $label) {

    $option->addAttr('selected', 'true');
    $option->addAttr(['data-item' => $label]);

})->renderAsMultiple();

attr()

Dropdown/listbox attributes.

<?php

Category::attr(['name' => 'categories', 'class' => 'red'])->renderAsDropdown();

Configuration

The above examples were performed with default settings. Config variables in config/nestable.php file.

name type description
parent string Parent category column name
primary_key string Table primary key
generate_url boolean Generate the url for html output
childNode string Child node name
body array Array output (default)
html array Html output columns
dropdown array Dropdown/Listbox output

body

The body variable should be an array and absolutely customizable.

Example:

<?php

'body' => [
    'id',
    'category_name',
    'category_slug'
]

html

Configuration for html output.

name description
label Label column name
href Url column name

Example:

<?php

'html' => [
    'label' => 'name',
    'href'  => 'slug',
]

dropdown

Configuration for dropdown/listbox output.

name description
prefix Label prefix
label Label column name
value Value column name

Example:

<?php

'dropdown' => [
    'prefix' => '-',
    'label'  => 'name',
    'value'  => 'id'
]

Using Independent Models

Include the Nestable facade.

<?php

use Nestable;

$result = Nestable::make([
    [
        'id' => 1,
        'parent_id' => 0,
        'name' => 'T-shirts',
        'slug' => 't-shirts'
    ],
    [
        'id' => 2,
        'parent_id' => 1,
        'name' => 'Red T-shirts',
        'slug' => 'red-t-shirts'
    ],
    [
        'id' => 3,
        'parent_id' => 1,
        'name' => 'Black T-shirts',
        'slug' => 'black-t-shirts'
    ]
    // and more...
]);

For array output:

$result->renderAsArray();

Validators

It controls the structure of the data. They also made the rendering process with a second parameter control after they.

name Parameters
isValidForArray boolean
isValidForJson boolean
isValidForHtml boolean
isValidForDropdown boolean
isValidForMultiple boolean

Example 1:

<?php

Menu::make($categories)->isValidForHtml();

// return true or false

Example 2:

<?php

Menu::make($categories)->isValidForHtml(true);

// return html string if data valid

Macros

<?php

Nestable::macro('helloWorld', function($nest, $categories) {

    return $nest->make($categories)->active('sweater')->route(['tests' => 'slug'])->renderAsHtml();

});

Call the above macro:

<?php

$categories = [

    [
        'id'        => 1,
        'parent_id' => 0,
        'name'      => 'T-shirt',
        'slug'      => 'T-shirt'
    ],
    [
        'id'        => 2,
        'parent_id' => 0,
        'name'      => 'Sweater',
        'slug'      => 'sweater'
    ]

];

Nestable::helloWorld($categories);

Helper

<?php

nestable($data)->renderAsHtml();
<?php

nestable()->make($data)->renderAsHtml();
<?php

nestable()->macro('helloWorld', function() {
    return 'Hello Laravel';
});

// run
nestable()->helloWorld();
Comments
  • Add Attributes to <ul> and <li>

    Add Attributes to

    hi dear @atayahmet i want to add some attributes to <ul> but i didn't see anything in documentation

    is it possible in this version? if it's not, how i can add this feature to the package?

    edit: i solved this by modifing NestableService.php (only worked for parent ul) i changed renderAsHtml by these codes:

    if($first) {
       $tree = $first ? '<ul '.$this->addAttributes().'>' : '';
    }
    

    anyway i'm waiting for your update for this package ... i need attributes for <ul> and <li> i have a function to generate ul li for nav-menu so i need dynamic attributes for nested ul and li

    enhancement help wanted question 
    opened by mostafaznv 15
  • use where in output query

    use where in output query

    hi. thanks for your nice package.

    i created a custom database like this:

    | id | parent_id | name | slug | post_type | img | | --- | --- | --- | --- | --- | --- | | 1 | 0 | cat 1 | cat-1 | posts | thumb.jpg | | 2 | 1 | cat 2 | cat-2 | posts | p.png | | 3 | 0 | cat 3 | cat-3 | products | pthumb.jpg |

    i want to show only categories for a specific post_type can u help me?

    bug enhancement 
    opened by mostafaznv 14
  • Memory Problem

    Memory Problem

    Hello, When I want to use this package I get:

    Fatal error: Out of memory (allocated 1470103552) (tried to allocate 262144 bytes) in D:\xampp\htdocs\platform\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 621

    After remove Nestable\NestableServiceProvider::class problem fixed.

    Now How can I use this package.

    Note:I change my memory_limit but yet it need more memory.

    help wanted question 
    opened by ghost 9
  • $categories = Category::nested()->get();

    $categories = Category::nested()->get();

    Im using laravel 5.5. I have added the package. I have also added the trait to the model,

    Where do i need to specify this $categories = Category::nested()->get(); When i do {{$categories = Category::nested()->get();}} it does not show anything on the view

    help wanted question 
    opened by ghost 8
  • where is breadcrumb option, how i can retrieve parents of child?

    where is breadcrumb option, how i can retrieve parents of child?

    hello i want to inverse the hierarchy, since each child can have one parent, how i can retrieve the breadcrumb (parents) of a child?

    -Electornic --Computer and tablet ---Computer (want get parent of computer as below)

    i want below Compiter > Computers and Tablets > Electronic

    help wanted question 
    opened by knour89 7
  • Not Compatible With Laravel  5.6

    Not Compatible With Laravel 5.6

    Hello Thank You For Your Time Making Good Work Out There 🔥

    I Have Installed The Package 📦

    On Laravel 5.6 💯 But It's Not Displaying When Using The Methods On Your Package I May Do Something Wrong

    question 
    opened by zymawy 6
  • configuring the link, route

    configuring the link, route

    hi i have many nested categories like mechanic-part,car and place but when i render as html and i click in a link it go directly to site.local/{slug} i want to change to custom link like site.local/car/{slug} site.local/mechanic-part/{slug} .... how can i?

    enhancement 
    opened by amine8ghandi8amine 6
  • I cannot use Eloquent methods

    I cannot use Eloquent methods

    Hello @atayahmet I've just installed your package to handle categories, but when I use Nestable\NestableTrait all Eloquent methods are not working as where(), findOrFail(), delete() .... And if I remove NestableTrait everything working good.

    Any solutions please ..

    bug enhancement help wanted question 
    opened by ZedanLab 6
  • Category by Id

    Category by Id

    Example category table

    | id | parent_id | name | slug | |----|-----------|-------|-------| | 1 | 0 | Car | car | | 2 | 1 | BMW | bmw | | 3 | 1 | Benz | benz | | 4 | 0 | Truck | truck |

    Is there any way to get Car's children only?

    Current output. Truck category also return

    {  
       "id":1,
       "name":"Car",
       "slug":"car",
       "child":[  
          {  
             "id":2,
             "name":"BMW",
             "slug":"bmw"
          },
          {  
             "id":3,
             "name":"Benz",
             "slug":"benz"
          }
       ]
    },
    {  
       "id":1,
       "name":"Truck",
       "slug":"truck"
    }
    
    question 
    opened by mifas 4
  • Call to a member function delete() on null in NestableTrait

    Call to a member function delete() on null in NestableTrait

    When I try deleting a record, it is throwing me this error

    FatalErrorException in NestableTrait.php line 277:
    Call to a member function delete() on null
    

    My Model File

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Nestable\NestableTrait;
    
    class Menu extends Model
    {
    use NestableTrait;
    
    protected $parent = 'parent_id';
    
    protected $fillable = ['parent_id', 'menu_id', 'name', 'slug', 'status'];
    }
    
    bug enhancement 
    opened by Sarav-S 4
  • Maximum function nesting level of '256' reached, aborting!

    Maximum function nesting level of '256' reached, aborting!

    This happens when attempting to use any function (that uses recursion behind the scenes).

    Side Note: My database table structure uses UUIDs for the primary key column, and thus also for the parent_id column. I also have a nullable foreign key from parent_id to id to constrain relationships.

    The documentation shows a parent_id of "0" for a category that's at the top. In my case, it's simply a null value for parent_id if it's at the top. A value of 0 would error out even if you were using numeric values with a foreign key constraint, as 0 would never be a valid ID because auto incrementing columns typically start on 1.

    Not sure what the issue is with this but I'm guessing it has something to do with this.

    opened by GlitterCakes 3
  • leftJoin not working with Category Model using NestableTrait

    leftJoin not working with Category Model using NestableTrait

    I have the following code in Category Model:

    <?php
    
    use Nestable\NestableTrait;
    
    class Category extends \Eloquent {
    
        use NestableTrait;
    
        protected $parent = 'parent_id';
    
    }
    

    And

    Category::attr(['name' => 'categories'])
        ->selected(2)
        ->renderAsDropdown();
    

    The above code works fine. But in some other function in Controller when I use leftJoin function with Category Model, leftJoin is not working. I have something like below:

    Category: leftjoin('expense','category.id','expense.category_id')->get();

    in above eloquent leftjoin is not rendering in response. Any help?

    opened by cse111 0
  • Default first item

    Default first item

    I need to render categories as dropdown, but need the first element to be empty. How can i set a default "Select one" with empty value and custom text?

    opened by josegus 1
Releases(v0.4.5)
Owner
Ahmet
Web Developer | Electronic music lover. Founder of themixzone.com
Ahmet
A collapsible side navigation menu built to seamlessly work with Bootstrap framework

yii2-widget-sidenav This widget is a collapsible side navigation menu built to seamlessly work with Bootstrap framework. It is built over Bootstrap st

Kartik Visweswaran 36 Apr 9, 2022
An intelligent code generator for Laravel framework that will save you time

An intelligent code generator for Laravel framework that will save you time! This awesome tool will help you generate resources like views, controllers, routes, migrations, languages and/or form-requests! It is extremely flexible and customizable to cover many of the use cases. It is shipped with cross-browsers compatible template, along with a client-side validation to modernize your application.

CrestApps 621 Jan 8, 2023
基于 swoole 的多进程队列系统,低延时(最低毫秒级)、低资源占用, 支持一键化协程、超时控制、失败重试。可与 laravel thinkphp 等框架配合使用

multi-process-queue 基于swoole的多进程队列系统,manage进程管理子进程,master进程监听队列分发任务,worker进程执行任务, 多进程、低延时(最低毫秒级)、低资源占用。可与 laravel thinkphp 等框架配合使用 版本要求: php>=7.1 swoo

yuntian 55 Dec 12, 2022
This package provides some basic methods to implement a self updating functionality for your Laravel application. Already bundled are some methods to provide a self-update mechanism via Github or some private repository via http.

This package provides some basic methods to implement a self updating functionality for your Laravel 5 application. Already bundled are some methods to provide a self-update mechanism via Github.

Holger Lösken 311 Dec 31, 2022
A magic PHP framework. Build reactive web apps without writing HTML, CSS, or JavaScript! Powered by Tailwind, Alpine, Laravel, & Livewire.

Malzahar A magic PHP framework. Build reactive web apps without writing HTML, CSS, or JavaScript! Powered by Tailwind, Alpine, Laravel, & Livewire. Re

null 26 Nov 17, 2022
Supercharge your Laravel application's performance.

Introduction Laravel Octane supercharges your application's performance by serving your application using high-powered application servers, including

The Laravel Framework 3.3k Jan 1, 2023
I made my own simple php framework inspired from laravel framework.

Simple MVC About Since 2019, I started learning the php programming language and have worked on many projects using the php framework. Laravel is one

null 14 Aug 14, 2022
Awesome tips for Laravel

Awesome tips for Laravel

Laravel Daily 5.3k Jan 1, 2023
A set of ready-made regex helper methods for use in your Laravel application.

Regex A set of ready-made regex helper methods for use in your Laravel application. Installation composer require hotmeteor/regex Usage Regex comes wi

Adam Campbell 229 Dec 25, 2022
A modified version of the Laravel Framework

Hexavel Framework Hexavel is a restructured version of Laravel, with the purpose of providing better work flows which will simplify the development pr

Peter Fox 7 Nov 1, 2022
RoadRunner ⇆ Laravel bridge

RoadRunner ⇆ Laravel bridge Easy way for connecting RoadRunner and Laravel applications. ?? If you want to see an example of a laravel application in

Spiral Scout 328 Dec 21, 2022
Laravel 8 Project Restrict User Access From IP Addresses. prevent other ip address that want to access over secure api or urls.

block-ip-address-laravel Laravel 8 Project Restrict User Access From IP Addresses. prevent other ip address that want to access over secure api or url

Hasmukh Dharajiya 2 Mar 24, 2022
💡 Mudrock is a MVC PHP framework, which was inspired by the Laravel and CodeIgniter frameworks.

?? Mudrock is a MVC PHP framework, which was inspired by the Laravel and CodeIgniter frameworks

null 3 Nov 17, 2021
Trabajo 06 Laravel y el modelo MVC

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Miguel Angel Sotelo Palacios 1 Nov 15, 2021
Files Course Laravel Microservice E-mail

Curso Laravel Microservices com RabbitMQ (micro e-mail) Saiba Mais Sobre o Curso Requisitos Este micro e-mail depende do microservice 01, portanto, pr

EspecializaTi 9 Oct 21, 2021
LaravelS is an out-of-the-box adapter between Swoole and Laravel/Lumen.

?? LaravelS is an out-of-the-box adapter between Swoole and Laravel/Lumen.

Biao Xie 3.7k Dec 29, 2022
Generate auto numbers for your Laravel Model.

Generate Autonumbers for your Laravel Model This package can help you in creating autonumbers for your laravel model. You can create autonumbers using

Ishaan 1 Dec 5, 2021
I made my own simple php framework inspired from laravel framework.

Simple MVC About Since 2019, I started learning the php programming language and have worked on many projects using the php framework. Laravel is one

Rizky Alamsyah 14 Aug 14, 2022
This package provides a high performance HTTP server to speed up your Laravel/Lumen application based on Swoole.

This package provides a high performance HTTP server to speed up your Laravel/Lumen application based on Swoole.

Swoole Taiwan 3.9k Jan 8, 2023