Thursday, 30 August 2018

Search using the foreach loop does not return to the first match

I want to get all records with the same refid but my foreach loop is just searching until it find the first record and halts.

$data = Projekt1Db::select('refid', 'userid', 'passwd', 'uid', 'gid', 'homedir')->get();
        $inputs = \Request::all();
        foreach ($data as $id) {
            if ($id->refid == $inputs['refid']){
                return view('searchfound', [
                    'id' => $id]);
            }
        }

        if($inputs !== $id){
            return redirect()->back()->with('message', 'Refid not found');
        }
    }

There are more records with the same refid, but it just gives me the first record with that refid.
In the view:
<b>Refid:</b> {{$id->refid}}<br>
<b>Userid:</b> {{$id->userid}}<br>
<b>Password:</b> {{$id->passwd}}<br>
<b>UID:</b> {{$id->uid}}<br>
<b>GID:</b> {{$id->gid}}<br>
<b>homedir:</b> {{$id->homedir}}<br><br>


Basic, change
foreach ($data as $id) {
  if ($id->refid == $inputs['refid']){
    return view('searchfound', [
      'id' => $id]);
  }
}

to
$data = array();
foreach ($data as $id) {
  if ($id->refid == $inputs['refid']){
    $data[] = $id;
  }
}
if (length($data) > 0) {
  var_dump($data);
} else {
  // nothing found
}

0 comments:

Post a Comment