0

I have following code,

\Cache::rememberForever('Roles', function() {
    return RoleModel
        ::where('ParentRoleID' >= $CurrenctUserRoleID)
        ->get();
});

Issue is: I am getting Error

Undefined variable: CurrenctUserRoleID

Question: Is there any way to pass variable in callback?

Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • Does this answer your question? [Access variables from parent scope in anonymous PHP function](https://stackoverflow.com/questions/15042197/access-variables-from-parent-scope-in-anonymous-php-function) – miken32 Dec 14 '20 at 19:41
  • Does this answer your question? [Callback function using variables calculated outside of it](https://stackoverflow.com/questions/4588714/callback-function-using-variables-calculated-outside-of-it) – mickmackusa Mar 25 '23 at 05:30

2 Answers2

3

You may try this (Notice the use of use keyword):

$CurrenctUserRoleID = 1; // Some id

\Cache::rememberForever('Roles', function() use($CurrenctUserRoleID) {
    return RoleModel
    ::where('ParentRoleID' >= $CurrenctUserRoleID)
    ->get();
});

Check the PHP manual: Inheriting variables from the parent scope.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
1

PHP.net - anonymous functions - Example #3

You aren't passing anything with the callback as you are not the caller of that callback. You are telling PHP to use a variable from the parent scope.

function (...) use (...) { ... }
lagbox
  • 48,571
  • 8
  • 72
  • 83