phplaravellaravel-collection

Filtering collection with an array in laravel


I want to return the sites to which the logged user is only available for viewing. When a user access someone else's site and you are not within that group, you should not be able to view it. This should only return the sites that you are associated with. I have a unit test on this and it passes but it seems that there is a better way to do this. TIA

$user = $this->userRepo->findUserById($userId);

$userRepo = new UserRepository($user);

$sites = $userRepo->findSites();

$loggedUser = app('request')->user();

$loggedUserSites = $loggedUser->sites()->get()->all();

// Return only the sites of the user being access that is the same with the currently logged user
$sites = $sites->filter(function (Site $site) use ($loggedUserSites) {
    foreach ($loggedUserSites as $userSite) {
        if($site->id === $userSite->id) {
            return $site;
        };
    }
});

// user 1: [1,2,3] - `/users/2/sites` - should return [1,2] (default since user 2 is only associated with this 2 sites)
// user 2: [1,2] - `/users/1/sites` - should return [1,2] (no 3 since user has no site #3)

Solution

  • You could use something like whereIn():

    $sites = $sites->whereIn('id', $loggedUserSites->pluck('id')->toArray())->all();
    

    If you're using >= 5.3 you should be able to remove the ->toArray() method as well.