如何将变量传递给Cache :: remember函数

nik*_*aft 10 laravel

Laravel文档给出了这个例子:

$value = Cache::remember('users', $minutes, function() {
    return DB::table('users')->get();
});
Run Code Online (Sandbox Code Playgroud)

就我而言,我有

public function thumb($hash, $extension)
{
    Cache::remember('thumb-'.$hash, 15, function() {
        $image = Image::where('hash', $hash)->first();
    });
Run Code Online (Sandbox Code Playgroud)

如果我跑了,我得到ErrorException in ImageController.php line 69: Undefined variable: hash.我试图将$ hash传递给函数,如下所示:

Cache::remember('thumb-'.$hash, 15, function($hash)
Run Code Online (Sandbox Code Playgroud)

但后来又出现了另一个错误:

缺少App\Http\Controllers\ImageController :: App\Http\Controllers {closure}()的参数1,在C:\ xampp\htdocs\imagesharing\vendor\laravel\framework\src\Illuminate\Cache\Repository.php中调用在316行并定义

如何传递参数,以便在查询中使用它?

use*_*496 29

你需要使用它use.

Cache::remember('thumb-'.$hash, 15, function() use ($hash) {
    $image = Image::where('hash', $hash)->first();
});
Run Code Online (Sandbox Code Playgroud)

  • 添加更多细节 - 这不是 Laravel 问题,这就是闭包/匿名函数在 PHP 中的工作方式。请参阅。[PHP 文档] (http://php.net/manual/en/functions.anonymous.php) (2认同)
  • php 8 你可以这样做:cache()->remember(key, value, fn() => dd($hash)); (2认同)