duanou9739 2019-03-25 16:03
浏览 149

将Laravel特定会话变量设置为在一段时间后过期

Im working on the Statistics page on my site, and I need to keep the general session Variables to normal duration (ex: 120 min) But I also want to store some of my Variables so I wont have to do 8 SQL queries every page reload for example I want to save the user posts count for each of the past 30 days but its something that changes often so want to save it only for 10 minutes How can I make only specific Variables from the session to be removed after 10 minutes but keep the other alive?

I've thought about saving the last refresh time and every reload check if its been 10 minutes

Session::put('lastRefresh',  Carbon::now()->timestamp);

In Cache I would just do it

Cache::put('posts',  $posts, 10);

But its unique to each user so I can't And some times its just a big array (90 Items for 90 Days) So I can't use cookie :P

Just don't know if its the best or most efficient way to do so

  • 写回答

1条回答 默认 最新

  • dongliugu8843 2019-03-25 16:05
    关注

    As it's unique to each user, you could namespace the cache key to identify the user:

    Cache::put('user_' . auth()->user()->id . '_posts',  $posts, 10);
    
    or
    
    cache(['user_' . auth()->user()->id . '_posts' => $posts], 10);
    

    Then you can retrieve using:

    Cache::get('user_' . auth()->user()->id . '_posts');
    
    or
    
    cache('user_' . auth()->user()->id . '_posts');
    

    Note: If using laravel 5.8 the cache expiration is now in seconds and not minutes.

    评论

报告相同问题?

悬赏问题

  • ¥15 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?