Undesirable duplicate content with double foreach in blade - php

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);

Related

Foreach error if only single record exists in the import csv - Laravel blade

I have an import feature where users can import records from a .csv file. It works fine if the user is importing a file with multiple records but if one tries to import a .csv that has only one record it throws an error, "Invalid argument supplied for foreach()" and spits out this reference code for the error.
<?php $__currentLoopData = $line; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $field): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
As stated this error only occurs when there is a single record in the import .csv, if one were to add additional records to the .csv the import feature the process works fine.
Here is the blade's foreach code, what's going on?
<table class="table">
#if (isset($headers))
<tr>
#foreach ($headers as $field)
<th>{{ $field }}</th>
#endforeach
</tr>
#endif
#if($lines)
#foreach ($lines as $line)
<tr>
#foreach ($line as $field)
<td>{{ $field }}</td>
#endforeach
</tr>
#endforeach
#endif
<tr>
#foreach ($headers as $key => $header)
<td>
<select name="fields[{{ $key }}]">
<option value=''>Please select</option>
#foreach ($fillables as $k => $fillable)
<option value="{{ $fillable }}"
#if (strtolower($header) === strtolower($fillable)) selected #endif>{{ $fillable }}</option>
#endforeach
</select>
</td>
#endforeach
</tr>
</table>
Here is the controller
public function parse(Request $request)
{
$file = $request->file('csv_file');
$request->validate([
'csv_file' => 'mimes:csv,txt',
]);
$path = $file->path();
$hasHeader = $request->input('header', false) ? true : false;
$reader = new SpreadsheetReader($path);
$headers = $reader->current();
$lines = [];
$lines[] = $reader->next();
$lines[] = $reader->next();
$filename = Str::random(10).'.csv';
$file->storeAs('csv_import', $filename);
$modelName = $request->input('model', false);
$fullModelName = 'App\\'.$modelName;
$model = new $fullModelName();
$fillables = $model->getFillable();
$church_id = $request->input('church_id');
$interest_tags = $request->input('interest_tags');
if ($modelName == 'Interest') {
$custom_fields = CustomField::where('created_by_team_id', $church_id)->pluck('name')->toArray();
if (! empty($custom_fields)) {
$fillables = array_merge($fillables, $custom_fields);
}
}
$is_adding_new_religious_background = $request->input('is_adding_new_religious_background', false) ? true : false;
$redirect = url()->previous();
return view(
'csvImport.parse_import',
compact('headers', 'filename', 'fillables', 'church_id', 'interest_tags', 'hasHeader', 'modelName', 'lines', 'redirect', 'is_adding_new_religious_background')
);
How does one modify this so that it functions for both single record and multi-record imports?
I think you have to check the second #foreach in your blade template. You need to check if if $line is empty before loop.

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

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

PHP to Laravel loop conversion

I am trying to convert this PHP code:
<?php
foreach ($arr as $v) {
echo '<tr><td>' . $v['bookTitle'] . '</td><td>';
$ar = array();
foreach ($v['authors'] as $key => $value) {
**$ar[] = '' . $value . '';**
}
echo implode(' , ', $ar) . '</td></tr>';
}
?>
into Laravel code, but have problems
#foreach ($arr as $v)
<tr><td> {{ $v['bookTitle'] }}</td><td>
<?php $ar = array(); ?>
#foreach ($v['authors'] as $key => $value)
***$ar[] = . $value . ;*** //{{ Html::link("all?authorID= $key", "$value")}}
#endforeach
{{implode(' , ', $ar)}}</td></tr>
#endforeach
Can someone please help me with this?
#foreach ($arr as $v)
<tr><td> {{ $v['bookTitle'] }}</td><td>
#php $ar = array(); #endphp
#foreach ($v['authors'] as $key => $value)
#php $ar[]; #endphp = {{ Html::link("all?authorID= $key", "$value")}}
#endforeach
{{implode(' , ', $ar)}}</td></tr>
#endforeach
FatalErrorException
Cannot use [] for reading
Your mistake is at this line. The $val is not exist as your are make each object in loop to $value variable
$ar[] = . $val . ;
Secondly, the blade syntax is like below. Refer to Docs for detail usage.
#foreach ($v['authors'] as $key => $value)
<td>{{ $value }}</td>
#endforeach
Note: Please keep the long code in controller instead of routes/web.php
As you're using Larvel 5.4.x, you can simply do the following and not have to re-write it using blade:
#php
foreach ($arr as $v) {
echo '<tr><td>' . $v['bookTitle'] . '</td><td>';
$ar = array();
foreach ($v['authors'] as $key => $value) {
$ar[] = '' . $value . '';
}
echo implode(' , ', $ar) . '</td></tr>';
}
#endphp
Albeit it's not the best solution, but, until you can move this logic into the controller and not have it within the view, it might be a good interim solution.
If you open up the following link for Control Structures within the Laravel documentation: https://laravel.com/docs/5.4/blade#control-structures and scroll down to the heading named "PHP" it should give you everything you need.

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