我正在为某些点击事件设置cookie.然后在cookie中存储值后,我想
>检查是否存在cookie
>获取cookie值
我通过参考Laravel官方文档开发了一个函数.控制台显示已设置cookie.但在那之后,我无法解决视图(Blade Template)中的两点(在上面的列表中提到).它总是显示(Cookie :: get(‘cookie.clients’))’null’.但浏览器控制台显示该cookie
.
如果有人知道答案,我们将不胜感激.
这是我的代码.
调节器
use App\Client; use App\Http\Requests; use Illuminate\Http\Request; use Validator; use App\Http\Controllers\Controller; use App\Repositories\ClientRepository; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cookie; class ClientController extends Controller { public function cookieadd(Request $request,Client $client) { $clients = []; if (Cookie::get('cookie.clients') != null) { $clients = Cookie::get('cookie.clients'); } array_push($clients,$client); Cookie::forever('cookie.clients',$clients); return redirect('/client'); } }
视图
@if (Cookie::get('cookie.clients') != null) <p>cookie is set</p> @else <p>cookie isn't set</p> @endif
您正在创建一个cookie对象,但是您没有通过响应发送它.
您可以将其直接添加到控制器中的响应中
$cookie = Cookie::forever('cookie.clients',$clients); return redirect('/client')->withCookie($cookie);
或者您可以对cookie进行排队并使用AddQueuedCookiesToResponse中间件自动将其添加到响应中.
Cookie::queue(Cookie::forever('cookie.clients',$clients)); return redirect('/client');