for loop with iteration in blade - php

i would like to know how to do in blade to have the equivalent of this code. I need to do an iteration inside a foreach . i see the blade loop variable like $loop->index or $loop->remaining but I need to know how to use it to make the equivalent of the code below.
<?php
for( $i = 0 ; $i < 3 ; $i++ ) {
$result[$i]['id'];
$result[$i]['name'];
$result[$i]['email'];
}
?>
Thank for any help

Thank mhrabiee. i found the solution.
#foreach($things as $thing)
#if( $loop->first or $loop->iteration <= 3 )
<tr>
<td>{{$thing)->id}}</td>
<td>{{$thing)->name}}</td>
<td>{{$thing)->email}}</td>
</tr>
#endif
#endforeach
this start first iteration
$loop->first
and this stop iteration after 3 loop
$loop->iteration <= 3
and voila !

Your question is a bit vague but exact equivalent of your code is something like this:
#for ($i = 0; $i < 3; $i++)
{{ $result[$i]['id'] }}
{{ $result[$i]['name'] }}
{{ $result[$i]['email'] }}
#endfor
By the way if you want to iterate through something like $results array you can do this:
#foreach ($results as $result)
<div>{{ $result->id }}</div>
<div>{{ $result->name }}</div>
<div>{{ $result->email }}</div>
#endforeach
PS: You can learn more about for loops in Laravel's Blade Documentation.

Related

setting variables inside a Laravel foreach loop

I've just started using the framework. In plain PHP after the opening foreach I would then set the variables then close the php tag but then from what I can work out you have to then do the Laravel #foreach tags and then open and close #php. Is there a way around this as it seems like a lot of extra work and code?
#foreach($steps as $row)
#php
$title = $row->title;
$text = $row->text;
$i = 1;
#endphp
<div class="steps-item grid-wrap">
<div class="number"
#if($text || $title)
<div class="text-wrap">
#if($title)
<h2>{{$title}}</h2>
#endif
{!! $text !!}
</div>
#php
$i++;
#endphp
#endif
</div>{{--END steps-item--}}
#endforeach
Since blade is no PHP, you have to return to PHP with that directive. But you can set/use the variables without doing that in your case:
#foreach($steps as $i => $row)
<div class="steps-item grid-wrap">
<div class="number"
#if($text || $title)
<div class="text-wrap">
#if($title)
<h2>{{ $row->title }}</h2>
#endif
{!! $row->text !!}
</div>
#php
$i++;
#endphp
#endif
</div>{{--END steps-item--}}
#endforeach
If you still want to set variables, there's a Laravel package called alexdover/blade-set. But as #brombeer pointed out, in most cases it's highly recommended to set all necessary variables in the controller before passing them to the view.
Use laravel provided loop variables:
$loop->iteration The current loop iteration (starts at 1).
It will increment in every loop iteration automatically.
e.g:
First iteration = $loop->iteration => 1 ;
Second iteration = $loop->iteration => 2 ;
so on until loop ends.
Check docs:
The Loop Variables
You can use a #for directive with sizeof($steps) like that:
#for($i=0; $i<= sizeof($steps)-1; $i++)
#endfor
#foreach ($steps as $row)
<div class="steps-item grid-wrap">
<div class="number">
<div class="text-wrap">
#if ($row->title != '')
<h2>{{$row->title}}</h2>
/* if you want to display another title when its blank you can
use if-else here otherwise not need to use if conditions for
title and text */
#endif
#if ($row->text != '')
{!! $row->text !!}
#endif
</div>
</div>
</div>
#endforeach
{{--
for an example you have $steps values like
$steps =
Array(
[0] -> 1,
[1] -> 'title',
[2] -> 'text'
);
if you want this array key value pair you have to use #foreach like
#foreach ($steps as $key=>$value)
#endforeach
you can use key value in #foreach loop only
--}}

how to add index in laravel blade html attribute while calling collection

