我想返回记录用户只能查看的网站。当用户访问其他人的网站但您不在该网站内时,您应该无法查看该网站。这应该只返回与您关联的站点。我有一个单元测试,它通过但似乎有一个更好的方法来做到这一点。 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)
答案 0 :(得分:0)
您可以使用类似whereIn()的内容:
$sites = $sites->whereIn('id', $loggedUserSites->pluck('id')->toArray())->all();
如果你使用> = 5.3,你也应该能够删除->toArray()
方法。