mbpp's avatar
Level 3

Iterate in blade json data

Hello, im trying to iterate in a foreach loop a json object, but with no success, it keeps giving me error regarding html entities.

The data im trying to output in my foreach is:

data: variable that is stored the data above is '$product->tags['data']'

{"tags":[{"type":"circle","points":[[1.0449999570846558,0.5450000166893005],[0.9850000143051147,0.4399999976158142]],"popup":{"title":"my title","description":"my description"}},{"type":"rectangle","points":[[0.03500000014901161,0.125],[0.3400000035762787,0.6000000238418579]],"popup":{"title":"roupa","description":"guardar roupa"}}]}

My code: @foreach($product->tags['data']->tags as $tag){ {{$tag->type}} }

0 likes
5 replies
tykus's avatar

json_decode() the JSON (which I would suggest is done in the Controller - give data to the view in the format that it uses the data)

@foreach ( json_decode($product->tags['data'])->tags as $tag)
    {{$tag->type}} 
@endforeach
rexsteroxy's avatar

@TYKUS - Please am also having the same problem..

@foreach (json_decode($property->property_image, true) as $image)
                    <img src="{{ $image[0][0] }}" alt="" width="100%">
                        @endforeach

My problem is how to iterate through it in my view blade and display them as image url.

"["http:\/\/kizflex.local\/properties\/2.jpg","http:\/\/kizflex.local\/properties\/2.jpg"]"

Please help a brother.

tykus's avatar

@rexsteroxy

Is property_image a property on the Property model; a column in your properties table?

If you are storing JSON as text on the table, you can cast it in the model:

class Property extends Model
{

    protected $casts = [
        'property_image' => 'json'
    ];
}

Now, you would be able to iterate over the resulting array directly:

@foreach ($property_image as $image)
    <img src="{{ $image}}" alt="" width="100%">
@endforeach
tykus's avatar

@ziakhan please create your own thread describing your issue rather than resurrecting older threads

Please or to participate in this conversation.