In Laravel Foreach loop is a powerful tool for iterating through arrays or collections of data. Often, you may need to perform specific actions on the first and last elements of the loop. Laravel provides a convenient way to achieve this through the use of $loop
variable, which exposes several properties including $loop->first
and $loop->last
.
Understanding $loop->first and $loop->last
The $loop
variable is automatically available in laravel Foreach loop. It provides information about the current loop iteration, such as the index, iteration count, and whether it is the first or last iteration.
$loop->first
: Returnstrue
if the current iteration is the first one in the loop; otherwise, it returnsfalse
.$loop->last
: Returnstrue
if the current iteration is the last one in the loop; otherwise, it returnsfalse
.
Practical Example
Let’s consider a scenario where we have an array of users, and we want to display a list of their names. Additionally, we want to add special styling to the first and last names in the list.
// Sample array of users
$users = [
['name' => 'John'],
['name' => 'Jane'],
['name' => 'Doe'],
['name' => 'Smith'],
];
// Blade view file
<ul>
@foreach($users as $user)
<li @if($loop->first) class="first" @endif
@if($loop->last) class="last" @endif>
{{ $user['name'] }}
</li>
@endforeach
</ul>
In this example, we use the @foreach
directive to loop through the $users
array. For each user, we check if it is the first or last iteration using $loop->first
and $loop->last
, respectively. If it is the first iteration, we add the CSS class “first” to the <li>
element, and if it is the last iteration, we add the class “last”.
Styling with CSS
Now, you can apply specific styles to the first and last items using the CSS classes we added in the Blade view.
/* CSS Styles */
ul {
list-style: none;
}
li {
margin-bottom: 5px;
padding: 5px;
border: 1px solid #ccc;
}
li.first {
font-weight: bold;
}
li.last {
background-color: #f2f2f2;
}
In this CSS example, we set a border and padding for all list items. We use the li.first
selector to make the text bold for the first item, and the li.last
selector to give a background color to the last item.
Conclusion
Laravel’s $loop
variable makes it easy to handle the first and last iterations in a foreach
loop. Whether you’re applying special styles, performing conditional logic, or any other operation, using $loop->first
and $loop->last
provides a clean and convenient way to manage these scenarios in your Blade views.
Check our tools small Tools
Check our tools website check More tutorial
Check our tools website Word count