Laravel cookie in serviceprovider not comparable

2019-06-08 19:08发布

I try to pass a variable based on a cookie value in my compose function to all my view to build my menu, with the use of serviceproviders recommmended here:

File: Providers/ViewComposerServiceProvicer.php

public function boot(Request $request) { $this->composeTopBar($request);}

public function composeTopBar(Request $request)
{
     $cookieValue = $request->cookie('brand');
    // if value not set use default value.
    if($cookieValue == null)
    {
        $cookieValue = 1;
    }
    $brands = \App\Brand::orderBy('priority', 'asc')->get();
    foreach($brands as $brand){
        if($brand->id == $cookieValue){
            $brand->menuActive = true;
        }
        else{
            // show value to debug
            $brand->menuActive = $cookieValue;
        }
    }


    view()->composer('front.layouts.top', function ($view) use ($brands) {
        $view->with('brandItems',$brands );
    });
}

the cookieValue looks like

yJpdiI6IlNJODBvQ1RNM004OWVleyJpdiI6IlNJODBvQ1RNM004OWVleyJpdiI6IlNJODBvQ1RNM004OWVl

While the value in my controller looks like '2' How can i get the original value 2 in my compose function?

I need to get the original value to compare it in my composeTopBar function so I can pass a variable to be true if it equals the cookie value.

Method to set cookie

    $response = response()-> view('front.products.category', compact('products','category'));
    $response->withCookie(cookie()->forever('brand',1));
    return $response;

2条回答
手持菜刀,她持情操
2楼-- · 2019-06-08 19:42

I ended up using a class based composer . The reason why this works is because it's called later in the lifecycle of laravel and the Cookie variables are decrypted. When using Closure based composers the values are encrypted.

查看更多
做个烂人
3楼-- · 2019-06-08 20:05

Try this: put the view() call as a parameter to response().

$response = response(view('front.products.category', compact('products','category')));
$response->withCookie(cookie()->forever('brand', 1));
return $response;
查看更多
登录 后发表回答