【问题标题】:Filtering collection with an array in laravel在laravel中使用数组过滤集合
【发布时间】:2018-11-13 06:45:57
【问题描述】:

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

【问题讨论】:

  • $loggedUserSites 是收藏吗?

标签: laravel laravel-collection


【解决方案1】:

你可以使用类似whereIn():

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

如果您使用 >= 5.3,您应该也可以删除 ->toArray() 方法。

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多