Search code examples
laravellaravel-5laravel-5.1laravel-5.3

Is there any way to pass variable in rememberForever callback?


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?


Solution

  • 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.