Read and Write Cookie in laravel 5.4

Share:

Setting and getting cookie in Laravel 5.4

Hi Guys, in this post we are going to see how to read and write cookies in Laravel 5.4. In Laravel all cookies are encrypted and signed with an authentication code.They become invalid if client make any changes on created cookies. Below is code to get and set cookies in Laravel 5.4.
<?php
//adding cookie namespace.
use Illuminate\Cookie\CookieJar;

class CookieController extends Controller{

 public function setCookie(Request $request){
  $user_name=$request->input('user_name');
  $cookie_name="user_name";
  $cookie_value="PhpScots";
  $cookie_expired_in=3600;//in mins
  $cookie_path='/'; // available to all pages of website.
  $cookie_host=$request->getHttpHost(); // domain or website you are setting this cookie.
  $http_only=false;
//Creating cookie;
  $my_cookie= cookie($cookie_name, $cookie_value,$cookie_expired_in,$cookie_path,$cookie_host,$http_only);
// sending response to browser, make sure you send this, if you not send Laravel not able to identify this cookie.
  return response()->withCookie($my_cookie);

}

public function getCookie(){
// Getting saved cookie
return Cookie::get('user_name');
}

?>


No comments