phplaravelclosureseach

Laravel returning array from each() method


I am getting an array of permissions related to the roles of a specific user, mainly as a way to get my head around working with eager loading and the each() method

When creating a $permissions array in this manner, how would I actually be able to access the array outside the closure?

$user = User::with('roles.perms')->find(1);

$permissions = array();

$list = $user->roles->each(function($role) use($permissions)
{
    $permissions = array_merge($permissions, $role->perms->toArray());
});

Thanks!


Solution

  • Just pass the $permissions variable by reference:

    $user->roles->each(function($role) use(&$permissions) { //<-- passed by reference
        $permissions = array_merge($permissions, $role->perms->toArray());
    });
    

    Notice the &, now you have the same variable declared outside the function and it's in your current scope and modified inside the closure. SO, you can use the $permissions here, for example:

    dd($permissions); // dump and die