Mahiran Digital Sdn. Bhd.

In Blade language, there is a simple @include() command where the view path will be pass as a parameter. But what if you are not sure whether the view exists or not? Or what if you want to make it a dynamic variable?

A simple example: @include (‘partials.header’, [‘title’ => ‘First Page’])

Three complicated cases:

1. @includeIf :- View May Be Non-Existent

If the included view file does not exist, Laravel will give fatal error and will not load the page. To avoid this problem, you can check the existence with:

  • @if (view() -> exists(‘partials.header’)) or
  • can use a special command of @includeIf which are @includeIf (‘partials.header’, [‘title’ => ‘First Page’])

2. @includeWhen :- Include Only With Condition

Typical code will be:

@if ($load_header)

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

@endif

The code can be written shorter with a special @includeWhen:

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

3. @includeFirst :- Fallback “Default” View

This case is relevant for projects with multiple “themes” of Blade views.

As an example, you want to load a header for a particular theme but it may not exist, so you fallback to the “default” header.

@includeFirst(‘adminlte.header’, ‘default.header’, [‘title’ => ‘First Page’])

In this case, Laravel will try to load adminlte.header Blade but if it does not exist, the other plan would be to load default.header with the same parameter.

Credit to : https://bit.ly/3DLrW2d

Leave a Reply

Your email address will not be published. Required fields are marked *

Open chat
💬 Need help?
Hello 👋
How can we help you?