繁体   English   中英

Laravel中没有设置cookie

[英]Cookie not getting set in laravel

很难检查Cookie是否存在,然后创建/更新Cookie。 这是为了检查用户是否在网站上选择了货币首选项,如果是,则将其保存到Cookie和会话中。 为此,我编写了以下辅助函数。

use Log;
use App\Currency;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Cookie;

function store_currency($prefCurrency = null)
{
    // If not passed, get from context
    if( empty($prefCurrency) ){
        if(request()->has('store_currency')){
            $prefCurrency = request('store_currency');
        } elseif (session()->has('store_currency')) {
            $prefCurrency = session('store_currency');
        } elseif (request()->hasCookie('store_currency')) {
            $prefCurrency = cookie('store_currency');
        } else {
            $prefCurrency = env('APP_DEFAULT_CURRENCY');
        }
    }

    // Uppercase it
    $prefCurrency = strtoupper($prefCurrency);

    // Is this an active currency?
    try{
        $c = Currency::findOrFail($prefCurrency);
    }catch(ModelNotFoundException $mnfe){
        $prefCurrency = env('APP_DEFAULT_CURRENCY');
    }

    // Update the context
    //dump('Currency set to: ' . $prefCurrency);
    Cookie::forever('store_currency', $prefCurrency);
    session()->put('store_currency', $prefCurrency);

    // prints null always :(
    //Log::debug('cookie: ' .  Cookie::get('store_currency') );

    return $prefCurrency;
}

这是我从控制器方法调用此帮助器函数的方式。

public function order(Request $request, $currency = null)
{
    $currency = store_currency($currency);

    $plans = ServicePlan::popuplarPlansForHome('UNL', 5)->get();
    $selectedPlan = $request->plan_id ? : '';
    $right_now = Carbon::now();
    return view('checkout/order', compact('plans', 'selectedPlan', 'right_now'))
        ->withCookie(Cookie::forever('store_currency', $currency));
}

好像我在这里缺少什么,请帮忙。 没有错误,但没有显示Cookie。

PS和路由声明如下:

Route::group(['middleware' => 'web'], function () {
    Route::get('checkout/order/{currency?}', 'CheckoutController@order')->name('newOrder');
});

此外,当我尝试从视图中转储cookie时,会看到以下内容:

store_currency=deleted; expires=Tue, 03-Mar-2015 10:43:39 GMT; path=/; httponly

解决了

这是新的控制器方法,它就像一个魅力。 此前,该Cookie未附加到响应中。

public function order(Request $request, $currency = null)
{
    $currency = store_currency($currency);

    $plans = ServicePlan::popuplarPlansForHome('UNL', 5)->get();
    $selectedPlan = $request->plan_id ? : '';
    $right_now = Carbon::now();
    return response()->view('checkout/order', compact('plans', 'selectedPlan', 'right_now'))
        ->withCookie(Cookie::forever('store_currency', $currency));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM