doushang3352 2016-10-30 01:22
浏览 27
已采纳

怎么做“如果firstOrNew然后增加”?

I am currently building a website with a table that counts how many times the users used the coupon.

This is the line that I used to increment. It worked well but it increments every time the page was refreshed.

\App\Coupon::where('coupon_id','=',$coupon[0]->coupon_id)->increment('no_paid');

I wanted this to increment only once even though the page was refreshed multiple times. Please help me :)

  • 写回答

1条回答 默认 最新

  • doubiaokai4998 2016-10-30 01:45
    关注

    You can use a session for that. Here's an example (using Laravels global session helper):

    if (!session()->has('coupon_used')) {
        \App\Coupon::where('coupon_id','=',$coupon[0]->coupon_id)->increment('no_paid');
        session()->put('coupon_used', true);
    }
    

    This first checks if the session exists. If it doesn't, it runs the code and sets the session. The second time the page is loaded, the session will be set and the code won't run.

    Alternatively

    The above code only allows for one coupon per user session, regardless if they try different coupon ID's. If you want to add the same functionality, while allowing different coupons (being able to increment once/coupon id), then you can do this:

    if (!session()->has('coupon_' . $coupon[0]->coupon_id)) {
        \App\Coupon::where('coupon_id','=',$coupon[0]->coupon_id)->increment('no_paid');
        session()->put('coupon_' . $coupon[0]->coupon_id, true);
    }
    

    This does the same thing, but sets a session for just that coupon ID (since it dynamically creates the session name to have the ID appended).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