Search code examples
phplaraveleloquent

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


Solution

  • 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();