如何在laravel 5.4中使用cookie来存储数据

时间:2017-09-09 08:16:44

标签: php cookies laravel-5

我正在创建一个需要存储用户信息并保存到cookie的网站。 这是我的获取cookie控制器

public function index($id, Request $request)
{    
    $petitions = Petitions::where('id',$id)->first();
    $sign->name  = $request->cookie('name'); 
    $sign->email = $request->cookie('email');

    return view('petitions.index', compact('petitions'))->with(['name'=>$sign->name,'email'=>$sign->email]);
}

这里是设置cookie控制器

public function store(Request $request)
{
    $sign = new ActionUsers();

    $sign->name = $request->get('name');
    $sign->email = $request->get('email');
    $sign->job = $request->get('job');
    $sign->reason = $request->get('reason');
    $sign->ip_address = $request->get('ip_address');
    $sign->petition_id = $request->get('petition_id');
    $sign->is_anonymous = $request->get('is_anonymous');

    $sign->save(); 

    $name_cookie = cookie('name', $sign->name, 30);
    $email_cookie = cookie('email', $sign->email, 30);

    return back()->withCookie($name_cookie,$email_cookie);
}

我查看存在Cookie的观点

@if( isset($sign->name)  &&  isset($sign->email) )
    done!
@else Oops! Error

并返回错误在$ sign-> name = $ request-> cookie(' name')中从空值创建默认对象;     $ sign-> email = $ request-> cookie(' email');

任何人帮我解决这个问题!谢谢

2 个答案:

答案 0 :(得分:0)

尝试以商店函数返回:

return back()->withCookie($name_cookie)->withCookie($email_cookie);

答案 1 :(得分:0)

有几种方法可以做到这一点:

$response = new \Illuminate\Http\Response(view('your_view'));
$response->withCookie(cookie('cookieName' , 'cookieValue' , expires_in_minutes));
return $response;

\Cookie::queue('cookieName', 'cookieValue', expires_in_minutes);
return view('your_view');

您也可以使用此代码获取Cookie:

$request->cookie('coockieName');