How to 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.


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;
   }