laravel - 检查是否定义了会话变量
问题描述
我需要计算观看次数。我正在使用会话变量来避免重复计数。我需要检查会话 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();
}
解决方案
你不能就这样吗
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')) {
//
}
推荐阅读
- c# - 多维关系松散与包装器的关系
- spring-boot - Spring Data Pagination GroupBy
- sql - SQL 查询 SQL SSRS
- excel - 使用 Excel VBA 在 Web 表单中选择列表选项(onchange)
- php - 在 prestashop 1.7 的表单文本字段中显示配置值
- docker - 在容器内运行的 Airflow 任务未启动
- python - Pandas:日期时间索引系列到时间索引日期列数据框
- java - 如何让两个图像在匹配时保持不变并在它们不匹配时翻转(记忆匹配游戏)?
- c++ - 更改其子类中的 QPushButton 区域掩码以创建 RoundButton
- mysql - Mysql显示四(4)位数字