Add separator between foreach returned values - php

I have the following foreach returning values :
#foreach($content['order'] as $products)
<tr>
<td><span>{{ $products->Type }} {{ $products->Nom }} {{ $products->{'# Personnes'} }} {{ $products->Inscription }} {{ $products->{'Décoration Chocolat et fruits'} }} {{ $products->{'Décoration petites fleurs'} }} {{ $products->Décoration }} {{ $products->{'Nombre de sandwiches'} }} {{ $products->Poids }} {{ $products->{'Assortiment 1'} }} {{ $products->{'Assortiment 2'} }} {{ $products->{'Assortiment 3'} }} {{ $products->{'Assortiment 4'} }} {{ $products->{'Couleur Ruban'} }} {{ number_format($products->Prix, 2) }} {{ number_format($products->Supplément, 2) }} {{ number_format($products->{'Supplément décoration'}, 2) }} {{ number_format($products->Total, 2) }}</td>
</tr>
#endforeach
I would like to add a separator between each returned values (except for the last).
I added
.' | '
{{ $products->Type.' | ' }} {{ $products->Nom.' | ' }} {{ $products->{'# Personnes'}.' | ' }} {{ $products->Inscription.' | ' }} {{ $products->{'Décoration Chocolat et fruits'}.' | ' }} {{ $products->{'Décoration petites fleurs'}.' | ' }} {{ $products->Décoration.' | ' }} {{ $products->{'Nombre de sandwiches'}.' | ' }} {{ $products->Poids.' | ' }} {{ $products->{'Assortiment 1'}.' | ' }} {{ $products->{'Assortiment 2'}.' | ' }} {{ $products->{'Assortiment 3'}.' | ' }} {{ $products->{'Assortiment 4'}.' | ' }} {{ $products->{'Couleur Ruban'}.' | ' }} {{ number_format($products->Prix, 2).' | ' }} {{ number_format($products->Supplément, 2).' | ' }} {{ number_format($products->{'Supplément décoration'}, 2).' | ' }} {{ number_format($products->Total, 2) }}
Problem I have is that the separator is added even when no value is returned
Pie | Chocolate | 2-3 servings | Text | Decoration chocolate | Decoration flowers | | | | | | | | | 19.00 | 5.00 | 0.00 | 24.00
How can I print a separator only if a value is returned.
Thanks

#if(isset($products->Type)) {{ $products->Type. '|' }} #endif
This is an example of your first row how you can handle it. You check if exists and if it does you echo the result concatenating a separator on it.
small thing, mind your span tag, you are not closing it in the code you provided.

You can use ternary operator as a short hand for the same,
{{ !empty($products->Type) ? $products->Type.' | ': '' }}
Do this for all the fields

There's several way of going about this, but one quite dynamic way would be to fetch all the values into an array instead, filter it for non-empty values and implode it.
We'd be using standard PHP, which you can do within blades.
<?php
foreach($content['order'] as $products) {
$values = [];
$values[] = $products->Type;
$values[] = $products->Nom;
$values[] = $products->{'# Personnes'};
$values[] = $products->Inscription;
$values[] = $products->{'Décoration Chocolat et fruits'};
$values[] = $products->{'Décoration petites fleurs'};
$values[] = $products->Décoration;
$values[] = $products->{'Nombre de sandwiches'};
$values[] = $products->Poids;
$values[] = $products->{'Assortiment 1'};
$values[] = $products->{'Assortiment 2'};
$values[] = $products->{'Assortiment 3'};
$values[] = $products->{'Assortiment 4'};
$values[] = $products->{'Couleur Ruban'};
$values[] = number_format($products->Prix, 2);
$values[] = number_format($products->Supplément, 2);
$values[] = number_format($products->{'Supplément décoration'}, 2);
$values[] = number_format($products->Total, 2);
echo "<td>".implode(" | ", array_filter($values))."</td>";
}
?>

