Braw Rajab
Braw Rajab

Reputation: 35

how to display array values inside view in laravel

i am trying to display an array inside a view but it says undefined index this is the code inside the controller

   $collection = [];

    foreach($drugss as $r){
        $collection[] = DB::table('drugs')->where('id', $r['drug_id'])->get();
    }

     // dd($collection);
    return view('billing')->withDrugs($collection)->withPending($pending_orders);

and wen i type dd($collection) it shows that all the objects inside the array but i cant access them inside the view

this is the view

                @foreach ($drugs as $drug)

                <span >{{ $drug['generic_name']}}</span> 
               @endforeach

this is the array collection that i am sending to the view

enter image description here

Upvotes: 0

Views: 1622

Answers (2)

Aless55
Aless55

Reputation: 2709

Your problem is that you have an array of collections. I am not sure why you chose such a strange structure. With your array structure, you will have to call another foreach loop inside your foreach loop to iterate over your collections arrays.

I think what you really wanted was to get a collection of Drugs which have some ids.

I would create an id array first and then get all the Drugs which have one of the ids in the ids array:

$ids = [];

 foreach($drugss as $r){
        array_push($ids, $r['drug_id']);
   }
$drugs = DB::table('drugs')->whereIn('id', $ids)->get();

@edit If you want duplicate entries (assuming you have a Drug model):

$drugs = collect(new Drug);
foreach($drugss as $r){
      $drugs->add(Drug::find($r['drug_id']));
}

Otherwise you can do something like that:

$drugs = [];
foreach($drugss as $r){
      array_push($drugs, Drug::find($r['drug_id']));
}

Upvotes: 3

gbalduzzi
gbalduzzi

Reputation: 10176

What the dd output tells you is that each item in the collection is another collection containing a single element: the array.

This is because ->get() will always return a collection.

What you have:

 $collection
  - 0: Collection
     - 0:  [ ...first array ... ]
  - 1: Collection
     - 0: [ ...second array ... ]
  ...

What you expect:

 $collection
  - 0: [ ...first array ... ]
  - 1: [ ...second array ... ]
  ...

You could use first() to obtain the array instead of the collection:

$collection[] = DB::table('drugs')->where('id', $r['drug_id'])->first();

As a more performant alternative, you could retrieve all the drugs directly with a single query by identifying all your ids before performing the query:

$drugsId = array_map(function ($r) { return $r['drug_id']; }, $drugss);
$collection = DB::table('drugs')->whereIn('id', $ids)->get();

Upvotes: 1

Related Questions