Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

Conditionally Include Partial Views in Laravel Blade

Learn how to conditionally include your partial views in Laravel to have a better flexibility when loading the views

Created on Jun 28, 2021

26 views

Sometimes including partials view in Laravel causes an error because the view doesn't exist. To avoid that you can conditionally load to determine if there are partials to load or if the criteria met the condition.

So instead of using the commonly "include" blade directive like below.
@include('partials.announcement', ['status' => 'complete'])

You can instead make use of "includeIf" directive and when the "announcement" partials exist, they will be imported to the views, otherwise, no partials will be loaded.
@includeIf('partials.announcement', ['status' => 'complete'])

In the case that you want to include the views only on truthy condition then make use of "includeWhen" and specify the boolean condition.
@includeWhen($boolean, 'view.name', ['status' => 'complete'])

Otherwise, you can define the inverse condition and define it using "includeUnless" like below.
@includeUnless($boolean, 'view.name', ['status' => 'complete'])

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More