Turn into array, filter empty values and implode with an " | " string
{{join("|", array_filter([
$products->Type ,
$products->Nom ,
$products->{'# Personnes'} ,
$products->Inscription ,
$products->{'Décoration Chocolat et fruits'} ,
$products->{'Décoration petites fleurs'} ,
$products->Décoration ,
$products->{'Nombre de sandwiches'} ,
$products->Poids ,
$products->{'Assortiment 1'} ,
$products->{'Assortiment 2'} ,
$products->{'Assortiment 3'} ,
$products->{'Assortiment 4'} ,
$products->{'Couleur Ruban'} ,
number_format($products->Prix, 2) ,
number_format($products->Supplément, 2) ,
number_format($products->{'Supplément décoration'}, 2) ,
number_format($products->Total, 2)
]))}}

Related

How to return images sequentially inside a "for loop"?

My view displays collections from four different tables. $redtable is my longest collection.
#for ($i = 0; $counter < $redtable->count(); $i++)
<div>
{{ $red->slice($i, 1)->first()?->content }}
{{ $green->slice($i, 1)->first()?->content }}
{{ $blue->slice($i, 1)->first()?->content }}
{{ $gray->slice($i, 1)->first()?->content }}
<div>
#endfor
My image table:
+----+------------------------------------+-------------------------+--------------+
| id | image | imageable_type | imageable_id |
+----+------------------------------------+-------------------------+--------------+
| 1 | /path/redtable/image.png | App\Models\Red | 1 |
| 2 | /path/greentable/image.png | App\Models\Green | 1 |
| 3 | /path/blue/image1.png | App\Models\Blue | 1 |
| 4 | /path/blue/image2.png | App\Models\Blue | 1 |
| 5 | /path/blue/image3.png | App\Models\Blue | 1 |
| 6 | /path/blue/image4.png | App\Models\Blue | 1 |
| 7 | /path/blue/image5.png | App\Models\Blue | 1 |
| 8 | /path/gray/image.png | App\Models\Gray | 2 |
+----+------------------------------------+-------------------------+--------------+
My Controller:
class ColorsController extends Controller
{
public function index()
{
$red = \App\Models\Red::with('polymorphicRelationship')->limit(3)->orderby('id', 'desc')->get();
$green = \App\Models\Green::with('polymorphicRelationship')->limit(3)->orderby('id', 'desc')->get();
$blue = \App\Models\Blue::with('polymorphicRelationship')->limit(3)->orderby('id', 'desc')->get();
$gray = \App\Models\Gray::with('polymorphicRelationship')->limit(3)->orderby('id', 'desc')->get();
return view('home.colors', [
'red' => $red,
'green' => $green,
'blue' => $blue,
'gray' => $gray
]);
}
How to display the images of the "Model Blue" table in the view.
I did a test using $picture->first()?->polymorphicRelationship()->first()->image, but it only displays the image of the first line of the table.
#for ($i = 0; $counter < $red->count(); $i++)
<div class="general">
{{ $red->slice($i, 1)->first()?->content }}
{{ $green->slice($i, 1)->first()?->content }}
{{ $blue->slice($i, 1)->first()?->content }}
<div class="slide">
<!-- First slide image -->
{{ $blue->polymorphicRelationship->image1 }}
<!-- Second slide image -->
{{ $blue->polymorphicRelationship->image1 }}
<!-- Third slide image -->
{{ $blue->polymorphicRelationship->image1 }}
<!-- Fourth slide image -->
{{ $blue->polymorphicRelationship->image1 }}
<!-- Fifth slide image -->
{{ $blue->polymorphicRelationship->image1 }}
</div>
{{ $graytable->slice($i, 1)->first()?->content }}
</div>
#endfor
Assumming the relationship is defined as a polymorphic one to many, you can just add another loop.
Also you can replace slice($i, 1)->first() with get($i).
#for ($i = 0; $counter < $red->count(); $i++)
<div class="general">
{{ $red->get($i)?->content }}
{{ $green->get($i)?->content }}
{{ $blue->get($i)?->content }}
<div class="slide">
#foreach ($blue->polymorphicRelationship as $image)
{{ $image->image }}
#endforeach
</div>
{{ $graytable->get($i)?->content }}
</div>
#endfor

Check for relation laravel and print results

I have relation, in foreach I check if exists this relation then print result, but if else then print results without relation.
#foreach($attr as $at)
#if($at->related)
<option value="{{ $at->related->id }}">
#if($at->value)
{{ $at->related->value }}
#else
{{ $at->related->extra['first_name'] ? 'First Name and Lastname: ' . $at->related->extra['first_name'] : '' }} {{ $at->related->extra['last_name'] }} |
{{ $at->related->extra['email'] ? 'Email: ' . $at->related->extra['email'] : '' }} |
{{ $at->related->extra['telephone'] ? 'Tel: ' . $at->related->extra['telephone'] : '' }}
#endif
</option>
#else
<option value="{{ $at->id }}">
#if($at->value)
{{ $at->value }}
#else
{{ $at->extra['first_name'] ? 'First Name and Lastname: ' . $at->extra['first_name'] : '' }} {{ $at->extra['last_name'] }} |
{{ $at->extra['email'] ? 'Email: ' . $at->extra['email'] : '' }} |
{{ $at->extra['telephone'] ? 'Tel: ' . $at->extra['telephone'] : '' }}
#endif
</option>
#endif #endforeach
I get all results and with relation and without relation. How I can fix this? Condition is not working.
In $attr I have array with models Attribute:
$attrs = Attribute::with('related')->get()->groupBy('attr_id');
When you do groupBy('attr_id') Laravel Collection creates collection of a collection based on id.
The correct implementation would be a nested foreach loop to iterate through collections.
Collection:
$attrCollection = Attribute::with('related')->get()->groupBy('attr_id');
Blade file:
#foreach($attrCollection as $attr)
#foreach($attr as $at)
#if(! is_null($at->related) )
<option value="{{ $at->related->id }}">
#if($at->value)
{{ $at->related->value }}
#else
{{ $at->related->extra['first_name'] ? 'First Name and Lastname: ' . $at->related->extra['first_name'] : '' }} {{ $at->related->extra['last_name'] }} |
{{ $at->related->extra['email'] ? 'Email: ' . $at->related->extra['email'] : '' }} |
{{ $at->related->extra['telephone'] ? 'Tel: ' . $at->related->extra['telephone'] : '' }}
#endif
</option>
#else
<option value="{{ $at->id }}">
#if($at->value)
{{ $at->value }}
#else
{{ $at->extra['first_name'] ? 'First Name and Lastname: ' . $at->extra['first_name'] : '' }} {{ $at->extra['last_name'] }} |
{{ $at->extra['email'] ? 'Email: ' . $at->extra['email'] : '' }} |
{{ $at->extra['telephone'] ? 'Tel: ' . $at->extra['telephone'] : '' }}
#endif
</option>
#endif
#endforeach
#endforeach
Try by changing if condition from
#if($at->related)
to
#if(!empty($at->related))
Replace
#if($at->related)
with
#if(!$at->related->isEmpty())

Laravel array loop

I have shipping method where will calculate price, this codes/prices etc. comes from third-party website (nothing stored in my database).
my problem is i don't know how to get objects that i need!
here is screen shot of my data on dd
my function
public function index() {
$province = RajaOngkir::Provinsi()->all();
// this part will return dd image above
$cost = RajaOngkir::Cost([
'origin' => 501, // id kota asal
'destination' => 114, // id kota tujuan
'weight' => 1000, // berat satuan gram
'courier' => 'jne', // kode kurir pengantar ( jne / tiki / pos )
])->get();
return view('welcome', compact('province', 'cost'));
}
my view codes blade
#foreach($cost as $option)
{{$option['code']}} <br>
{{$option['name']}}
#endforeach
PS: I got my dd with {{dd($option)}} in my loop(#foreach)
So far my loop return this (compare to dd to):
You can do something like:
#if(!empty($cost))
#foreach($cost as $option)
{{$option['code']} <br>
{{$option['name']}} <br>
#if(!empty($option['costs']))
#foreach($option['costs'] as $cost)
{{$cost['service']}} <br>
{{$cost['description']}} <br>
#if(!empty($cost['cost'])
#foreach($cost['cost'] as $c)
{{ $c['value'] }} <br>
{{ $c['etd'] }} <br>
{{ $c['note'] }} <br>
#endforeach
#endif
#endforeach
#endif
#endforeach
#endif
try this :
#foreach($cost as $option)
{{$option['code']}} <br>
{{$option['name'] }} <br>
#foreach($option['costs'] as $cost)
#foreach($cost as $arr)
{{$arr['service'] }} <br>
{{$arr['description']}} <br>
#foreach($arr['cost'] as $c)
{{ $c['value'] }} <br>
{{ $c['etd'] }} <br>
{{ $c['note'] }} <br>
#endforeach
#endforeach
#endforeach
#endforeach

Is it possible to set/insert a new variable in $_GET | $_POST | $_SESSION | $_COOKIE from TWIG?

I have a requirement which which might require me to set a new variable in TWIG for
{{ app.request.query }} i.e. ($_GET)
{{ app.request.request }} i.e. ($_POST)
{{ app.request.session }} i.e. ($_SESSION)
{{ app.request.cookies }} i.e. ($_COOKIE)
e.g. {% app.request.query.set('myvariable':'value' %} ...
If you want to set the variable while in TWIG here is what I know:
For $_POST variables use this :
{{ app.request.request.add(['var1', 'data1']) }}
{{ app.request.request.get(0) }}
{{ app.request.request.get(1) }}
For $_GET variables use this :
{{ app.request.query.add(['var2', 'data2']) }}
{{ app.request.query.get(0) }}
{{ app.request.query.get(1) }}
For $_COOKIE variables use this :
{{ app.request.cookies.add(['var3' , 'data3']) }}
{{ app.request.cookies.get(0) }}
{{ app.request.cookies.get(1) }}
For $_SESSION variables use this :
{{ app.session.set('var4', 'data4') }}
{{ app.session.get('var4') }} <!-- shows 'data4 -->
Or
{{ app.request.session.set('var4', 'data4') }}
{{ app.request.session.get('var4') }} # shows 'data4
You can easy append element to the array before calling Twig->render in PHP.
Simply write
$_GET['myvariable'] = $value

preg_match_all not matching all possibilities

I'm trying to retrieve all matches however I am only receiving one
Here is my string
$html = '<p> This is my Home Page.</p><p><span style="line-height: 1.42857;">{{ type="slider" }} </span></p><p> </p>';
If you see string contain {{ type="slider" }} , now if i write this string only once i am getting my expected result,
but if i write it multiple times in html sting like {{ type="slider" }} {{ type="banned" }} {{ type="testimonial" }}
$html = '<p> This is my Home Page.</p><p><span style="line-height: 1.42857;">{{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }} </span></p><p> </p>';
and try to get the values within my string {{ type=" ???? " }} it shows weird result
I am using this below code .
preg_match_all('/{{ type=\"(.+)\" }}/', $html, $matches, PREG_SET_ORDER);
echo "<pre>";
print_r($matches);
foreach ($matches as $val) {
echo "matched: ". $val[0] . "<br/>";
echo "My Value" . $val[1] . "<br/>";
}
Current Result :
Array
(
[0] => Array
(
[0] => {{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }}
[1] => slider" }} {{ type="banner" }} {{ type="testimonial
)
)
matched: {{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }}
My Value : slider" }} {{ type="banner" }} {{ type="testimonial
I am expecting result in array with the values written between {{ type=" and " }}
with {{ type="slider" }} only i am getting this result which is perfect.
Array
(
[0] => Array
(
[0] => {{ type="slider" }}
[1] => slider
)
)
matched: {{ type="slider" }}
My Value : slider
Any idea ?
Sorry for my bad english.
You need to make your regex match non-greedy by adding either a ? :
preg_match_all('/{{ type=\"(.+?)\" }}/', $html, $matches, PREG_SET_ORDER);
or the U modifier:
preg_match_all('/{{ type=\"(.+)\" }}/U', $html, $matches, PREG_SET_ORDER);
What you're currently getting is pretty normal, since by default your regexp is greedy, i.e. /{{ type="(.+)"}} / looks for the longest string beginning with {{ type=" and ending with }}.
Another answer here suggests you to add a "not-greedy" quantifier ? and it'll work but it's not the best solution (because it'll need more work from the regex engine).
Instead you'd better to merely replace (.+) by ([^"]+) in your regexp.

Categories