如何设置和获取cookie?

时间:2017-01-11 11:10:33

标签: laravel laravel-5 laravel-5.2

我有这个功能,但问题是我从来没有得到第一部分,它就像没有cookie。任何建议我如何解决这个问题?

  public function downvote(Request $request){

       $comment_id = $request->comment_id;
      if(!Cookie::has('vote_' + $comment_id)){
         Cookie::forever('vote_' + $comment_id, $comment_id);
         return response()->json(['already_voted' => true],200);
      }
      else{
        $comment = ArticleComments::findOrFail($comment_id);
        $comment->downvotes -= 1;
        $comment->save();
        return response()->json(['downvote_value' => $comment->downvotes],200);

      }
    }

1 个答案:

答案 0 :(得分:2)

您必须创建一个烹饪并将其与您的回复一起发送:

public function downvote(Request $request)
{
    $comment_id = $request->comment_id;
    $cookie_id = 'vote_' + $comment_id;

    if ($request->cookie($cookie_id)) {
        return response()->json(['already_voted' => true], 200)
    } else {
        $comment = ArticleComments::findOrFail($comment_id);

        $comment->downvotes -= 1;

        $comment->save();

        return response()
                ->json(['downvote_value' => $comment->downvotes],200)
                ->cookie(Cookie::forever($cookie_id, $comment_id));
    }
}

检查文档:https://laravel.com/docs/5.3/requests#cookies