Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How do I parse this json data in view blade?

Currently this is my view

{{ $leads }} 

And this is the output

{"error":false,"member":[{"id":"1","firstName":"first","lastName":"last","phoneNumber":"0987654321","email":"[email protected]","owner":{ "id":"10","firstName":"first","lastName":"last"}}]} 

I wanted to display something like this

Member ID: 1 Firstname: First Lastname: Last Phone: 0987654321  Owner ID: 10 Firstname: First  Lastname: Last 
like image 600
David Alrdrin Avatar asked May 06 '15 09:05

David Alrdrin


People also ask

How do I parse JSON?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How can we get data from JSON column in laravel?

It's possible to transform JSON into array with no need of using json_decode by casting the column. All we need to do is adding this to our Item model. protected $casts = [ 'furni' => 'array' ]; Now, every time we fetch data from the furni column, we will get an array response.

How can you decode JSON string?

You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type. Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value. When it is set as “true”, JSON objects are decoded into associative arrays.

What is JSON decode in laravel?

The json_decode() method is a PHP built-in function, which helps to convert a JSON object into a PHP object. It takes the input value as a string and returns a readable PHP object.


2 Answers

It's pretty easy. First of all send to the view decoded variable (see Laravel Views):

view('your-view')->with('leads', json_decode($leads, true)); 

Then just use common blade constructions (see Laravel Templating):

@foreach($leads['member'] as $member)     Member ID: {{ $member['id'] }}     Firstname: {{ $member['firstName'] }}     Lastname: {{ $member['lastName'] }}     Phone: {{ $member['phoneNumber'] }}      Owner ID: {{ $member['owner']['id'] }}     Firstname: {{ $member['owner']['firstName'] }}      Lastname: {{ $member['owner']['lastName'] }} @endforeach 
like image 101
Maxim Lanin Avatar answered Oct 12 '22 23:10

Maxim Lanin


it seems you can use @json($leads) since laravel 5.5

https://laravel.com/docs/5.5/blade

like image 21
mygeea Avatar answered Oct 12 '22 23:10

mygeea