2016-03-02 214 views
0

越來越設置有一個艱難的時間,如果cookie存在檢查,然後創建/更新相同。這是爲了檢查用戶是否在網站上選擇了貨幣首選項,如果是,請將其保存到Cookie和會話中。爲此,我寫了以下幫助函數。餅乾不laravel

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?}', '[email protected]')->name('newOrder'); 
}); 

此外,當我試圖轉儲從這裏來看cookie是我所看到的:

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

做你的路線有網絡中間件?在5.2 –

+0

是新@AmirBar是的,它有以下幾點: \t路線::組([ '中間件'=> '捲筒紙'],函數(){ \t \t路線::得到('結帳/順序/ {貨幣?}」, 'CheckoutController @順序') - >名稱( 'newOrder'); \t}); – mishka

回答

0

解決

這裏是新的控制器方法,它的作用就像一個魅力。早些時候,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)); 
}