I am calling categories collection from controller and displaying in the blade in foreach loops
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="1">{{ $subcategory->name }}</a>
#endforeach
#endforeach
I need to add index numbers generated in the loop from 1 in data-column value
data-column="1"
data-column="2"
data-column="3"
so on....in
For doing this you need to make a variable for counting after that you should pass that variable to view like below.
I am inside a method
public function getSingle($slug){
$category= Post::where('slug','=',$slug)->first();
if ($post != null) {
$counter = 0;
return view('blog.single')->withCategories($category)->withCounter($counter);
} else {
return view('error.error404');
}
}
After that you should access that Counter variable in view like below
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="{{$counter++}}">{{ $subcategory->name }}</a>
#endforeach
#endforeach
The classic for will do
#foreach ($categories as $category)
#for ($i = 0; $i < count($category->subcategories); $i++)
<a class="a.toggle-vis" data-column="{{$i}}">{{ $category->subcategories[$i]->name }}</a>
#endfor
#endforeach
For a shorter one, I think, we can do something like this. A little bit dirty in view but in the small snippet, it should be okay.
{{ !($index = 1) }}
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="{{ $index++ }}">{{ $subcategory->name }}</a>
#endforeach
#endforeach
Use this simple solution (Laravel method):
$loop->iteration The current loop iteration (starts at 1).
It will automatically increment, in every loop iteration.
Check docs:
The Loop Variable

Laravel Only display first 5 array

$reviews has 10 arrays and I am trying to only display the first 5. This is what I have come up so far.
#for ($i = 0; $i < 6; $i++)
#foreach ($reviews as $reviews; i++)
<p>Body</p>
#endforeach
#endfor
Any idea why this isn't working?
Just use the take method and run a foreach loop, like so
#foreach($reviews->take(5) as $review)
<p>{{ $review->body }}</p>
#endforeach
I think that is much simpler and cleaner
Assuming you are using Collections you could use the take method (see here) method:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
Usage
$reviews2 = $reviews->take(5);
#foreach ($reviews2 as $review)
<p>{{ $review->body }}</p>
#endforeach
As you are asking .
Any idea why this isn't working?
Because you have syntax error here i++
#for ($i = 0; $i < 6; $i++)
#foreach ($reviews as $key=>$values)
<p>{{$i}} : Body</p>
#endforeach
#endfor
Note : changed $reviews row value as $values
You can use #if to limit the loop inside #foreach
#for ($i = 0; $i < 6; $i++)
#foreach ($reviews as $review)
{{$i++}}
#if ($i < 1)
<p>Body</p>
#endif
#endforeach
#endfor
You have written the wrong syntax of foreach
<?php $i = 1; ?>
#foreach ($reviews as $review)
<p>Body</p>
#if ($i == 5)
break;
#endif
<?php $i++; ?>
#endforeach

foreach in blade template not working correctly

I'm having issues on displaying my data from foreach loop. I have 400+ thumbs on my database but laravel doesn't not work correctly, and my footer template didn't display too. I will put my code below.
#foreach($thumbs as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach
myfooter code goes here.
from my controllers
$data['thumbs'] = thumb::all();
return View('tubetour/home',$data);
but when I tried to var_dump or return the value of thumbs on my controller
it displays all my 400+ data.
$data['thumbs'] = thumb::all();
return $data['thumbs'];
You need to pass an associative array as a second argument to the view function:
// Controller
$thumbs = Thumb::all();
return \View::make('tubetour.home', ['thumbs' => $thumbs]);
// View
#foreach($thumbs as $thumb)
{{ $thumb->name }}
{{ $thumb->desc }}
{{ $thumb->place }}
#endforeach
Edit: if you are using laravel 4 you will need to use View::make()
If Thumb is an Eloquent model, then the Thumb::all() will return an Eloquent collection, not an array. In that case you have to update your blade template like so:
#foreach($thumbs as $thumb)
{{ $thumb->name }}
{{ $thumb->desc }}
{{ $thumb->place }}
#endforeach
Hope this solve your issue.
UPDATE
Pass the $thumbs as an array and display it as table.
Update your controller like this:
$data['thumbs'] = thumb::all()->toArray();
return View('tubetour/home', $data);
And your view like this, see how many rows being displayed.
<table>
<thead>
<tr>Id</tr>
<tr>Name</tr>
<td>Desc</td>
<td>Place</td>
</thead>
<tbody>
#for ($i = 0; $i < count($thumbs); $i++)
<tr>
<td>{{ $i }}</td>
<td>{{ $thumbs[$i]['name'] }}</td>
<td>{{ $thumbs[$i]['desc'] }}</td>
<td>{{ $thumbs[$i]['place'] }}</td>
</tr>
#endfor
</tbody>
</table>
UPDATE 2
Blade template example with bootstrap grid:
<div class="row">
#for ($i = 0; $i < count($thumbs); $i++)
<div class="col-md-4">
<img src="img/sample.jpg">
<h3>{{ $thumbs[$i]['name'] }}</h3>
{{ $thumbs[$i]['desc'] }}
</div>
#endfor
</div>
try this
#foreach($data as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach
Update your controller
$data = Thumb::all();
return View::make('tubetour/home')->with("thumbs",$data)
->render();
Then your view with this:
#foreach($thumbs as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach

