首页 > 解决方案 > 检查是否定义了会话变量

问题描述

我需要计算观看次数。我正在使用会话变量来避免重复计数。我需要检查会话 view_count 是否设置,然后将其设置为 false 并增加视图计数

$currentPost = Post::where('slug',$slug)->first();
$comments =  \App\Comment::where('post_id',$currentPost->id)->get();

if(\Session::get('view_count')) {
    \Session::put('view_count', false);
    $currentPost->view_count = $currentPost->view_count + 1;
    $currentPost->save();
}

标签: laravel

解决方案


你不能就这样吗

if (Session::has('your_key'))
{
  //your code here
}

更新答案

确定会话中是否存在项目

要确定会话中是否存在项目,您可以使用 has 方法。如果项目存在且不为 null,则 has 方法返回 true:

if ($request->session()->has('users')) {
    //
}

要确定一个项目是否存在于会话中,即使它的值为null,您也可以使用该 exists方法。如果项目存在,exists 方法返回 true:

if ($request->session()->exists('users')) {
    //
}

推荐阅读