2

I have a function like this:

public function entity($entity_id, Request $request)
{
    $expiresAt = Carbon::now()->addMinutes(10);
    $entity = Cache::remember('entities', $expiresAt, function () {
        return Entity::where('id', $entity_id)
            ->with('address')
            ->with('_geoloc')
            ->first();
    });

However this returns an error saying, $entity_id is undefined, however when I do dd($entity_id) after $expiresAt, it is defined as I get the id back, id comes from url if that is needed.

2 Answers 2

5

You should allow anonymous function to capture the variable outside the scope. $entity_id its outside the scope. This is how php express the closure. With a use() would work.

public function entity($entity_id, Request $request)
{
$expiresAt = Carbon::now()->addMinutes(10);
$entity = Cache::remember('entities', $expiresAt, function () use($entity_id) {
    return Entity::where('id', $entity_id)
        ->with('address')
        ->with('_geoloc')
        ->first();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, will accept this once I can, +1 for explaining in a bit more details
Thank you :) I appreciate it
2

You have to add use($entity_id) because that variable is outside the scope of the annonymous function it needs to be passed in using the use keyword as shown in the example below :

public function entity($entity_id, Request $request)
{
    $expiresAt = Carbon::now()->addMinutes(10);
    $entity = Cache::remember('entities', $expiresAt, function ()use($entity_id) {
        return Entity::where('id', $entity_id)
            ->with('address')
            ->with('_geoloc')
            ->first();
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.