Learn about usages of $loop Variable in laravel blade?

Today now in this post i will share with you usages of  $loop variable of blade. We are know that Laravel is provides us several features in API, Mail, Model, Blade Template etc. So now today we learn feature $loop variable of blade view in Laravel application.

We know laravel Blade templating language is provides us several things as like @if, @foreach, @include etc and you know that this thing is very well. We know in laravel 5.3 is give a new variable $loop in blade template engine and also we can use it with @foreach.

We know by using $loop variable we can simply get the first and the last records. Sometimes we need to give the difference layout of first element and also last element of loop. So, we can simply do that task by using bellow example.

So, now in this article i will give you a simple example how to use the $loop variable.

at First declare a new route as like as bellow:


Ok, now we need to create a new HomeController with the feature method.

But make sure that you need a users table and also with 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 need to create a blade file and we will by use $loop variable in this file. so now create feature.blade.php file and put the bellow code.


<!DOCTYPE html>
	<title>Laravel 5.3 loop variable</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    @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>

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.