mercredi 1 août 2018

Multiple query inside foreach loop in Laravel

I've been scratching my head over this since last night. I have this function on my controller:

 public function generate_documents($id)
    {
        $contract = Contract::find($id);
        $booking_ids = $contract->booking_id;
        $booking_ids = json_decode($booking_ids);
        $bookings = Booking::find($booking_ids);
   }

$booking_ids returns a json of ids that are stored in the database. I then find the booking records based on the IDs.

foreach($bookings as $booking) {
   $asset = Omg_asset::where('id', $booking->omg_asset)->first();
}

Here's the part where I am expecting 3 results but only the last one gets returned on my view. I tried this method:

$asset = '';
foreach($bookings as $booking) {
   $asset .= Omg_asset::where('id', $booking->omg_asset)->first();
}

But whenever I try to retrieve the values on my view, it's returning a json containing all the records I need and I can't access it via index.

Attaching a screenshot for better context:

enter image description here

Here's my code on my view by the way:

@foreach($bookings as $booking)
    <tr>
        <td></td>
    </tr>
@endforeach

Here's the error thrown whenever I try to do on view:

"Illegal string offset 'asset_name'"

I haven't used Laravel in a long time so I would really appreciate your help. If there's also a better way to do this, I'm open for suggestions.

Thanks in advance!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire