Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass variable to Cache::remember function

Tags:

laravel

Laravel docs give this example:

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

In my case I have

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

If I run that I get ErrorException in ImageController.php line 69: Undefined variable: hash. I tried to pass $hash to function like so:

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

but then got another error as below:

Missing argument 1 for App\Http\Controllers\ImageController::App\Http\Controllers{closure}(), called in C:\xampp\htdocs\imagesharing\vendor\laravel\framework\src\Illuminate\Cache\Repository.php on line 316 and defined

How do I pass argument so I can use it in my query?

like image 488
niko craft Avatar asked Sep 28 '16 13:09

niko craft


1 Answers

You need to pass it using use.

Cache::remember('thumb-'.$hash, 15, function() use ($hash) {
    $image = Image::where('hash', $hash)->first();
});
like image 71
user1669496 Avatar answered Oct 20 '22 20:10

user1669496