27a 27a - 4 months ago 40
PHP Question

Laravel - Get the Last Element of @foreach

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

Answer

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().

Comments