Skip to main content
Tutorial Free

Laravel Blade @include: Three Additional "Helpers"

January 17, 2019
2 min read

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('adminlte.header', 'default.header', ['title' => 'First Page'])

In this case, Laravel will try to load adminlte.header Blade, but if it doesn't exist, the "plan B" would be to load default.header with the same parameters.

Source: Blade official documentation

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.