Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing default data for a controller in Laravel

Tags:

php

laravel

I want to build a menu from an array in Laravel. What I'm currently doing is putting the array in a view

$menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];

and then looping through it to generate the menu:

<section>
    <!-- Left Nav Section -->
    <ul class="left">
        <li class="divider"></li>
        @foreach($menu as $key => $nav)
            <li class="has-dropdown">
                <a href="#" class="active">{{ $key }}</a>
                <ul class="dropdown">
                    @foreach($nav as $subnav)
                        <li>
                            <a href="">{{ $subnav }}</a>
                        </li>
                    @endforeach
                </ul>
            </li>
        @endforeach
    </ul>
</section>

Is there any other way that I can achieve the same result without putting the data in the view?

I also tried creating a constructor function in the controller:

public function __construct() {
    $menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];

    return $menu;
}

But I guess that is not how it works. I appreciate any ideas on how I can go about this. Thanks in advance

like image 952
user225269 Avatar asked Mar 13 '26 05:03

user225269


2 Answers

View composers to the rescue!

They are executed every time before a view is rendered, so you can use this to pass standard data to them.

like image 164
Franz Avatar answered Mar 14 '26 18:03

Franz


If you're using controller layouts you can bind data to the layout from within the constructor. Just make sure you call the parent constructor first so that the layout is instantiated properly.

public function __construct()
{
    parent::__construct();

    $this->layout->menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];
}

That will bind a $menu variable to the layout, and will also be available to any nested views that are used with Blades @include.

like image 38
Jason Lewis Avatar answered Mar 14 '26 18:03

Jason Lewis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!