Search code examples
phplaravelloopslaravel-5eloquent

while traversing through results in laravel in foreach loop it saves only last element in new array element?


My Controller

$followers = Followers::where('requested', $user->id)->where('status', 1)->get();

    foreach ($followers as $follower){

        $followerss = User::with('id', $follower->requester)->get();

    }

if I had two or more followers for that particular id, but im $followerss variable it stores only the last follower data but not previous data.

Thanks in advance <3


Solution

  • Thats because you are overwriting the value of variable $followerss with each iteration.

    You need to declare $followerss as an array before it enters the loop, then in the loop merge or push the items

    Push example:

    $followerss = [];
    
    foreach ($followers as $follower){
    
        $users = User::with('id', $follower->requester)->get();
        foreach($users as $user) {
            $followerss[] = $user;
        }
    
    }
    

    Merge example:

    $followerss = [];
    
    foreach ($followers as $follower){
    
        $followerss = array_merge($followerss, User::with('id', $follower->requester)->get());
    
    }