PHP code example of fomvasss / tree-builder

1. Go to this page and download the library: Download fomvasss/tree-builder 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/ */

    

fomvasss / tree-builder example snippets




namespace App\Managers\TreeBuilder;

use Fomvasss\TreeBuilder\TreeBuilder;

class CommentTreeItem extends TreeBuilder
{
    protected $userTreeItem;

    public function __construct(UserTreeItem $userTreeItem)
    {
        $this->userTreeItem = $userTreeItem;
    }

    protected function transform(array $item)
    {
        return [
            'id' => $item['id'],
            'name' => $item['name'],
            'created_at' => optional(\Carbon\Carbon::parse($item['created_at']))->toIso8601String(),
            'user' => $this->userTreeItem->getItem($item['user'])
        ];
    }
}


class CommentController
{
    
    public function index(Request $request)
    {
        $comments = \App\Models\Comment::where('article_id', $request->article_id)->get();
		$commentTreeBuilder = new \App\Managers\TreeBuilder\CommentTreeItem();
		
        return \response()->json(['data' => $commentTreeBuilder->getTree($comments->toArray())]);
    }
    
	public function show($id)
	{
		$comment = \App\Models\Comment::findOrFail($id);
		$commentTreeBuilder = new \App\Managers\TreeBuilder\CommentTreeItem();
		
		return \response()->json(['data' => $commentTreeBuilder->hideDepth()->getItem($comment->toArray())]);
	}
}