Menu

Laravel Blade @include And Helpers

In Blade language there’s a simple @include() command, where you just pass the view path as a parameter. But what if you’re not 100% sure if that view exists? Or what if you want to make it a dynamic variable? Let’s explore the possibilities.

First, a simple example:

@include('partials.header', ['title' => 'First Page'])

Sounds simple, right? Now, let’s discuss three more complicated cases.

 


 

1. @includeIf: View May Be Non-Existent

If the included view file doesn’t exist, Laravel will surely throw fatal error and won’t load the page. To avoid that, you can check the existence with @if (view()->exists(‘partials.header’)) or use a special command @includeIf:

@includeIf('partials.header', ['title' => 'First Page'])

 


 

2. @includeWhen: Include Only With Condition

Typical code would be:

@if ($load_header)
  @include('partials.header', ['title' => 'First Page'])
@endif

Which may be written shorter with special @includeWhen:

@includeWhen($load_header, 'partials.header', ['title' => 'First Page'])

 


 

3. @includeFirst: Fallback “Default” View

This is relevant for projects with multiple “themes” of Blade views. Let’s say, you want to load a header for a particular theme, but it may not exist, so you fallback to the “default” header.

@includeFirst('theme.header', 'default.header', ['title' => 'First Page'])

In this case, Laravel will try to load theme.header Blade, but if it doesn’t exist, the “plan B” would be to load default.header with the same parameters.

Larave Blade Source: Blade official documentation

705
Search

Ads