PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] How to use Laravel Cache::remember with a callback function

 February 12, 2022     laravel, laravel-8, laravel-cache     No comments   

Issue

I would like to reference a private function as the third parameter to the Cache::remember function.

Instead of this (try{}catch() was removed for a cleaner code):

class ApiController extends Controller
{

    public function index(){
        $data = Cache::remember('dataKey', 60, function () {
            return Model::multipleMethodsHere()->get();
        });
        return response()->json($data,200);
    }
}

I'd like to do this:

class ApiController extends Controller
{

    public function index(){
        $data = Cache::remember('dataKey', 60, $this->getIndex());
        return response()->json($data,200);
    }
    private function getIndex(){
        return Model::....->get();
    }
}

I got this error if I try to reference a private function.

Argument 3 passed to Illuminate\\Cache\\Repository::remember() must be an instance of Closure, instance of Illuminate\\Database\\Eloquent\\Collection given

Is it possible ? If yes, how should I do ?


Solution

Based on comments in the discussion to the OP, re-strategize the Cache:remember to be a part of the getIndex function like:

class ApiController extends Controller
{

    public function index(){
        $data = $this->getIndex();
        return response()->json($data,200);
    }

    private function getIndex(string $dataKey = 'dataKey', int $time = 60){
        return Cache::remember($dataKey, $time, function () {
               return Model::....->get();
            })
          
    }
}


Answered By - Coola
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing