Getting first element of loop in blade - laravel-4

I'm trying to get only first element which is presented in the loop. So if I have something like
#foreach($entries as $entry)
#if($element == 1)
// do something
#else
// do something else
#endif
#endforeach

You can use loop.first more information here
#foreach($array as $key => $value)
#if($loop->first)
// do something
#else
// do something else
#endif
#endforeach
By default, blade doesn't have #break and #continue which are useful to have. So that's included.
Furthermore, the $loop variable is introduced inside loops, (almost) exactly like Twig.
loop.first True if first iteration
There is other way also like this but you'll have problems if there is not element starting with 0
....
if($key == 0)
....

Related

How to skip a loop after a certain count to the next loop and back again after a certain count is achieved in the next loop

From the code below, it works just fine but now I'd like to achieve a functionality whereby when the first loop iterates 3 times it breaks then the second loop iterates 3 times and then breaks. And the process starts again from the first loop and repeats again and again.
Blade:
#foreach ($officialOutfits as $outfit)
{{ $outfit }}
#endforeach
#foreach ($casuallOutfits as $outfit)
{{ $outfit }}
#endforeach
Route
Route::get('/products', function () {
$outfits = Outfit::latest()->get();
$officialOutfits = Outfit::where('look', 'official')->latest()->get();
$casualOutfits = Outfit::where('look', 'casual')->get();
return view('products', compact(['casualOutfits', 'officialOutfits']));
})->name('products');
As the DOCUMENTATION states, you can use the $loop variable when on Blade.
So you should have something like this:
#foreach ($officialOutfits as $outfit)
#if ($loop->index >= 3)
#break
#endif
{{ $outfit }}
#endforeach
#foreach ($casuallOutfits as $outfit)
#if ($loop->index >= 3)
#break
#endif
{{ $outfit }}
#endforeach
You set the for loop to only loop three times, that's standard. What you also need is recursion. Recursion is making a function call itself:
function doStuff(){
forloop{
forloop2{
}
}
doStuff();
}
This will go on infinitely if you don't terminate it, so you can set the limit to whatever you want - say, 50 times.
let limit = 0;
while (limit < 50){
function doStuff(){
forloop{
forloop2{
}
}
limit++
doStuff();
}
}

How do I write an #if in Laravel that uses data from my database?

I'm new to Laravel and am using Laravel 6. One of my views is going to contain the values in a row of my MySQL table. The table column is a boolean so it contains either 0 or 1. Rather than displaying 0 or 1 in the view, I want to display YES or NO. An #if seems the logical way to do this but I can't get my #if to work.
#if ({{ $sleepDiaryEntry->outdoorLight }} == 1 )
<p>Two hours of outdoor light? YES</p>
#else
<p>Two hours of outdoor light? NO</p>
#endif
I've tried several variations of the #if but every variation gives me a syntax error on the first line of the #if.
Unfortunately, the Laravel manual is very skimpy on details of exactly what arguments can and cannot appear in an #if. They tend to give an example or two and think they've anticipated every possible situation and question.
How I can accomplish what I want to do, either with or without #if?
remove {{}} in #if, like followings
#if ($sleepDiaryEntry->outdoorLight == 1 )
<p>Two hours of outdoor light? YES</p>
#else
<p>Two hours of outdoor light? NO</p>
#endif
because {{}} for show the variable
I am not sure about what you want but by using {{}} you are trying to print data.
Try :
#if ($sleepDiaryEntry->outdoorLight == 1 )
<p>Two hours of outdoor light? YES</p>
#else
<p>Two hours of outdoor light? NO</p>
#endif
If it doesn't work:
Are you giving $sleepDiaryEntry to the view in your controller method ?
Try to {{ dd($sleepDiaryEntry) }} see what you have in your view.
#if ({{ $sleepDiaryEntry->outdoorLight }} == 1 ) just gets rendered down to:
<?php if ({{ $sleepDiaryEntry->outdoorLight }} == 1 ) { ?>
in the final Blade template, which will cause a syntax error. You don't need the {{ }} tags in the conditional (not just "don't need": they won't be parsed at all here); it takes plain old PHP code in the ().

if the array were empty in laravel . then how to dispaly the message that their are no record found

#foreach($array as $value)
{{$value}}
#endforeach
$array is my array pass from Laravel controller then i want to display the message record not found if the array were empty.
this is my code example.
Besides 'foreach' loops, we also got 'forelse' loops in laravel blade template, what exactly this 'forelse' loops does? and most importantly should we care about it?
The 'forelse' loops is the better version of 'foreach', so yes, you should care, 'forelse' loops works exactly as 'foreach' except it also check the value is empty or not.
So with 'foreach' normally you check first whether the value is empty or not using 'if' statement, using 'forelse' you don't need to do that, the value is automatically checked.
#forelse ($array as $value)
{{ $value }}
#empty
There are no record found.
#endforelse
You can use #forelseas Shoukat Mirza in his answer and you also could use #if clause:
#if (count($array) > 0)
// foreach loop here
#endif
This is also helpful when you have multiple conditionals to check.

is there an index to be accessed in the CI foreach with {}-Notation?

i'm new with Codeigniter,and whish to know if i can access any kind of iterator for the foreach with {}-Notation in my views.
The thing is, i'm having a list which should be devided after each x items.
example (what i would like to do:
<ul>
{list}
<li>{items}</li>
<? if ($iterator % 15 == 0) echo "</ul><ul>"; ?>
{/list}
</ul>
thanks in advice ;-)
If you are using codeigniters template parser class, I don't think there is a way to do what you're looking for.
You could forego the template parser, and use a regular for loop:
<ul>
<?php
$i=1;
foreach($item as $key=>$value){
echo "<li>".$value."</li>";
if($i % 15 === 0) echo "</ul><ul>";
$i++;
}
?>
</ul>

Standard Pattern for Iterating Over Loop and Printing Start and End Tags

This is a problem I have run into before and I have yet to find an elegant solution, so I thought I would ask for SO's help.
I am iterating through an array and printing off some information from that array and having trouble figuring out how to print my start and end <div> tags. Below is an example table and the desired output along with a basic implementation of my current algorithm. I am hoping that somebody can point me to a better algorithm for printing the data. I'm doing it in PHP, but a generic algorithm would be wonderful.
Thanks very much!
Table: (spacing added for clarity)
Choice ID Choice Body Question ID Question Body
---------------------------------------------------------------------
1 Yes, very much 1 Do you like sandwiches?
2 Somewhat 1 Do you like sandwiches?
3 Not at all 1 Do you like sandwiches?
4 I hate them 1 Do you like sandwiches?
5 Sure, why not 2 Do you like apples?
6 Yesh, I guess 2 Do you like apples?
7 What are those 2 Do you like apples?
8 Yes, very much 3 Do you like chips?
9 Not at all 3 Do you like chips?
Desired Output:
<div class='question' id='1'>
<p>Do you like sandwiches?</p>
<div class='choices'>
<span class='choice'>Yes, very much</span>
<span class='choice'>Somewhat</span>
<span class='choice'>Not at all</span>
<span class='choice'>I hate them</span>
</div>
</div>
<div class='question' id='2'>
<p>Do you like apples?</p>
<div class='choices'>
<span class='choice'>Sure, why not</span>
<span class='choice'>Yeah, I guess</span>
<span class='choice'>What are those</span>
</div>
</div>
<div class='question' id='3'>
<p>Do you like chips?</p>
<div class='choices'>
<span class='choice'>Yes, very much</span>
<span class='choice'>Not at all</span>
</div>
</div>
Basic Algorithm I'm Currently Using:
$last_id = null;
while ($choice = pg_fetch_array($choices)) {
if ($last_id != $choice['id']) {
if ($last_id != null) {
echo "</div>";
}
echo "<div id='$choice[id]'>";
}
// Print choice info
$last_id = $choice['id'];
}
if ($last_id != null) {
echo "</div>";
}
Note: The reason I'm using this way is for optimization purposes. This requires only one database query, and there are going to be a lot of results. I don't want to have to do a query for each question to get it's choices. I know how to do that, and it is easier, but not very efficient or fast.
Edit 1: Fixed code, the algorithm now works, but still isn't pretty. For the commenter: pg_fetch_array() is a PostgreSQL function that basically creates an associative array. Very similar to an object. Allows you to just ask for the $choice['id'] or $choice['body'].
Grouping items by similar values can hardly be called an algorithm. It's more of a coding pattern if anything else.
A good way to code is to separate the mechanism from the intent. In this case the mechanism is how to keep track of the key values to find the grouping boundaries and the intent is to output HTML for each sequential group.
Python for instance has a library function called groupby to do exactly this. So in Python the code would look something like this (ignoring the fact that one would use a templating library for this):
from itertools import groupby
def question_from_row(row):
return dict(id=row['question_id'], body=row['question_body'])
for question, choices in groupby(questions, key=question_from_row):
print('<div class="question" id="%s">' % question['id'])
print(' <p>%s</p>\n' % question['body'])
print(' <div class="choices">')
for choice in choices:
print('<span class="choice">%s</span>' % choice['choice_body'])
print(' </div>')
print('</div>')
PHP to my knowledge doesn't have anything like that built in, but a naive implementation is pretty easy:
function array_groupby($input, $keyfunc) {
$output = array();
$last_key = null;
$current = null;
foreach ($input as $item) {
$item_key = $keyfunc($item);
if ($last_key === null || $item_key != $last_key) {
if ($current !== null) {
$output[] = $current;
}
$last_key = $item_key;
$current = array();
}
$current[] = $item;
}
if ($current !== null) {
$output[] = $current;
}
return $output;
}
This would be typical library code that you include in. The code that deals with the output then becomes rather trivial. Completely isolated from how the grouping is done. For instance you could change array_groupby to return an object that implements the Iterator interface and only lazily fetches from the input iterable.
$questions = array_groupby(pg_fetch_array($choices),
function($choice) { return $choice['id']; });
foreach ($questions as $choices) {
$question = $choices[0];
echo '<div class="question" id="'.$question['id'].'">';
echo '<p>'.$question['body'].'</p>';
echo '<div class="choices">';
foreach ($choices as $choice) {
echo '<span class="choice">'.$choice['choice_body'].'</span>';
}
echo '</div>';
echo '</div>';
}
This example is using the PHP 5.3 closures feature. On older versions specifying the function to extract the grouping key would be slightly uglier, perhaps calling for an object oriented approach.
You should print the closing </div> at the beginning of the loop, if the freshly read id is different from last one (and the last one is not null).
Additionally, after the loop (again, if last id is not null, which would mean that there were no groups at all) you need to close the last group.
Been a while since I've done any PHP but I'd try something like this...
// print leading div for very first in array
echo "<div>";
$last_question = null;
while ($choice = pg_fetch_array($choices)) {
// print choice info
echo "<span ...>";
if($last_question != $choice['question_id'])
{
// print trailing div for last one
echo "</div>";
// print leading div for next one
echo "<div>";
}
// set last question
$last_question = $choice['question_id'];
}
// print trailing div for very last in array
echo "</div>";
Might need improving to make sure it doesn't print an extra div at the end.

Resources