Reputation:
Basically, I'm passing a variable employees from the StaticPagesController to about.blade.php When looping through @foreach, I want the code to know if it's the last element so it will output the employee's name without comma. Neither of these would work.
1.
@foreach($employees as $employee)
@if($employee == end($employees))
{{ $employee->first_name }} {{ $employee->last_name }}
@else
{{ $employee->first_name }} {{ $employee->last_name }},
@endif
@endforeach
enter code here
2.
@foreach($employees as $employee)
@if($employees->last())
{{ $employee->first_name }} {{ $employee->last_name }}
@else
{{ $employee->first_name }} {{ $employee->last_name }},
@endif
@endforeach
Upvotes: 4
Views: 12185
Reputation: 2632
It's easier since Laravel 5.3 : you have a $loop variable in all @foreach :
https://laravel.com/docs/5.3/blade#the-loop-variable
@foreach($employees as $employee)
@if ($loop->last)
// This is the last iteration.
{{ $employee->first_name }} {{ $employee->last_name }}
@else
{{ $employee->first_name }} {{ $employee->last_name }},
@endif
@endforeach
A shortest alternative can be :
@foreach($employees as $employee)
{{ $employee->first_name }} {{ $employee->last_name }}{{ ($loop->last ? '' : ',') }}
@endforeach
Note that $loop->first also exists.
Upvotes: 6
Reputation: 329
From my understanding, the logic of your code is comparing the value of each element with the value of the last element to determine whether it's the last element and avoid the trailing comma.
If there are 2 persons having exactly the same details, one happen to be the last, you may have a partial list rendered.
I suggest you use for loop instead of foreach and compare element index instead of value. Code:-
@for ($i = 0; $i < count($employees); $i++)
@if ($i + 1 < count($employees))
{{ $employees[$i]->first_name }} {{ $employees[$i]->last_name }},
@else
{{ $employees[$i]->first_name }} {{ $employees[$i]->last_name }}
@endif
@endfor
Upvotes: 2
Reputation: 584
Here's the code you probably want:
@foreach($employees as $employee)
@if($employees->last() === $employee)
{{ $employee->first_name }} {{ $employee->last_name }}
@else
{{ $employee->first_name }} {{ $employee->last_name }},
@endif
@endforeach
So here I am comparing the last()
employee to the current $employee
. When it reaches the last $employee
, it will be the same as last()
.
Upvotes: 4