I would like to set and get value in cookie but it doesn't work:
Cookie::queue('online_payment_id', "1", 15);
$value = Cookie::get('online_payment_id');
dd($value);
dd()
returns null
;
I used below way but I got this message:
Method cookie does not exist.
request()->cookie('online_payment_id');
$value = response()->cookie('online_payment_id', "1", 15);
dd($value);
Creating a CookieCookie can be created by global cookie helper of Laravel. It is an instance of Symfony\Component\HttpFoundation\Cookie. The cookie can be attached to the response using the withCookie() method. Create a response instance of Illuminate\Http\Response class to call the withCookie() method.
For Creating cookies in Laravel we use Cookie::make() method and for reading cookie we use Cookie::get() method. Basically the Cookie::get() method is a wrapper over Request::cookie().
If you check out the Cookie class now you can use Cookie::has('cookieName'); class Cookie extends Facade { /** * Determine if a cookie exists on the request. * * @param string $key * @return bool */ public static function has($key) { return ! is_null(static::$app['request']->cookie($key, null)); } // ...
Laravel ships with several great drivers out of the box: file - sessions are stored in storage/framework/sessions . cookie - sessions are stored in secure, encrypted cookies. database - sessions are stored in a relational database. memcached / redis - sessions are stored in one of these fast, cache based stores.
Set Cookies
public function setCookie(Request $request){
$minutes = 60;
$response = new Response('Set Cookie');
$response->withCookie(cookie('name', 'MyValue', $minutes));
return $response;
}
Get Cookie
public function getCookie(Request $request){
$value = $request->cookie('name');
echo $value;
}
public function setCookie(Request $request) {
Cookie::queue('name', $request->test, 10);
return view('home');
}
Here Cookie::queue($cookie_name, $data, $life_time_of_this_cookie);
and simply print cookie where you want to show data.
{{ Cookie::get('name') }}
You can read from here Laravel Cookie Example | Set and Get Cookie in Laravel
Even if you carefully follow the Laravel documentation regarding how to set cookies, you may end up going crazy for hours (as I did today) because you just can't get your cookies set!
I finally discovered why my cookies weren't being set... I was also using the dump()
function to display data while I tested the code. The dump()
function sends output to the browser, which requires headers to be sent. Cookies also have to be sent with the headers, so if you're using dump()
, your cookies will never be sent!
I hope this helps others who will very likely run into this situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With