Abdallah Sakre
Abdallah Sakre

Reputation: 915

How to pass an array from a query inside a foreach

I have the following query that will bring all Auth user friends :

$usrusrmembs = DB::table('usrusrs')
                    ->where('accepted', 1)
                    ->where('user_id', $u_id)
                    ->orwhere('friend_id', $u_id)                   
                    ->pluck('friend_id', 'user_id');

Next is a foreach to loop the ids received from the above query, get the posts of all Ids, and then sending the result to a blade :

foreach($usrusrmembs as $key => $val){

       $rec_users = ($key == $u_id) ? $val : $key;  

      $f_usrs_psts = DB::table('posts')      
            ->where('posts.user_id', $rec_users)
            ->get();

                                      }

return view('updates', ['f_posts' => $f_usrs_psts] );

The output in the blade shows only posts of one friend , while ignores the others. I feel there is a problem in the posts query, where it only sends to the blade the last processed ID. If this is the problem, then how can I solve it ?

Upvotes: 0

Views: 209

Answers (1)

Watercayman
Watercayman

Reputation: 8178

This is where Laravel really shines. Take advantage of the relationships and do this all in one query with eager loading. I don't know what your model relations are, but something like this:

$usrusrmembs = \App\UserUserModel::where('accepted', 1)
                ->where('user_id', $u_id)
                ->orwhere('friend_id', $u_id)                   
                ->with('posts')
                ->get();

If you want more control, you can use a combination of closures and whereHas, but this above should get you close. Then, in your view you can loop on the posts for each:

  @foreach($usrusrmembs as $usr)
      echo $usr-name // etc
      @foreach ($usr->posts as $post)
          echo $post->whatever
      @endforeach
  @endforeach

This is not going to give you exactly what you need, but the idea should help you to work through it and you can skip the whole n+1 issue by removing the foreach loop in your controller.

Upvotes: 2

Related Questions