Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nikocraft's avatar

how to pass variable to Cache::remember('key', 15, function()

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:

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?

0 likes
3 replies
ohffs's avatar
ohffs
Best Answer
Level 50

I think you need PHP's use clause, like :

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

That worked I have now another problem. How do I solve this:

        Cache::remember('thumb-'.$hash, 15, function() use($hash) {
            $image = Image::where('hash', $hash)->first();
        });
        // return ImgResizer::make($image->hash . '.jpg')->response($image->extension);

        if($image == null)
        abort(404, 'The image you are looking for could not be found.');

gives me ErrorException in ImageController.php line 73: Undefined variable: image

How can I access $image?

nikocraft's avatar

solved it

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

Please or to participate in this conversation.