- カテゴリ: helper
 - 掲載バージョン: Laravel 12・PHP 8.4
 - 名前空間 / FQCN / コマンド: 
cache()(グローバル関数) - 関連: Cache ファサード / remember / rememberForever / put / forget
 - 変更履歴: Laravel 5.8 以降、TTLは「秒」単位に統一
 
要点(TL;DR)
- 取得・保存・Repository取得を1つの関数で行うためのヘルパー
 cache('key', 'default')/cache(['key' => 'value'], 300)/cache()->remember('key', 300, fn()=>...)- 罠:TTLは秒/
0や負数は即時失効/hasはnull値を「なし」と判定(existsを使う) 
概要
cache() はキャッシュ操作の最短手段です。引数なしで呼ぶとキャッシュ Repository(Illuminate\Contracts\Cache\Repository)を返し、メソッド連鎖で高度な操作ができます。文字列キーで呼べば取得、配列で呼べば保存というオーバーロード風の使い分けが特徴です。
構文 / シグネチャ
// 取得:見つからない場合は $default を返す
mixed cache(string $key, mixed $default = null);
// 保存:複数キーも可。$ttl は秒 or 日時/間隔
bool cache(array $keyValue, int|\DateInterval|\DateTimeInterface $ttl);
// Repository 取得:ストア選択や remember 等に利用
Illuminate\Contracts\Cache\Repository cache();
- 引数(表)
 
| 引数 | 型 | 必須 | 既定値 | 説明 | 
|---|---|---|---|---|
| keyOrPairs | string | array | null | いいえ | null | 取得時はキー(string)。保存時は ['key' => 'value', ...]。未指定なら Repository を返す。 | 
| defaultOrTtl | mixed | int | DateInterval | DateTimeInterface | null | いいえ | null | 取得時は既定値。保存時はTTL(秒/日時/間隔)。 | 
- 戻り値:取得時は 
mixed、保存時はbool、引数なしはRepository - 例外/副作用:無効なTTL指定で 
InvalidArgumentException等/選択したストア(file/redis等)へI/O/値はシリアライズ保存 
使用例
最小例
<?php
$value = cache('user:1:name', 'guest');    // 取得(なければ 'guest')
cache(['user:1:name' => 'Alice'], 300);    // 5分保存
実務例(重いDB結果をキャッシュ)
<?php
use Illuminate\Support\Facades\DB;
$report = cache()->remember('reports:monthly:2025-09', 1800, function () {
    return DB::table('orders')
        ->selectRaw('count(*) as cnt, sum(amount) as total')
        ->whereBetween('created_at', ['2025-09-01', '2025-09-30'])
        ->first();
});
// 別ストア(Redis)を明示
cache()->store('redis')->put('flags:feature_x', true, 60);
よくある落とし穴・注意
- TTLは秒:分と誤認しやすい。
300は5分。 - 0/負数のTTL:即時失効扱い。無期限は 
rememberForever()/forever()を使用。 hasとexists:has('k')はnull値を「なし」と判定。nullも区別したいならexists('k')。- シリアライズ前提:クロージャやDBコネクタ等、非シリアライズな値は保存不可。DTOや配列に落とす。
 - ストア依存:file ドライバはパーミッション、redis/memcached は接続設定に注意。
 
代替・関連APIとの比較
cache()vsCacheファサード:機能は同等。1行で完結したいならcache()、型補完やIDE支援を重視するならCache。cache([...], $ttl)vscache()->putMany([...], $ttl):複数保存はどちらでもOK。明示性は後者。remember系:計算を一度だけ実行して保存する用途に最適。更新頻度が低い重処理はremember/rememberForeverを優先。
テスト例(Pest)
<?php
use Illuminate\Support\Facades\Config;
it('stores and gets value via helper', function () {
    Config::set('cache.default', 'array'); // テストは揮発性の array ドライバに
    expect(cache(['foo' => 'bar'], 60))->toBeTrue();
    expect(cache('foo'))->toBe('bar');
});
it('returns default when missing', function () {
    Config::set('cache.default', 'array');
    expect(cache('missing', 'fallback'))->toBe('fallback');
});
トラブルシュート(エラー別)
| 症状/エラー | 原因 | 対処 | 
|---|---|---|
Class "Memcached" not found | memcached拡張未導入 | PHP拡張を導入するか、config/cache.php で別ドライバへ変更 | 
Redis connection refused | 接続先未起動/認証不備 | config/database.php の redis 設定とサーバ起動・認証を確認 | 
Serialization of 'Closure' is not allowed | 非シリアライズ値を保存 | クロージャを実行して値へ展開、DTO/配列へ変換して保存 | 
| 値が即時に消える | TTLを 0/負数で保存 | TTLを正の秒数に、無期限は rememberForever/forever | 
has が false だがキーはある気がする | 値が null | exists を使う/nullを避けて明示値を保存 | 
カテゴリ別の追記(helper)
- フレームワーク依存:
cache()はサービスコンテナから Repository を解決。環境設定(.env/config/cache.php)に従う。 - コンテナ/グローバル状態:同一プロセス内では同一 Repository を共有。ストア切替は 
cache()->store('redis')。 - 純PHP代替:単体スクリプトでは APCu / Symfony Cache / PSR-16 実装を検討。Laravel外では 
cache()は利用不可。 
参考リンク
- Laravel Docs — Cache(公式): https://laravel.com/docs/cache
 - Laravel Docs — Helpers(公式): https://laravel.com/docs/helpers
 - API — 
Illuminate\Contracts\Cache\Repository: https://laravel.com/api/11.x/Illuminate/Contracts/Cache/Repository.html - 設定ファイル 
config/cache.php(公式リポジトリ): https://github.com/laravel/laravel/blob/12.x/config/cache.php 

  
  
  
  