how to foreach data from same database with two tables laravel - php

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

Related

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

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

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 group similar names from database before "-"

hey so my database looks like this. Please only focus on the second column:
db
and for now i have done this that looks like:
what i have done
so for now as u all can see i did a view where it shows and separates and groups the same value:
approval-timing-when,
approval-violation,
cancellation-person,
cancellation-person-1,
cancellation-person-2
but what i want to do now is to group all "approval" together and all "cancellation" together and not separate them as shown in my second pictuere. How can i do that? My code is as below:
route:
Route::get('queries/{companyID}/{entityType}/{entityValue}','Chatbot\ChatbotController#queries');
controller:
public function queries($companyID, $entityType, $entityValue)
{
$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->queries] = $datum->id;
}
$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->reply] = $datum->id;
}
ksort($data);
return view('AltHr.Chatbot.queries', compact('data','entityType','entityValue','companyID'));
}
view:
#foreach($data as $intentName => $questionAnswer)
<div class="form-group edit-response-container">
<label data-toggle="collapse" data-target="#collapse-{{$intentName}}" aria-expanded="false" aria-controls="collapse-{{$intentName}}"> {{$intentName}} <i class="fa fa-chevron-down"></i></label>
<div class="collapse" id="collapse-{{$intentName}}">
</div>
</div>
#endforeach
I'd use the groupBy collection method and work off the second column like this:
// change to your model and whatever the second column is named.
$collection = Model::all();
// or DiraQuestion/DiraResponse ..
$collection = ... your query...
// then
$grouped = $collection->groupBy(function ($item, $key) {
return explode('-', $item['column_2'])[0];
});
update
// result of DiraResponses query
$grouped = $detailsAns->groupBy(function ($item, $key) {
return explode('-', $item['column_2'])[0];
});

Access data in multidimensional array

I am trying to get all data i need in one variable
--Subject
---Chapters related to subject
----Topics related to chapter
And this is what i have done!
$subjects = Subject::all();
$chapters = Chapter::all();
$topics = Topic::all();
foreach ($subjects as &$subject)
{
$i = 0;
$subject->related_chapters = array();
$chapters_reltn = array();
foreach ($chapters as $chapter)
{
if ($chapter->subject_id == $subject->id)
{
$chapters_reltn[$i]['id'] = $chapter->id;
$chapters_reltn[$i]['name'] = $chapter->name;
$j = 0;
foreach ($topics as $topic)
{
if ($topic->chapter_id == $chapter->id)
{
$chapters_reltn[$i]['related_topics'][$j]['id'] = $topic->id;
$chapters_reltn[$i]['related_topics'][$j]['name'] = $topic->name;
$j++;
}
}
$i++;
}
};
$subject->related_chapters = $chapters_reltn;
}
When i dd() in laravel, i see all the data arranged in structure i wanted.
The problem comes when accessing a specific data like so,
#foreach($subjects as $subject)
{{ $subject->name }}
{{ $subject->related_chapters[0]['name'] }}
#endforeach
i get an error:
Undefined offset: 0
Is there a better way of structuring my array, and getting data correctly. Please help!
Undefined offset is an notice that comes when you try to access an array which does not exist . Make sure that a value exists in that index or you can do something like this just before accessing the value
If (isset ( $subject->related_chapters[0]['name']))

Laravel Many to Many get collection of third instance selection

I am trying to grab collections form many to many relationships in my application.
To explain very quickly: Lets say I have categories that themselves have dedicated hashtags. Those hashtags again have photos.
Now, I want to grab one category and its dedicated hashtags. But I also want to grab all photos that are associated with those hashtags.
So here is what I have tried but still, this does not work:
$all_related_hashtags = $categorie->hashtags()->get();
$photos = foreach ($all_related_hashtags as $hashtag) {
$hashtag->photos;
}
Is there any way to fix this?
Any help would be awesome.
Thanks.
EDIT
#foreach ($all_related_hashtags as $hashtag)
#foreach(array_chunk($hashtag->photos, 4) as $row)
<div class="row">
#foreach($row as $photo)
SECOND EDIT
#foreach ($all_related_hashtags as $hashtag)
#foreach ($hashtag->photos as $photo)
{{ $photo->title }}
#endforeach
#endforeach
Try this instead
$all_related_hashtags = $categorie->hashtags()->get();
$photos = array();
foreach ($all_related_hashtags as $hashtag) {
$photos[] = $hashtag->photos;
}
If you just want to display in your view the photos for each hashtag you can actually call the photos in your view using nested loop such as:
foreach ($all_related_hashtags as $hashtag) {
foreach ($hashtag->photos->take($limit) as $photo){
echo $photo->url
}
}
Try this:
$all_related_hashtags = $categorie->hashtags()->get();
$categorie_photos = array();
foreach ($all_related_hashtags as $hashtag) {
$current_photos = array();
foreach ( $hashtag->photos as $photo ) {
$current_photos[] = $photo;
}
array_merge($categorie_photos, $current_photos);
}

Categories