PHP code example of maso / treeify

1. Go to this page and download the library: Download maso/treeify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

maso / treeify example snippets


use Maso\Treeify\Traits\HasTree;

class Category extends Model
{
    use HasTree;

    /**
     * The name of the field that identifies the parent ID.
     *
     * This field is optional. If not specified, the default field name 'parent_id' will be used
     *
     */
    protected $parentFieldName = 'parent_id';
}


$tree = Category::treeify();

[
    {
        "id": 1,
        "name": "Electronics",
        "children": [
            {
                "id": 2,
                "name": "Laptops",
                "children": [
                    {
                        "id": 5,
                        "name": "Gaming Laptops"
                    }
                ]
            },
            {
                "id": 3,
                "name": "Desktops"
            },
            {
                "id": 4,
                "name": "Smartphones"
            }
        ]
    }
]

$category = Category::find(2);
$categoryTree = $category->treeify();


[
    {
        "id": 2,
        "name": "Laptops",
        "children": [
            {
                "id": 5,
                "name": "Gaming Laptops"
            }
        ]
    }
]

$tree = Category::treeify(false);



[
    {
        "id": 1,
        "name": "Electronics",
        "children": [
            {
                "id": 2,
                "name": "Laptops",
                "children": [
                    {
                        "id": 5,
                        "name": "Gaming Laptops"
                    }
                ]
            },
            {
                "id": 3,
                "name": "Desktops"
            },
            {
                "id": 4,
                "name": "Smartphones"
            }
        ]
    },
    {
        "id": 2,
        "name": "Laptops",
        "children": [
            {
                "id": 5,
                "name": "Gaming Laptops"
            }
        ]
    },
    {
        "id": 3,
        "name": "Desktops"
    },
    {
        "id": 4,
        "name": "Smartphones"
    }
]