Laravel $loop Variable New Feature Example
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:
routes/web.php
Route::get('feature','HomeController@feature');
Ok, now we have to create new HomeController with feature method.
But make sure you have users table and some dummy records for testing.
app/Http/Controllers/HomeController.php
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.
resources/views/feature.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.3 loop variable</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<ul>
@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>
@else
<li>{{ $user->email }}</li>
@endif
@endif
@endforeach
</ul>
</body>
</html>
Now, you can check...
Maybe it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Install Tailwind CSS Example
- How to Add Two Factor Authentication with SMS in Laravel?
- How to Setup Database in Laravel Vapor?
- Laravel Blade If Condition Example
- Laravel Send SMS to Mobile with Nexmo Example
- How to Send SMS using Twilio in Laravel?
- Laravel Livewire Change Event Example
- Laravel Carbon Get Current Date Time Example
- Laravel Livewire Datatables Example Tutorial
- Laravel Global Scope Tutorial Example
- Laravel Generate Slug from Title Example
- Laravel Where Clause with date_format() Example
- How to Define Global Variables in Laravel?