HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/helder.komma.pro/app/Komma/Sidebar/SidenavComposer.php
<?php

namespace App\Komma\Sidebar;

use App\Komma\Pages\Models\Page;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Request;


class SidenavComposer
{
    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $root = Page::where('lft',1)->first();

        $pages = $this->build($root);

        $view->with([
            'pages'=>$pages,
        ]);
    }


    //todo: refactor, do this in a service
    private function build($root)
    {
        // Fetch children on depth 1
        $pages = $root->findChildren();

        // Create array with required page ids
        $pagesIds = [];
        foreach($pages as $page)
        {
            $pagesIds[] = $page->id;
        }

        // Fetch required pages with relations
        $pages = Page::with(['translation.route'])->whereIn('id',$pagesIds)->get();

        $collection = collect([]);

        foreach($pages as $page)
        {
            $routeAlias = $page->translation->route->alias;
            if($routeAlias == '/') $page->translation->route->alias = '';

            if(\Str::startsWith(Request::path(),$routeAlias))
            {
                $page->routeIsActive = 1;
                $page->children = $this->build($page);
            }

            $collection->push($page);
        }

        $collection = $collection->sortBy('lft');

        return $collection;
    }

}