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(V
I created this blade directive for including the first view that exists, and returns nothing if none of the views exist:
Blade::directive('includeFirstIfExists', function ($expression) {
// Strip parentheses
if (Str::startsWith($expression, '(')) {
$expression = substr($expression, 1, -1);
}
// Generate the string of code to render in the blade
$code = "<?php ";
$code .= "foreach ( {$expression} as \$view ) { ";
$code .= "if ( view()->exists(\$view) ) { ";
$code .= "echo view()->make(\$view, \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ";
$code .= "break; } } ";
$code .= "echo ''; ";
$code .= "?>";
return $code;
});
Had a similar issue. Turns out that from Laravel 5.3 there is an @includeIf
blade directive for this purpose.
Simply do @includeIf('some-view')