li bing zhao
li bing zhao

Reputation: 1418

How to get json data in blade laravel

In the blade template:

<?php
      $meta = json_encode($datas,true);   
      echo $meta;
?>

It shows:

{"data":[{"id":1,"title":"Alice.","rating":0},
{"id":2,"title":"So Alice.","rating":2},
{"id":3,"title":"Alice.","rating":2},
{"id":4,"title":"After a.","rating":2},
{"id":5,"title":"Alice.","rating":0}],
"meta":{"song_count":5}}

My question is how to get (song_count: 5 ) in blade template. I have tried : echo $meta['meta'];

" it shows;

"Illegal string offset 'meta'"

Anyone can help, thank you so much

Upvotes: 0

Views: 2276

Answers (3)

STA
STA

Reputation: 34678

json_encode() method give you a json formatted data. You need to decode it :

$meta = json_encode($datas,true);   
$meta = json_decode($meta, true);
echo $meta;

Now you access the array property as $meta['meta'];

NB : if $datas is already an array, then you don't need to encode and decode it.

Upvotes: 1

li bing zhao
li bing zhao

Reputation: 1418

The steps to show the value of json data from controller as bwlow:

<?php
$datas = json_encode($datas,true);
 //dd($data);
$datas = json_decode($datas);
// dd($datas);
foreach($datas->meta as $link){
 echo $link;
}
?>

Upvotes: 0

Mohamed Ahmed
Mohamed Ahmed

Reputation: 830

thats mean you try to take meta key from string because $meta is json not array so you dont need to json_encode $data , you can do direct :- $datas['meta']['song_count'] if $data is array . but this maybe give you error if $datas is empty to solve this you can make check if $data !empty or use optional method in laravel like this :- optional($datas['meta'])['song_count'] it solve the problem .

Upvotes: 0

Related Questions