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

时间:2016-09-28 13:17:17

标签: laravel

Laravel docs给出了这个例子:

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

就我而言,我有

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

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

Cache::remember('thumb-'.$hash, 15, function($hash)

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

  

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

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

1 个答案:

答案 0 :(得分:25)

您需要使用use传递它。

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