2

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.

2
  • json_decode($payload) ? Commented Jan 27, 2018 at 16:20
  • i used json_decode in my controller. Commented Jan 27, 2018 at 16:23

1 Answer 1

1

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',
];
Sign up to request clarification or add additional context in comments.

4 Comments

thats a great hidden feature.
Its already added. I tried this today but i couldn't make it.
You solved my all issues @Alexey Mezenin I am believing you can give me the solution. I got still same problem.
@AliÖzen please show results of {{ dd($values) }}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.