使用 laravel 中的数组过滤集合
Filtering collection with an array in laravel
我想return登录用户只能查看的站点。当用户访问其他人的站点而您不在该组中时,您应该无法查看它。这应该只 return 与您关联的网站。我对此进行了单元测试并且它通过了,但似乎有更好的方法可以做到这一点。 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)
你可以使用 whereIn():
$sites = $sites->whereIn('id', $loggedUserSites->pluck('id')->toArray())->all();
如果您使用的是 >= 5.3,您应该也可以删除 ->toArray()
方法。
我想return登录用户只能查看的站点。当用户访问其他人的站点而您不在该组中时,您应该无法查看它。这应该只 return 与您关联的网站。我对此进行了单元测试并且它通过了,但似乎有更好的方法可以做到这一点。 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)
你可以使用 whereIn():
$sites = $sites->whereIn('id', $loggedUserSites->pluck('id')->toArray())->all();
如果您使用的是 >= 5.3,您应该也可以删除 ->toArray()
方法。