Adorablegh
Adorablegh

Reputation: 53

How to get data from a database using FOREACH in Laravel?

Please I have a health management system and trying to get data from the database using foreach. The return value is one array result instead of two. Kindly go through my code. I need assistance to display all results.

Controller.php

$result = \DB::table('patient_results')
        ->select('*')
        ->whereIn('test', $arraylistTable)
        ->where('patient_id', $id)
        ->where('specimen_id', $specimen_id)
        ->get();


        $testValue = $result->pluck('test'); //return values [ "KMS", "MLS"]
        
        foreach($testValue as $clinical_data) {

           return $Testdata = \DB::table('tests')
            ->select('*')
            ->where('test_name', $clinical_data)
            ->get();            
           // returns data for only "KMS" Instead of both. There exist a data for both "KMS", "MLS". How do I display them
        }

Upvotes: 0

Views: 1528

Answers (3)

Hari Shankar Singh
Hari Shankar Singh

Reputation: 24

$testValue = $result->pluck('test'); //return values [ "KMS", "MLS"]
$newArray = [];
array_push($testValue , $newArray);

   
        foreach($newArray as $clinical_data) {

           return $Testdata = \DB::table('tests')
            ->select('*')
            ->whereIn('$clinical_data', $newArray)
            ->get();            
           // returns data for only "KMS" Instead of both. There exist a data for both "KMS", "MLS". How do I display them
        }

Upvotes: 0

Manthan Tripathi
Manthan Tripathi

Reputation: 144

It shows one record because you have return statement in your loop. It retuns back on the first execution.

Solution

  • Combine all the records in an array and then return

Better Solution

  • Apply Join of both the tables or write a Sub-Query. This will reduce your overhead of the Loop.

Upvotes: 1

aynber
aynber

Reputation: 23011

where takes a single value. You're looking for whereIn, which will use the array for the search. It translates to where test_name IN ('KMS','MLS')

->whereIn('test_name', $clinical_data)

Upvotes: 1

Related Questions