Reputation: 687
Having a tough time with checking if a cookie exists and then create/update the same. This is to check if user has selected a currency preference on the site and if yes, save that to a cookie and session. For this I've written the following helper function.
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;
}
Here is how I call this helper function from a controller method.
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));
}
Looks like I'm missing something here, please help. No errors but cookie doesn't show up.
P.S and the route is declared like below:
Route::group(['middleware' => 'web'], function () {
Route::get('checkout/order/{currency?}', 'CheckoutController@order')->name('newOrder');
});
Further, when I try to dump the cookie from a view here is what I see:
store_currency=deleted; expires=Tue, 03-Mar-2015 10:43:39 GMT; path=/; httponly
Upvotes: 1
Views: 2137
Reputation: 687
SOLVED
Here is the new controller method and it works like a charm. Earlier the cookie was not attached to response.
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));
}
Upvotes: 1