为什么Laravel的Cookie为空-5.7

时间:2018-12-10 17:43:56

标签: php laravel laravel-5

我的cookie为空!但我不知道:

use Illuminate\Support\Facades\Cookie;

HomeController:

public function index()
{
    Cookie::queue('currentLang', 'heb', 999999999);



      $cat1         = $this->categoryRepo->findCategoryById(1);
      $lastPosts    = $this->blogPosts->listBlogPosts(array('*'),'id','desc')->take(3);

    return view('front.index', compact('cat1','lastPosts'));
}

现在我想从另一个控制器获取此密钥:

LoginController:

public function showLoginForm()
{
    dd(Cookie::get('currentLang'));
    return view('auth.login');
}

但它返回null! 我正在使用localhost。

1 个答案:

答案 0 :(得分:0)

根据文档,

Cookie::queue(...用于将Cookie附加到您的响应(一种替代方法)上。如果检查响应头,您应该注意到Set-Cookie: currentLang=someencryptedvalue确实存在。

我创建了一些原型端点来说明如何创建和删除cookie:

use Illuminate\Support\Facades\Cookie;

Route::get('/wont-clear-cookie', function() {
    Cookie::forget('currentLang');

    return redirect()->to('/get-cookie');
});

Route::get('/clear-cookie', function() {
    Cookie::queue(Cookie::forget('currentLang'));

    return redirect()->to('/get-cookie');
});

Route::get('/set-cookie', function() {
    Cookie::queue('currentLang', 'heb', 999999999);

    return redirect()->to('/get-cookie');
});

Route::get('/get-cookie', function() {
    dump(Cookie::get('currentLang'));
    dd(request()->cookie('currentLang'));
});

以上端点应放在web.php中。

此外,请确保在web中正确配置了App\Http\Kernal.php中间件组:

'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    // \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],