2

I'm using laravel with blade and vuejs. Using a controller for a list I am receving the correct response with all the users data to show.

Some of this fields are json data and I can't understand how to retrieve single value.

`@foreach ($lista as $freelance)
  <md-table-row>
    <md-table-cell>
      {{ $freelance->regione }}
     </md-table-cell>
  </md-table-row>
@endforeach`

$freelance->regione is a JSON, correctly shown in the page as:

`{"text": "Veneto", "value": "Veneto"}`

My question is, how can I get the single value of the JSON response and not all the data? Preferably without loops...I know that I can use a new loop for it but possible no..

Murphz
  • 33
  • 1
  • 7

3 Answers3

1

Try this in your controller before passing the $lista variable to view do this.

foreach($lista as list)
{

 //we will decode the variable befoe passing it to view
 $list->regione = json_decode($list->regione, true);


}

and then pass the variable to your view like :

    return View::make('your_view_name', compact('lista'));

then in your blade view.

`@foreach ($lista as $freelance)
  <md-table-row>
    <md-table-cell>
      {{ $freelance->regione['text'] }}
     </md-table-cell>
    <md-table-cell>
      {{ $freelance->regione['value'] }}
     </md-table-cell>
  </md-table-row>
@endforeach`
Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98
  • seems good Sapnesh...I've made as you said and in the List Controller I've seen the right value...unfortunately the compact($lista) throws me this error: Call to a member function total() on array... – Murphz May 10 '17 at 15:07
  • @Murphz oh sorry, you don't need to include `$` when using compact, it was a typo. updated now – Sapnesh Naik May 10 '17 at 15:31
  • 1
    That'is Sapnesh, it works! I have had to correct some errors in your code but maybe it's just my platform. The json_decode result cannot be applied to $list->regione as it only accept string and not array, used a temp value solved it. After that, using the compact('lista') I am now able to retrieve the correct value in the blade template using just $freelance->regione...thank you again sir! – Murphz May 10 '17 at 16:00
0

There are functions laravel blade template allow use directly. You need to decode the json string in order to get the value in it.

@foreach ($lista as $freelance)
 <md-table-row>
    <md-table-cell>
        {{ json_decode($freelance->regione)->value }}
    </md-table-cell>
 </md-table-row>
@endforeach
Dinoop
  • 479
  • 4
  • 10
  • That’s probably because some of your regione json string in the loop may not contain value key – Dinoop May 11 '17 at 06:32
0

You can use json_decode to parse the json string, refer to this for json parse

{{ json_decode($freelance->regione, true)['value'] }}
Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295
  • Yes, tried that..but inside blade is not working to me, using json_decode in the controller as Sapnesh wrote seems working good... – Murphz May 10 '17 at 16:05