Martin AJ
Martin AJ

Reputation: 6707

How can I get cookie in Laravel?

The title of my question seems duplicate, but it isn't. I've tested all existing approaches in the internet.

Here is my code:

dd($request->cookie('guarantee_ticket'));
// I also have tested this: dd(Cookie::get('guarantee_ticket'));

And the result is null, while that cookie is exists in the browser. I can see it:

enter image description here

Any idea how can I get the value of that cookie?

Upvotes: 0

Views: 5548

Answers (1)

Mayur Panchal
Mayur Panchal

Reputation: 655

Here, I'm mention set and get a cookie in laravel simple example following.

First of the create a controller.

1.php artisan make:controller CookieController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CookieController extends Controller {

  **/* below code a set a cookie in browser */**
   public function setCookie(Request $request){
      $response = new Response('Hello World');
      $response->withCookie(cookie('name', 'Anything else'));
      return $response;
   }
  **/* below code a get a cookie in browser */**
   public function getCookie(Request $request){
      $value = $request->cookie('name');
      echo $value;
   }
}

1. Add a follwing line code in routes/web.php file (Laravel 5.4)

Route::get('/cookie/set','CookieController@setCookie');

Route::get('/cookie/get','CookieController@getCookie');

And all files add-in project than a run program easily gets a cookie.

Upvotes: 2

Related Questions