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

Laravel+Vue两日期范围搜索无返回数据问题排查

Laravel+Vue日期范围筛选功能异常修复

现存问题汇总

代码一共存在5处逻辑错误,直接导致日期筛选失效:

  • 前端请求参数拼接错误:两个查询参数之间缺少&分隔符,拼接后的URL参数格式完全错误,后端无法正确获取search_date_to值
  • request()函数用法错误:后端request()传参格式不符合Laravel规范,仅会读取第一个参数字段,其余字段被当作默认值处理
  • 查询构造器when()逻辑错误:只要任意一个搜索参数存在,就会强制给所有字段加查询条件,空值参数会生成无效查询条件
  • whereBetween()参数错误:直接传入固定字符串'search_date_from'、'search_date_to',没有读取请求中传递的实际日期值
  • 日期边界处理缺失:即使参数正确,传入结束日期如2022-06-07时,仅会匹配到当天0点的时间,漏掉当天0点后创建的所有数据

分步修复方案

1. 修复前端请求传参

不要手动拼接URL参数,改用axios的params配置自动处理参数格式,同时把其他搜索字段也一并传入,避免其他搜索功能失效:

searchDateFrom(){
    axios.get('/api/auth/matter', {
        params: {
            search_client: this.search_client,
            search_file_ref: this.search_file_ref,
            search_file_status: this.search_file_status,
            search_date_from: this.search_date_from,
            search_date_to: this.search_date_to
        }
    })
    .then(response => this.matters = response.data)
},

2. 修复后端控制器逻辑

每个搜索条件单独判断是否存在再追加查询规则,日期范围查询需同时校验开始、结束日期存在才执行,同时补全结束日期的时间边界:

public function index() {
    $query = Matter::query();

    // 普通字段搜索:参数存在才加查询条件
    $query->when(request('search_client'), function($query){
        $query->where('client_company', 'like', '%' . request('search_client') . '%');
    });
    $query->when(request('search_file_ref'), function($query){
        $query->where('file_ref', 'like', '%' . request('search_file_ref') . '%');
    });
    $query->when(request('search_file_status'), function($query){
        $query->where('status', 'like', '%' . request('search_file_status') . '%');
    });

    // 日期范围搜索:两个日期都传值才执行,补全结束日期时间到当天23:59:59
    $query->when(request('search_date_from') && request('search_date_to'), function($query){
        $startDate = request('search_date_from');
        $endDate = request('search_date_to') . ' 23:59:59';
        $query->whereBetween('created_at', [$startDate, $endDate]);
    });

    return $query->orderBy('id','asc')->get();
}

3. 修正模型日期配置

模型中created_at的格式化配置不影响数据库查询,但返回给前端的日期格式带多余空格和斜杠容易引发解析问题,建议改成标准时间格式:

protected $casts = [
    'created_at' => 'datetime:Y-m-d H:i:s',
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 09:24:35