Reputation: 1609
I have a question about for loop. I am saving json data just in one column. For example:
1 / John / ["jsondata1","jsondata2","jsondata3"]
2 / Elizabeth / ["jsondata3","jsondata4"]
I need to show this values in a table. 3rd column max data size is allways 4. there is no jsondata5
I was created this loop in my blade view.
<table>
@foreach($values as $value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->name}}</td>
@for ($i = 0; $i < 4; $i++)
<td>{{$value->jsondata[$i]}}</td>
@endfor
</tr>
@endforeach
</table>
In this case i am getting some errors.
Error is "Undefined offset: 2"
When i tried for ($i = 0; $i < 2; $i++)
it just show the last 2 data.
But if i tried $i < 4
there is an error.
What is the right way to do this for loop? I tried so much ways.
Upvotes: 2
Views: 48
Reputation: 163778
The best way to handle this is to use casting. From the docs:
The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model
Add this to the model and you'll be able to work with JSON data as with a simple array:
protected $casts = [
'column_name' => 'array',
];
Upvotes: 1