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

Laravel如何仅展示近2个月数据?解决Carbon忽略年份问题

解决方案:筛选当年近2个月的销售订单数据

针对你的需求,这里提供两种可行方案,优先推荐API层面筛选(更高效),其次是本地数据过滤:

方案一:通过API参数直接筛选(优先使用)

如果外部API支持按日期范围查询,直接在请求时携带日期参数,让API返回符合条件的数据,避免本地处理大量冗余数据。

修改控制器代码如下:

use Carbon\Carbon;

public function index()
{
    // 1. 获取认证Token
    $response = Http::post('http://example.com/authenticate', [
        'Username' => 'ADMIN',
        'Password' => 'ADMIN',
        'Token' => 'FK98DL..',
    ]);
    $token = json_decode($response, true);

    // 2. 计算当年近2个月的日期范围:上个月第一天到当前月最后一天
    $startDate = Carbon::now()->subMonths(1)->startOfMonth()->format('Y-m-d');
    $endDate = Carbon::now()->endOfMonth()->format('Y-m-d');

    // 3. 携带日期参数请求API
    $apiURL = "http://example.com/api/SalesOrder/?startDate={$startDate}&endDate={$endDate}";
    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => $token,
    ];
    $response2 = Http::withHeaders($headers)->get($apiURL);
    $filteredData = $response2->json();

    // 4. 返回视图
    return view('api.auth.orders.index', compact('filteredData'));
}

视图代码只需遍历$filteredData即可:

@foreach ($filteredData as $item)
<tr>
    <td>{{ $item['DocDate'] }}</td>
</tr>                                             
@endforeach

方案二:本地过滤数据(API不支持参数时使用)

如果外部API无法按日期筛选,就在控制器中对返回的数据进行过滤,确保只保留当年近2个月的记录:

修改控制器代码如下:

use Carbon\Carbon;
use Illuminate\Support\Collection;

public function index()
{
    // 1. 获取认证Token
    $response = Http::post('http://example.com/authenticate', [
        'Username' => 'ADMIN',
        'Password' => 'ADMIN',
        'Token' => 'FK98DL..',
    ]);
    $token = json_decode($response, true);

    // 2. 请求全部订单数据
    $apiURL = 'http://example.com/api/SalesOrder/';
    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => $token,
    ];
    $response2 = Http::withHeaders($headers)->get($apiURL);
    $data = $response2->json();

    // 3. 计算目标年份和月份:当年的当前月与上月(1月时仅保留1月)
    $currentYear = Carbon::now()->year;
    $currentMonth = Carbon::now()->month;
    $targetMonths = $currentMonth == 1 ? [$currentMonth] : [$currentMonth - 1, $currentMonth];

    // 4. 过滤数据:匹配年份和目标月份
    $filteredData = collect($data)->filter(function($item) use ($currentYear, $targetMonths) {
        $docDate = Carbon::parse($item['DocDate']);
        // 同时验证年份和月份,避免跨年份的相同月份被错误保留
        return $docDate->year === $currentYear && in_array($docDate->month, $targetMonths);
    })->values()->all(); // 重置数组索引

    // 5. 返回视图
    return view('api.auth.orders.index', compact('filteredData'));
}

视图代码同样遍历$filteredData即可。

关键说明

  • 之前使用Carbon时忽略年份的问题,核心原因是只校验了月份未校验年份,上述方案中通过$docDate->year === $currentYear强制限制了年份,避免错误包含往年同月份的数据。
  • 如果DocDate的格式存在解析问题,可以在Carbon::parse()中指定格式,比如Carbon::createFromFormat('Y-m-d', $item['DocDate']),确保日期解析准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:36:07