Home > Enterprise >  How to iterate JSON with Laravel in Blade
How to iterate JSON with Laravel in Blade

Time:08-29

I am starting to use Mongo with Laravel. I have managed to make the connection and execute the first added queries. The question I have now is to iterate through the results with foreach in the blade template.

I go through a basic json file without problems

$json1 = '{
            "title":"Superman",
            "category": "Superhero"
          }';

return view('index', ['data' => $json1]);

On the blade:

  @foreach($data as $item)
       {{$item->title}}
       {{$item->category}}
       <br/>
  @endforeach

Now, how do I go through the following file:

$json2 = '{
    "tag":{
       "title":"title"
    }
}';

return view('index')->with('data', json_decode($json2));

I don't know how to access the title of the tag.

I have tried the following but without success.

@foreach($data as $item)
       {{$item->tag.title}}
        <br/>
@endforeach

CodePudding user response:

The json_decode method returns a stdClass object (unless you provide true as the second parameter which returns an associative array).

So once you have decoded your JSON, you can access the properties as you would do so for any other class based property:

$json2 = '{
    "tag":{
       "title":"title"
    }
}';

$data = json_decode($json2);

return view('index', compact('data'));
@foreach ($data as $item)
    {{ $item->title }}
@endforeach
  • Related