0

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

3
  • Why did you encode the $data? You can get it from the data array Commented Feb 6, 2021 at 13:12
  • Does this answer your question? Access PHP array element Commented Feb 6, 2021 at 13:19
  • var_dump(data); to see is that the array or the object. Then access those elements/members accordingly. Commented Feb 6, 2021 at 13:22

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you for you answer and help, when I use "echo $meta['meta'];" it shows empty, as you see the meta has some data.
what is the output of dd($datas);?
SongsCollection {#198 ▼ +collects: null +collection: Collection {#208 ▼ #items: array:5 [▶] } +resource: LengthAwarePaginator {#204 ▶} +with: [] +additional: array:1 [▼ "meta" => array:1 [▶] ] }
"meta":{"song_count":5} is under "+resource", I need to access the meta in resource.
would you please share the screenshot of the output dd($datas);
|
0

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 .

2 Comments

Thank you Mohamed, it shows empty :$datas['meta']['song_count'].
what is the result of using :- dd($datas, $datas['meta']) ??
0

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;
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.