How to use foreach to display various array values for the view in a table

Asked

Viewed 211 times

0

I’m having a question so I can use one array of PHP to display the values within a table. The principle is to store the values in a array and then use a foreach to insert the values within a table in HTML in my view of Laravel. as an example to the code below.

<tbody>                         
  <tr>
       @foreach($dataTable as $dt)

           <td class="text-center">
                {{$dt->valor1}}
           </td>
           <td class="text-center">
                {{$dt->valor2}}
           </td>
           <td class="text-center">
                {{$dt->valor3}}
           </td>
      @endforeach
  </tr>
</tbody>

In my controller, I inserted 3 types of array within another array, that I ended up transforming that same array in object, as shown in the example below.

$dataTable[] = (object) ['valor1'=>$valor1, 'valor2'=>$valor2, 'valor3'=>$valor3];

I ended up using a test on my own Controller of Laravel using the following code below to see how the values are being used.

foreach($dataTable as $dt){
     dd($dt);
}

The values gave the following result.

   {#418 ▼
      +"valor1": array:7 [▶]
      +"valor2": array:7 [▶]
      +"valor3": array:7 [▶]
    }

But mine view with the code HTML, is not working using the values this way. It appears the following error message:

Cannot use object of type stdClass as array

I am using the Laravel framework. Is there any way with the same idea of entering the values in the table that works and is feasible? I tried to go through being an array and not an object and yet the view shows no functionality. Instead, errors like:

htmlspecialchars() expects parameter 1 to be string, array given

I find it strange that inside the controller works right. But inside the HTML with the tables, always persists in the errors.

  • Displays the code of this controller and the dd of $datatable

1 answer

1


You must first convert your objects and be an object array to collect the data the way you want it:

All the $object must have the same attribute value to be used in this way and not value1, value2, etc.

$arr = [$objeto, $objeto2, $objeto3];

return view('minha.view', compact('arr'));

In view

@foreach($arr as $item)
  {{$item->valor}}
@endforeach
  • In this case. What is the functionality of the Compact function? What is it doing with the array?

  • Compact allows you to pass more than one array, to view, for example Compact(['arr', 'arr2', 'arr3']); If you are going to pass an element only vc can pass straight if it is an array, if it is an object you still need the Compact.

  • can pass as well as Compact('arr', 'arr1', 'arr2', 'arr3')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.