Laravel Include When Directive

News

March 1st, 2017

include-when.png

A new feature in Laravel Blade is an includeWhen directive. This allows you to simplify a typical if statement into a single line.

“I think it’s a cool feature as it tidies up so much boilerplate”, said James Brooks, the author of the pull request.

To see this feature in use pretend you have this common setup:

1@if(Auth::user())
2 @include('nav.user')
3@endif

Now, this can be simplified using includeWhen:

1@includeWhen(Auth::user(), 'nav.user')

Or as another example for those using Laravel’s Authorization system:

1@if ($user->ownsPost($post)
2 @include('posts.edit-controls', ['post' => $post])
3@endif

Can be changed to the following:

1@includeWhen($user->ownsPost($post), 'posts.edit-controls', ['post' => $post])

This feature is now included in Laravel and you can run a composer update to be sure you are on the latest release. For more Blade features check out the Laravel Blade category here on Laravel News.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.