Rickin Rathatha
Rickin Rathatha

Reputation: 177

Laravel set cookie not working

I have the following code in a custom middleware:

public function handle($request, Closure $next)
{
    if($request->hasCookie('uuid')) {
        return $next($request);    
    }

    $uuid = 99;
    $response = $next($request);
    return $response->withCookie(cookie()->forever('uuid', $uuid));

}

I have registered the middleware in the app.php file, but cookies is still not being written. Please can anyone help. Additionally can this above be run as a singleton, so that it is executed once on app start?

Thanks

Upvotes: 1

Views: 21600

Answers (4)

Kingsley Uchenna
Kingsley Uchenna

Reputation: 700

You can use the laravel helper function cookie(). This worked for me.

<?php
//Create: 
cookie()->queue(cookie($name, $value, $minutes));
// forever
cookie()->queue(cookie()->forever($name, $value));
//get
request()->cookie($name);
//forget
cookie()->queue(cookie()->forget($name));

Upvotes: 1

Mohammad Naji
Mohammad Naji

Reputation: 5442

If you are on a local environment, make sure to set 'secure' => env('SESSION_SECURE_COOKIE', false), around lines #165-170 in your config/session.php file.

On a non-SSL domain (like http://localhost/), this directive must be false. Otherwise cookies will not be set in browser.

Upvotes: 7

Mayur Panchal
Mayur Panchal

Reputation: 655

You can obtain the response object in middleware like so:

public function handle($request, Closure $next)
{
    $response = $next($request);

    // Do something after the request is handled by the application

    return $response;
}

So you could do something like this

if($request->hasCookie('uuid')) {
    return $next($request);    
}

$uuid = Uuid::generate();
$response = $next($request);
return $response->withCookie(cookie()->forever('uuid', $uuid));

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

Add a following 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 sets and get a cookie.

Upvotes: 6

Related Questions