1

I have a foreach loop where each time certain value is matched and then it related records is fetched

 foreach($results as $result){
    // Value may be 1,2,3 etc
    if($result->id == $value){
       $users = User::whereId($value)->get();
    }
  }
  return view('index',compact('users'));

Now how to pass all users records to the view? Currently it only fetches the first record!

Khirad Zahra
  • 843
  • 2
  • 17
  • 42

3 Answers3

1

You can store all id's in an array and then fetch all records at once. Running a database queries in a loop have a performance overhead.

$userIds = [];

foreach ($results as $result) {
    // Value may be 1, 2, 3 etc.
    if ($result->id == $value){
        $userIds[] = $value;
    }
}

$users = User::whereIn('id', $userIds)->get();

return view('index', compact('users'));
tooleks
  • 557
  • 5
  • 17
  • Perhaps you doesn't get my question,i don't all records,only that records that are matched with specific condition in loop.Please review the question,Thank you – Khirad Zahra Jul 31 '17 at 03:50
0

So what you want to do is:

  • Make a new array that holds arrays of users when it matches
  • Then return that new array

Example:

$matchedUsers = array();

foreach($results as $result) {
    // Value may be 1,2,3 etc
    if($result->id == $value) {
       $matchedUsers[] = User::whereId($value)->get();
    }
}
return view('index', compact('matchedUsers'));

An even cleaner way to do this is to have a seperate function that does your call for User Info when it matches:

public function getUsers($results)
{
    $matchedUsers = array();

    foreach($results as $result){
        // Value may be 1,2,3 etc
        if($result->id == $value) {
            $matchedUsers[] = User::whereId($value)->get();
        }
    }
    return view('index', compact('matchedUsers'));
}

public function getMatchedUser($userId)
{
    return User::whereId($userId)->get();
}
giolliano sulit
  • 996
  • 1
  • 6
  • 11
0

You can use "whereIn" for this purpose.

You can get further information from Laravel doc

$ids = [];

foreach ($results as $result) {

    if ($result->id == $value){
        $ids[] = $value;
    }
}

$users = User::whereIn('id', $ids)->get();

return view('index', compact('users'));
Asim Shahzad
  • 1,438
  • 11
  • 18