How to display something only for the first item from the collection in Laravel Blade template

I have a #foreach loop in the Blade template and need to apply special formatting to the first item in the collection. How do I add a conditional to check if this is the first item?
#foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
#endforeach`
Laravel 5.3 provides a $loop variable in foreach loops.
#foreach ($users as $user)
#if ($loop->first)
This is the first iteration.
#endif
#if ($loop->last)
This is the last iteration.
#endif
<p>This is user {{ $user->id }}</p>
#endforeach
Docs: https://laravel.com/docs/5.3/blade#the-loop-variable
SoHo,
The quickest way is to compare the current element with the first element in the array:
#foreach($items as $item)
#if ($item == reset($items )) First Item: #endif
<h4>{{ $item->program_name }}</h4>
#endforeach
Or otherwise, if it's not an associative array, you could check the index value as per the answer above - but that wouldn't work if the array is associative.
Just take the key value
#foreach($items as $index => $item)
#if($index == 0)
...
#endif
<h4>{{ $item->program_name }}</h4>
#endforeach
As of Laravel 7.25, Blade now includes a new #once component, so you can do it like this:
#foreach($items as $item)
#once
<h4>{{ $item->program_name }}</h4> // Displayed only once
#endonce
// ... rest of looped output
#endforeach
Laravel 7.* provides a first() helper function.
{{ $items->first()->program_name }}
*Note that I'm not sure when this was introduced. So, it may not work on earlier versions.
It is only briefly mentioned in the documentation here.
The major problem with Liam Wiltshire's answer is the performance because:
reset($items) rewind the pointer of $items collection again and again at each loop... always with then same result.
Both $item and the result of reset($item) are objects, so $item == reset($items) requires a full comparison of its attributes... demanding more processor time.
A more efficient and elegant way to do that -as Shannon suggests- is to use the Blade's $loop variable:
#foreach($items as $item)
#if ($loop->first) First Item: #endif
<h4>{{ $item->program_name }}</h4>
#endforeach
If you want to apply a special format to the first element, then maybe you could do something like (using the ternary conditional operator ?: ):
#foreach($items as $item)
<h4 {!! $loop->first ? 'class="special"': '' !!}>{{ $item->program_name }}</h4>
#endforeach
Note the use of {!! and !!} tags instead of {{ }} notation to avoid html encoding of the double quotes around of special string.
Regards.
if you need only the first element you can use #break inside your #foreach or #if.see example:
#foreach($media as $m)
#if ($m->title == $loc->title) :
<img class="card-img-top img-fluid" src="images/{{ $m->img }}">
#break
#endif
#endforeach
you can do it by this way.
collect($users )->first();
To get the first element of a collection in Laravel, you can use :
#foreach($items as $item)
#if($item == $items->first()) {{-- first item --}}
<h4>{{$item->program_name}}</h4>
#else
<h5>{{$item->program_name}}</h5>
#endif
#endforeach

Categories