If condition in foreach loop in laravel

Updated at 31-Aug-2021, By samar

If condition in foreach loop in laravel

Hello everyone, in this post we will examine how to solve the "If condition in foreach loop in laravel" programming puzzle.

You can use if condition in foreach loop in laravel using @if directive in laravel blade. You can also use if statement in laravel controller as php if statement.
  • First/last item of the array in laravel

    --PATH resources/views/<yourfile>.blade.php
    @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
    

    This code snippet helps you to get the first and last item of the array through the loop iteration. This array variable holds useful information like current loop index and whether this is the first or last iteration through the loop. This is a very useful function to get the first and last elements of an array in laravel using foreach in laravel blade file. 

    This is useful to add css classes to the first and last element in the array through loop iteration and you can manipulate first and last elements of the array as per your requirement.

Back to code snippet queries related laravel