Home > OS >  How to use Laravel Cache::remember with a callback function
How to use Laravel Cache::remember with a callback function

Time:01-26

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 ?

CodePudding user response:

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();
            })
          
    }
}
  •  Tags:  
  • Related