@markdown# $loop variable in foreachInside of foreach loop, check if current entry is first/last by just using `$loop` variable.```blade@foreach ($users as $user) @if ($loop->first) This is the first iteration. @endif @if ($loop->last) This is the last iteration. @endif

This is user {{ $user->id }}

@endforeach```There are also other properties like `$loop->iteration` or `$loop->count`.Learn more on the [official documentation](https://laravel.com/docs/master/blade#the-loop-variable).### Does view file exist?You can check if View file exists before actually loading it.```phpif (view()->exists('custom.page')) { // Load the view}```You can even load an array of views and only the first existing will be actually loaded.```phpreturn view()->first(['custom.dashboard', 'dashboard'], $data);```### Error code Blade pagesIf you want to create a specific error page for some HTTP code, like 500 - just create a blade file with this code as filename, in `resources/views/errors/500.blade.php`, or `403.blade.php` etc, and it will automatically be loaded in case of that error code.### View without controllersIf you want route to just show a certain view, don't create a Controller method, just use `Route::view()` function.```php// Instead of thisRoute::get('about', 'TextsController@about');// And thisclass TextsController extends Controller{ public function about() { return view('texts.about'); }}// Do thisRoute::view('about', 'texts.about');```### Blade @authInstead of if-statement to check logged in user, use `@auth` directive.Typical way:```blade@if(auth()->user()) // The user is authenticated.@endif```Shorter:```blade@auth // The user is authenticated.@endauth```The opposite is `@guest` directive:```blade@guest // The user is not authenticated.@endguest```### Two-level $loop variable in BladeIn Blade's foreach you can use $loop variable even in two-level loop to reach parent variable.```blade@foreach ($users as $user) @foreach ($user->posts as $post) @if ($loop->parent->first) This is first iteration of the parent loop. @endif @endforeach@endforeach```### Create Your Own Blade DirectiveIt’s very easy - just add your own method in `app/Providers/AppServiceProvider.php`. For example, if you want to have this for replace `
` tags with new lines:```blade```Add this directive to AppServiceProvider’s `boot()` method:```phppublic function boot(){ Blade::directive('br2nl', function ($string) { return "/i', \"\n\", $string); ?>"; });}```### Blade Directives: IncludeIf, IncludeWhen, IncludeFirstIf you are not sure whether your Blade partial file actually would exist, you may use these condition commands:This will load header only if Blade file exists```blade@includeIf('partials.header')```This will load header only for user with role_id 1```blade@includeWhen(auth()->user()->role_id == 1, 'partials.header')```This will try to load adminlte.header, if missing - will load default.header```blade@includeFirst('adminlte.header', 'default.header')```### Use Laravel Blade-X variable binding to save even more space```php// Using include, the old way@include("components.post", ["title" => $post->title])// Using Blade-X// Using Blade-X variable binding```Tip given by [@anwar_nairi](https://twitter.com/anwar_nairi/status/1442441888787795970)### Blade components props```php// button.blade.php@props(['rounded' => false])// view.blade.php// Non-rounded:Submit// Rounded:Submit```Tip given by [@godismyjudge95](https://twitter.com/godismyjudge95/status/1448825909167931396)### Blade Autocomplete typehint```php@php /* @var App\Models\User $user */@endphp
// your ide will typehint the property for you {{$user->email}}
```Tip given by [@freekmurze](https://twitter.com/freekmurze/status/1455466663927746560)### Component Syntax TipDid you know that if you pass colon (:) before the component parameter, you can directly pass variables without print statement `{{ }}`?```php// you can do instead```Tip given by [@sky_0xs](https://twitter.com/sky_0xs/status/1457056634363072520)### Automatically highlight nav linksAutomatically highlight nav links when exact URL matches, or pass a path or route name pattern.
A Blade component with request and CSS classes helpers makes it ridiculously simple to show active/inactive state.```phpclass NavLink extends Component{ public function __construct($href, $active = null) { $this->href = $href; $this->active = $active ?? $href; } public function render(): View { $classes = ['font-medium', 'py-2', 'text-primary' => $this->isActive()]; return view('components.nav-link', [ 'class' => Arr::toCssClasses($classes); ]); } protected function isActive(): bool { if (is_bool($this->active)) { return $this->active; } if (request()->is($this->active)) { return true; } if (request()->fullUrlIs($this->active)) { return true; } return request()->routeIs($this->active); }}``````bladeclass($class) }}> {{ $slot }}``````bladeProjectsProjectsProjectsProjects```Tip given by [@mpskovvang](https://twitter.com/mpskovvang/status/1459646197635944455)### Cleanup loopsDid you know the Blade `@each` directive can help cleanup loops in your templates?```blade// good@foreach($item in $items)

Name: {{ $item->name }}

Price: {{ $item->price }}

@endforeach// better (HTML extracted into partial)@each('partials.item', $items, 'item')```Tip given by [@kirschbaum_dev](https://twitter.com/kirschbaum_dev/status/1463205294914297861)### Simple way to tidy up your Blade viewsA simple way to tidy up your Blade views!
Use the `forelse loop`, instead of a `foreach loop` nested in an if statement```blade@if ($orders->count()) @foreach($orders as $order)
{{ $order->id }}
@endforeach@else

You haven't placed any orders yet.

@endif@forelse($orders as $order)
{{ $order->id }}
@empty

You haven't placed any orders yet.

@endforelse```Tip given by [@alexjgarrett](https://twitter.com/alexjgarrett/status/1465674086022107137)### Checked blade directiveIn Laravel 9, you'll be able to use the cool new "checked" Blade directive.
This is going to be a nice addition that we can use to clean up our Blade views a little bit```php// Before Laravel 9:active) ? 'checked' : '' }}/>active) ? '' : 'checked' }}/>// Laravel 9active))/>active))/>```Tip given by [@AshAllenDesign](https://twitter.com/AshAllenDesign/status/1489567000812736513)@endmarkdown
We use cookies to improve your experience and to help us understand how you use our site. By using this site, you accept our use of cookies. Cookie Info x