Laravel $loop Variable New Feature Example

By Hardik Savani November 5, 2023 Category : Laravel

Laravel 5.3 provides several new features in API, Mail, Model, Blade Template etc. Today we learn new feature $loop variable of blade view in Laravel 5.3.

Laravel Blade templating language provides several things like @if, @foreach, @include etc and you know this thing very well. Laravel 5.3 give new variable $loop in blade template engine and you can use it with @foreach.

$loop variable through we can simply get first and last records. Sometimes we require to give difference layout of first element and last element of loop. So, you can simply do that task by bellow example.

So, in this article i give simple example how to use $loop variable.

First declare new route like as bellow:



Ok, now we have to create new HomeController with feature method.

But make sure you have users table and some dummy records for testing.


namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use DB;

class HomeController extends Controller


public function feature()


$users = DB::table("users")->get();

return view('feature',compact('users'));



Ok, At Last we have to create blade file and we will use $loop variable in this file. so create feature.blade.php file and put bellow code.


<!DOCTYPE html>



<title>Laravel 5.3 loop variable</title>

<link rel="stylesheet" href="">




@foreach ($users as $user)

@if ($loop->count)

@if ($loop->first)

<li class="text-success">{{ $user->email }}</li>

@elseif ($loop->last)

<li class="text-danger">{{ $user->email }}</li>


<li>{{ $user->email }}</li>







Now, you can check...

Maybe it can help you...