You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何比较时间戳?请求校验登录前日期判断代码

Laravel日期校验代码分析与修正

现有代码的问题

你提供的代码逻辑不符合业务规则,存在以下问题:

  • 错误使用activated_at直接计算有效期,未用到规则中定义的end_date字段,忽略了管理员停用用户时的end_date更新逻辑
  • 比较逻辑倒置:activated_at->gte(now()->subDays(90))表示激活时间在90天前至今,此时返回错误,和你要校验"用户不可登录"的逻辑完全相反

符合业务规则的登录前校验逻辑

根据你给出的业务规则,正确的校验需围绕end_date和用户状态实现,示例代码如下:

// 未激活用户直接拦截登录
if (!$user->is_active) {
    return $this->sendError('messages.user_not_activated', [], 400);
}

// 校验当前日期是否超出有效期限(订阅到期或已被停用)
if (now()->gte($user->end_date)) {
    // 若当前日期等于停用日期,执行对应逻辑
    if (now()->isSameDay($user->end_date) && $user->deactivated_at) {
        // 比如自动标记用户状态为停用
        // $user->update(['is_active' => false]);
    }
    
    return $this->sendError('messages.user_subscription', [], 400);
}

配套字段更新逻辑

确保管理员操作时end_date字段正确更新:

  • 激活用户时:$user->update(['end_date' => now()->addDays(90), 'is_active' => true]);
  • 停用用户时:$user->update(['end_date' => now(), 'deactivated_at' => now(), 'is_active' => false]);

内容的提问来源于stack exchange,提问作者Eziz SOYUN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:25:21