简体   繁体   中英

Why are my cookies not persisting in Laravel (using Homestead, Vagrant)?

I've been using Laravel from command prompt in Windows 10, but the difficulty of switching between projects has made me switch to using Homestead . However, in a new project I have started there, I can't for the life of me get cookies to persist. Here is my current code (for debugging this problem only):

use Illuminate\Support\Facades\Cookie;

// ......

public function __construct(Request $request) {
    $customer_id = Cookie::get('customer_id');
    if(!$customer_id) {
        Cookie::queue('customer_id', time(), 3600);
    }
    dd($customer_id);
}

Expected output: On consecutive page loads, the visitor will see the same unix timestamp they initially opened the page at (I understand this is not a good way of handling it, again, this is just for reproducing the error.)

Reality: Every pageload will produce a different timestamp.

I've looked up as many discussions as I could find. Solutions that I tried:

  • Using the Route method of declaring cookies
  • Using good-old PHP setcookie
  • Using Cookie:make, and Cookie:forever
  • Adding 'customer_id' in the exceptions among EncryptCookies
  • Placing the route in the web middleware
  • Erasing php artisan cache, restarting vagrant
  • Making the session folder editable through chmod

Yet still, after applying all the above, the cookie is still gone after every page load.

Since I had no prior problem like this through Xampp's PHP, I have to assume there is a (hopefully) trivial and obvious problem with Vagrant that I don't yet know. Any advice is appreciated!

Queued cookies are only sent with responses, so be sure that your controller function does return one.

use Illuminate\Support\Facades\Cookie;

// ......

public function __construct(Request $request) {
    $customer_id = Cookie::get('customer_id');
    if(!$customer_id) {
        Cookie::queue('customer_id', time(), 3600);
    }
}

public function foo() {
    ...

    return response('some text');
}

Also, if using some kind of api you have to add a middleware to include the cookies on the response. See Laravel 5.4 - Cookie Queue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM