Lucien Dubois
Lucien Dubois

Reputation: 1674

How to use Laravel Cache::remember with a callback function

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 ?

Upvotes: 0

Views: 660

Answers (1)

Coola
Coola

Reputation: 3142

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();
            })
          
    }
}

Upvotes: 1

Related Questions