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

如何在Laravel中提取请求参数里日期的from和to值?

Laravel从请求参数的date对象提取起始/结束日期

你可以通过以下几种方式从请求的date对象中提取from和to日期:

基础提取方式

如果前端传递的date是JSON对象或嵌套表单参数,Laravel会自动解析为数组或对象,直接使用以下方式即可获取:

public function index(Request $request)
{   
    // 方式1:数组索引访问
    $from = $request->date['from'];
    $to = $request->date['to'];

    // 方式2:Laravel请求点语法(推荐,支持默认值)
    $from = $request->input('date.from');
    $to = $request->input('date.to');

    // 方式3:对象属性访问(当date被解析为对象时可用)
    $from = $request->date->from;
    $to = $request->date->to;

    // 后续可根据业务逻辑使用$from和$to
}

带默认值的安全提取

为避免参数缺失导致报错,建议使用input()方法设置默认值:

public function index(Request $request)
{   
    // 示例:默认值设为当月第一天和当天
    $from = $request->input('date.from', now()->startOfMonth()->toDateString());
    $to = $request->input('date.to', now()->toDateString());
}

日期格式转换(可选)

如果需要将提取的日期转换为标准数据库格式(如Y-m-d),可以结合Carbon处理:

use Carbon\Carbon;

public function index(Request $request)
{   
    $from = Carbon::createFromFormat('Y/m/d', $request->input('date.from'))->format('Y-m-d');
    $to = Carbon::createFromFormat('Y/m/d', $request->input('date.to'))->format('Y-m-d');
}

内容的提问来源于stack exchange,提问作者Malik Zubair Mukhtar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:19:55