With Laravel Blade, is there an elegant way to check if a view exists before doing an @include?

For example I'm currently doing this:

@if(View::exists('some-view'))
    @include('some-view')
@endif

Which gets quite cumbersome when 'some-view' is a long string with variables inside.

Ideally I'm looking for something like this:

@includeifexists('some-view')

Or to make @include just output an empty string if the view doesn't exist.

As an aside, I would also like to provide a set of views and the first one that exists is used, e.g.:

@includefirstthatexists(['first-view', 'second-view', 'third-view'])

And if none exist an empty string is output.

How would I go about doing this? Would I need to extend BladeCompiler or is there another way?

upvote
  flag
I'm 95 % certain you need to write your own method for that, but luckily, it's easy: laravel.com/docs/5.1/blade#extending-blade – Joel Hinz
upvote
  flag
Thanks! I'll take a look – Tom P

1 Answers 11

Had a similar issue. Turns out there is an @includeIf blade directive for this purpose.

Simply do @includeIf('some-view')

Not the answer you're looking for? Browse other questions tagged or ask your own question.