19 C
New York
Saturday, August 13, 2022

Laravel 5.3 new feature and update – $loop variable

- Advertisement -





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 AppHttpControllers;


use IlluminateHttpRequest;

use AppHttpRequests;

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…

- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles