PHP laravel How many days have passed before performing the operation?

use Illuminate\Support\Facades\Cache;

function queryCurrencyService(): JsonResponse
{
    $res = CurrencyName::query()
        ->select(['name', 'code'])
        ->get()
        ->toArray();

    // 获取上次拉取的时间
    $lastFetchedAt = Cache::get('last_fetched_at');

    $daysSinceLastFetch = $lastFetchedAt ? now()->diffInDays($lastFetchedAt) : null;

    // 检查是否需要拉取
    $shouldFetch = (!$res) || (!$lastFetchedAt) || ($daysSinceLastFetch && $daysSinceLastFetch > 3);

    if ($shouldFetch) {
        // 拉取数据的代码...

        // 更新上次拉取的时间,并缓存3天
        Cache::put('last_fetched_at', now(), 3 * 24 * 60); 
    }

    return response()->json($res);
}

Guess you like

Origin blog.csdn.net/mp624183768/article/details/133369010