Laravel : How to split/fetch the json nested elements in blade view? - php

When i am passing the below in view blade shows the entire Json structure fetching from mongo.
{!! $fees !!}
output :
[{"_id":"5e04a06ca445f78401a16d0a","University":[{"fees":"$200"},{"month":"June"}]}]
Now how to fetch the nested content.I want to show Fees = $200 and Month = June in the blade
Tried like this but result is 'blank' on the blade without any error. Is there any issue with the nested open/closing :[, which is just after 'University:' in the above JSOn input. Please suggest
#foreach ($fees as $value)
{{$content[] = $value->['University'] }}
#foreach ($content as $key)
<h1>{{ $key['fees'] }}</h1>
<h1>{{ $key['month'] }}</h1>
#endforeach
#endforeach
My earlier steps are given here :
Laravel not fetching result from mongodb
Edit(1) :
I tried like this so the structure on blade view.
<?php
$get_result = json_decode($fees, true);
#$get_result = implode(",", array_flatten($get_result));
#print_r($get_result);
#$get_result2 = json_encode($get_result, true);
echo "</br>";
print_r($get_result)
?>
output :
Array ([0] => Array ([_id] => 5e04a06ca445f78401a16d0a [University]
=> Array ([0] => Array ( [fees] => $200 ) [1] => Array ( [month] => June ) )))
Also,
<?php
echo htmlentities (print_r (json_encode ($fees), true));
?>
output:
"[{\"_id\":\"5e04a06ca445f78401a16d0a\",
\"University\":[{\"fees\":\"$200\"},{\"month\":\"June\"}]}]"
Also from Controller i tried as below:
..
public function getFees()
{
# database fetch test (with any one of the db query)
$fees = Finance::all();
$fees = Finance::where(['University.month' => 'June'])->get()->toArray();
$fees = Finance::where('University.month', 'June')->first();
$fees = Finance::where('University.month', 'June')->get();
# Return test (with any one of the return)
return view('tables')->with('fees', json_encode($fees, true));
return view('tables', compact('fees'));
return view('tables')->with(compact('fees'));
return view('tables')->with('fees', $fees);
}
..
Edit(2) :
in view blade i tried as below but getting exception as : Trying to get property 'fees' of non-object
<?php
$fees = json_decode($fees, true);
#echo "</br>";
#print_r($fees)
?>
#foreach ($fees[0] as $value)
#php $content = $value->University #endphp // or without #
#foreach ($content as $key)
<h1>{{ $key['fees'] }}</h1>
<h1>{{ $key['month'] }}</h1>
#endforeach
#endforeach
Edit(3) as per suggestion by Chandan.
<?php
$fees = json_decode($fees);
$univ = $fees[0]->University;
//print_r($univ);
foreach ($univ as $key => $value)
{
foreach($univ[$key] AS $k =>$v)
{
echo $k." " .$v;
}
}
?>
output :
fees $200month June
only thing the output is merges without comma separated.
Can I show them as below
fees = $200
month = June
or as a html
<td>{{$k}}</td><td>{{$v}}</td>

You can try this:
$fees = json_decode($fees);
$univ = $fees[0]->University;
//print_r($univ);
foreach ($univ as $key => $value) {
foreach($univ[$key] as $k =>$v){
echo $k .'= '.$v.' ';
}
}

It should be working as below:-
#foreach ($fees as $value)
{{$content[] = $value->['University'] }}
#if($content->['fees']!==null)
<h1>{{ $content['fees'] }}</h1>
#else
<h1>-</h1>
#endif
#if($content->['fees']!==null)
<h1>{{ $content['fees'] }}</h1>
#else
<h1>-</h1>
#endif
#endforeach

Related

Append HTML File Using Laravel

I need to add an HTML file to my laravel view, but I can't.
My back code:
$fls = array();
foreach ($docItems as $key => $value) {
$fl = array("flName" => $value["tab_name"], "flContent" => readfile("documents/". $referenceId .
"/" . $value["tab_name"] . ".html"));
array_push($fls, $fl);
}
$data['itemsContent'] = $fls;
return view('pages.doc', $data);
My laravel blade view code:
#foreach ($itemsContent as $k => $v)
<div>{{ $v["flContent"] }}</div>
#endforeach
Do you guys know why it is not working? I mean, it is adding my html code, but at the beginning of the page, and this is not what I want. Ahh and I am using Laravel 7 and PHP 7.

How can I user json to dispaly in laravel?

i tried to view data from database as per shown but get this error
$testjson = new TestJson ;
$testjson = $testjson->Where('id',2)->get();
return view('viewjson')->with('alldata',Json_decode($testjson));
user below code to view data
#foreach($alldata as $key => $value)
{{ $key }} - {{ $value }} <br>
#endforeach
can't get scope data
0 - {"id":2,"token":"2020-04-06 12:02:15","data":"{\"scope\":[\"volvo\",\"saab\",\"opel\",\"audi\"]}","created_at":"2020-04-06 12:02:15","updated_at":"2020-04-06 12:02:15"}
database
$testjson = new TestJson ;
$testjson = $testjson->Where('id',2)->get();
return response()->json(['data' => $testjson]);
If you are displaying in laravel view then no need to convert in json
$alldata = TestJson::find(2);
return view('viewjson', compact('alldata'));
And in laravel view
#foreach($alldata ?? [] as $key => $value)
#if($key == 'data')
#foreach(json_decode($value->data) ?? [] as $innerKey => $innerValue)
{{ $innerKey }} - {{ $innerValue}} <br>
#endforeach
#else
{{ $key }} - {{ $value }} <br>
#endif
#endforeach

How to use unknown JSON key names as my table headers

I'm using Laravel framework.
I've got a table with some JSON I want to iterate over, I've cast the table to an array. This is the format;
{"Height": "#m", "Width": "#m", "Weight": {"now": "#kg", "previous": "#kg"}}
My controller returns the view;
$person = Person::find($ID);
$data = $person->tableJson;
return view('person.person_details', compact('person', 'data'));
And in the view itself:
#foreach ($data as $value)
Width: {{ $value->tableJson['Width'] }} <br>
Height: {{ $value->tableJson['Height'] }} <br>
Weight (now): {{ $value->tableJson['Weight']['now'] }} <br>
Weight (previous): {{ $value->tableJson['Weight']['previous'] }} <br>
<hr>
#endforeach
I have that working. The thing is I want to replace the hard coded titles (Width, Height, etc) with the keys in the JSON itself. That way I can (hopefully) dynamically populate a table without knowing what the JSON contains.
When looping your $data use actual keys in that:
$data = [0: ["Height" => "#m", "Width" => "#m", "Weight" => ["now" => "#kg", "previous" => "#kg"]]];
foreach ($data as row) {
foreach ($row as $header => $val) {
if (is_string($val)) {
echo "{$header}: {$val}<br/>";
} else {
foreach ($val as $type => $subVal) {
echo "{$header} ($type): {$subVal}<br/>";
}
}
}
echo "<hr/>";
}

how to foreach data from same database with two tables laravel

I have written a code to view data but I'm having some problems.
From the code, I wrote it's viewing the data from one table which is the $details. But I also wanna view the data from the $detailsAns.
How can I do that? also, can I foreach two data from that two tables?
my code below:
public function queries($companyID, $entityType, $entityValue)
{
$data = [];
$details = DiraQuestion::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
$detailsAns = DiraResponses::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach($details as $key => $detailsValue)
{
if(!array_key_exists($detailsValue->intent, $data))
{
$data[$detailsValue->intent] = [];
}
if(!array_key_exists($detailsValue->reply, $data[$detailsValue->intent]))
{
$data[$detailsValue->intent]['answer'][$detailsValue->reply] = $detailsValue->id;
}
if(!array_key_exists($detailsValue->queries, $data[$detailsValue->intent]))
{
$data[$detailsValue->intent]['question'][$detailsValue->queries] = $detailsValue->id;
}
}
ksort($data);
return view('AltHr.Chatbot.queries', compact('data','entityType','entityValue','companyID'));
}
so as you can see I can return the data from foreach for $details but now I want to return data for $detailsAns also. how can I do that?
my database structure:
table1:
table2:
so to get the data it first has to select the company id, eType, eVal, and intent so from that now i need to display the reply and queries.
The output that i want is as below:
So as you can see i can output the questions table in the foreach that i did. and if i change the foreach to $detailsAns then i display the reply.. but i want to view the both now
It isn't very clear from the data provided how the tables relate to each other. If the answer has the same id value as the question, it is easy to relate them by structuring the arrays so that they are keyed by the common value.
$data = [];
$details = DiraQuestion::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach ($details AS $datum) {
if (!isset($data[$datum->intent])) $data[$datum->intent] = ['question' => [], 'answer' => []];
$data[$datum->intent]['question'][$datum->id] = $datum->queries;
}
$detailsAns = DiraResponses::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach ($detailsAns AS $datum) {
if (!isset($data[$datum->intent])) $data[$datum->intent] = ['question' => [], 'answer' => []];
$data[$datum->intent]['answer'][$datum->id] = $datum->reply;
}
At this point, since you said that there is no relation between the data sets, just pass the data array to the view the way you already are:
return view('AltHr.Chatbot.queries', compact('data','entityType','entityValue','companyID'));
And loop through both elements of data, printing out values in the view:
#foreach ($data['approval-document']['question'] as $id=>$question)
<p>Question #{{ $id }}: {{ $question }}</p>
#endforeach
#foreach ($data['approval-document']['answer'] as $id=>$answer)
<p>Answer #{{ $id }}: {{ $answer }}</p>
#endforeach

Undesirable duplicate content with double foreach in blade

how can I make sure I use more foreach in my blade, without the content repeating more than once?
$review = Review::orderBy('created_at', 'desc')->paginate(9);
$info_games = array();
$games = array();
foreach ($review as $value) {
$info_games[] = InfoGames::where('id_game', $value->id_game)->first();
$games[] = Games::where('id', $value->id_game)->first();
}
return view('front.pages.review.list', compact('review','info_games','games'));
and my blade:
#foreach ($review as $value)
#foreach ($info_games as $info_game)
<div>
<img src="https://gamelite.net/{{$info_game->image}}">
<p>{!! str_limit($value->body, 150) !!}</p>
</div>
#endforeach
#endforeach
{!! $review->render() !!}
use array_filter($array) . It will return unique .
in your case
$info_games = array_filter($info_games);

Categories