0

To build my menu i have a file Providers/ViewComposerServiceProvicer.php . in this file I have:

public function boot()
{
    $this->composeNavigation();
}

public function composeNavigation()
{
    view()->composer('front.layouts.menu', function ($view) {
        $view->with('menuItems', \App\MenuItem::orderBy('priority', 'asc')->get());
    });
}

What i want is add a where query based on a Coockie value like:

$brand = $request->cookie('brand');
// if value not set use default value.
if($brand == null)
{
  $brand = 1;
}

view()->composer('front.layouts.menu', function ($view) {
        //extra where function
        $view->with('menuItems', \App\MenuItem::Where('brand','=',$brand)->orderBy('priority', 'asc')->get());
 });

How can I get the coockie value in the compose function? Is there a special way to pass Request to my composeNavigation function?

EDIT i got it working but i cant access $brand in view()->composer(), if i copy my code inside the function i cant access request

My updated code :

public function boot(Request $request)
{
    $this->composeNavigation($request);
}
public function composeNavigation(Request $request)
{
   $coockieValue = $request->cookie('brand');
    // if value not set use default value.
    if($coockieValue == null)
    {
        $coockieValue = null;
    }
    $brands = \App\Brand::orderBy('priority', 'asc')->get();
    foreach($brands as $brand){
        if($brand->id == $coockieValue){
            $brand->menuActive = true;
        }
        else{
            $brand->menuActive = false;
        }
    }


    view()->composer('front.layouts.menu', function ($view) {
        $view->with('brandItems',$brands );
    });
}
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • 2
    `function ($view) use ($brand)` will make `$brand` available in the scope of the composer Closure. If you want to get access to the request object you can use the IoC container `$request = app('request');` or using DI and just adding `composeNavigation(Request $request)` – Ben Swinburne Oct 19 '15 at 09:59
  • It worked, however the cookie value is not readable. – Sven van den Boogaart Oct 19 '15 at 11:04
  • made another question on that subject http://stackoverflow.com/questions/33212802/laravel-cookie-in-compose-not-readable – Sven van den Boogaart Oct 19 '15 at 11:08

0 Answers0