Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

angelorigo's avatar

Loop a JSON variable into a blade template

I generate a excel spreadsheet with help of a class that implements https://packagist.org/packages/maatwebsite/excel package.

In the controller i do use json_encode, then in the blade template i loop over key and the value.

Inside the foreach the entire JSON $value is contained, as a string, inside a cell, into the Excel spreadsheet.

I am trying to find how to separate each $value item ? Ex. name, bank_orders, itens ?

From the controller i do export the data result using :

foreach($result as $key=>$value){ $result[] = json_encode($value); }

In the blade template i do loop :

@foreach($structure as $key=>$value)
< table >
< tr > < td >
{{ $key }}
< /td > < td > {{ $value }}
< /td >
< /tr >
< /table > @endForeach

The JSON structure is :

[ [ 0 ] => { "name": "My secret name", "number": 20, "bank_orders": [ { "operation_number": "1234", "category_invest": { "category": "122 costs"
}, "itens": [ { "item_number": 123456, "contract_data": "my contract data", "payment_date": "2025-01-01 00:00:00.000", "amount_payment": 4567.00,
}, { "item_number": 789910, "contract_data": "my new contract data", "payment_date": "2025-01-01 00:00:00.000", "amount_payment": 1234.00,
}

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Certainly! The issue is that you are encoding your data to JSON in the controller, so when you loop in the Blade template, each $value is a JSON string, not an array/object. To access individual fields (like name, bank_orders, itens), you need to decode the JSON string back to an array/object in your Blade template.

Solution:

1. Controller (Recommended: Don't Encode to JSON)

Instead of encoding to JSON in your controller, just pass the array to the view:

// Controller
// $result is already an array of arrays/objects
return view('your-view', ['structure' => $result]);

2. Blade Template

Now, you can loop through the array directly and access its properties:

3. If You Must Use JSON (Not Recommended)

If you must keep the JSON encoding, decode it in the Blade template:

@foreach($structure as $jsonValue)
    @php
        $item = json_decode($jsonValue, true);
    @endphp
    <table>
        <tr>
            <td>Name:</td>
            <td>{{ $item['name'] }}</td>
        </tr>
        <!-- Repeat as above -->
    </table>
@endforeach

Summary:

  • Best practice: Pass arrays/objects to the view, not JSON strings.
  • If you have JSON: Use json_decode($value, true) in Blade to convert it back to an array.

Let me know if you need help with a specific part of the structure!

1 like

Please or to participate in this conversation.