发送时为什么我的收藏品是空的?

时间:2018-05-04 15:08:45

标签: php html laravel laravel-5

我正在使用Laravel 5,我的控制器中有以下方法:

/**
 * Display the specified resource.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $authUser =  Auth::user();
    $sharesList = Group::find($id)->shares->sortByDesc('created_at');
    $groupList = $authUser->groupsAsMember->where('id', '<>', $id);
    $group = $authUser->groups->find($id);
    $postList = Group::find($id)->posted->sortByDesc('created_at');

    $postsGroups = PostGroup::where('group_id', $id)->with('commented')->get();
    //$commentsList;

    foreach ($postsGroups as $postGroup) {
        $commentsList = $postGroup->commented;
        //dd($commentsList);
    }

    //dd($commentsList);
    return view('Pages.Group.detail', ['sharesList' => $sharesList, 'groupList' => $groupList, 'theGroup' => $group, 'postList' => $postList, 'commentsList' => $commentsList]);
}

问题出在$commentsList集合中,如果我在@foreach中放置一个dd($commentsList),我可以看到里面有我想要的元素,但如果我放dd($commentsList)在foreach之外(在@endforeach之后)$ commentsList是空的,它到达我的HTML页面是空的,我该如何解决? 我试图将$commentsList;放在@foreach循环之前,但仍无效。

修改

2 个答案:

答案 0 :(得分:6)

您应该在每次循环时覆盖它,同时应添加新的数组元素。试试这个:

/**
 * Display the specified resource.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $authUser =  Auth::user();
    $sharesList = Group::find($id)->shares->sortByDesc('created_at');
    $groupList = $authUser->groupsAsMember->where('id', '<>', $id);
    $group = $authUser->groups->find($id);
    $postList = Group::find($id)->posted->sortByDesc('created_at');
    $commentsList = collect();

    $postsGroups = PostGroup::where('group_id', $id)->with('commented')->get();

    foreach ($postsGroups as $postGroup) {
        foreach($postGroup->commented as $commentPost) {
            $commentsList->push($commentPost);
        }
    }

    //dd($commentsList);
    return view('Pages.Group.detail', ['sharesList' => $sharesList, 'groupList' => $groupList, 'theGroup' => $group, 'postList' => $postList, 'commentsList' => $commentsList]);
}

答案 1 :(得分:1)

正如您在评论中提到的那样,您需要收集数组,因此首先要初始化注释列表:

$commentsList = [];

然后:

foreach ($postsGroups as $postGroup) {
    $commentsList[] = $postGroup->commented;
}