在 laravel 中使用数组过滤集合

问题描述 投票:0回答:1

我想返回登录用户只能查看的网站。当用户访问其他人的网站而您不在该组中时,您应该无法查看该网站。这应该只返回与您关联的网站。我对此进行了单元测试并且通过了,但似乎有更好的方法来做到这一点。 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)
php laravel laravel-collection
1个回答
1
投票

你可以使用类似 whereIn():

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

如果您使用 >= 5.3,您也应该能够删除

->toArray()
方法。

© www.soinside.com 2019 - 2024. All rights reserved.