Search code examples
phparrayslaravellaravel-5.3laravel-blade

fetch array data in blade view


I have an array which I return to a blade view. My array declaration looks like this:

 $data = array(
     $topSell,
     $quantity
 );

With the contained data structured like this:

[
  [
   {
    "id": 4,
    "author_id": 3,
    "category_id": 3
   },
   {
    "id": 5,
    "author_id": 2,
    "category_id": 1
   },
  ],
  [
    100,
    200
  ]
]

I return this array to my blade with:

return view('report',['value' => $data]);

I want to fetch this array in blade so it will look like:

id  author_id  Quantity
4      3         100
5      2         200

Solution

  • Assuming $topSell and $quantity always have the same size, you can just use a for loop:

    @for ($i = 0; $i < count($value[0]); $i++)
      <tr>
        <td>{{ $value[0][$i]->id }}</td>
        <td>{{ $value[0][$i]->author_id }}</td>
        <td>{{ $value[1][$i] }}</td>
      </tr>
    @endfor
    

    Alternatively, you can modify your data to integrate the quantity to your objects:

    for ($i = 0; $i < count($data[0]); $i++) {
        $data[0][$i]->quantity = $data[1][$i];
    }
    

    And then, returning only the first sub array in the view:

    return view('report',['value' => $data[0]]);
    

    You can use a foreach in blade:

    @foreach ($value as $element)
      <tr>
        <td>{{ $element->id }}</td>
        <td>{{ $element->author_id }}</td>
        <td>{{ $element->quantity }}</td>
      </tr>
    @endforeach
    

    More loop statements are detailed in the documentation.