Dynamic templates in Laravel Blade with View::first


September 13th, 2017


When building dynamic components or pages sometimes we want to display a custom template if it exists or otherwise fall back on a default one.

For example, imagine we are building a pages module, and some pages like “About Us” or “Contact Us” will need a custom template (for example to display pictures or a contact form), while others like “Terms of services” will do fine with a default template.

We can solve this problem with a series of conditionals or by using view()->exists() to check if a custom template exists or not, however, Laravel 5.5 brings us a better and more elegant way as I’ll demonstrate in the following video:

Using View::first

The view()->first() method allows us to replace the following code:

1if (view()->exists('custom-template')) {
2 return view('custom-template', $data);
5return view('default-template', $data);

With a simpler, more expressive version:

1return view()->first(
2 ['custom-template', 'default-template'], $data

You have to pass an array of templates as the first argument and the first method will load the first template it finds.

Of course, you can pass as many templates as you want and even use dynamic names:

1return view()->first([
2 "pages/{$page->slug}",
3 "pages/category-{$page->category->slug}",
4 "pages/default-template"
5], $data);

Remember you can also use this feature using its facade version:

1\View::first($templates, $data)

This dynamic view loading feature was added to Blade in Laravel v5.5 and is a great way of keeping your controllers simple by avoiding extra conditionals when dealing with dynamic templates.

Filed in:

Duilio Palacios

I am a PHP/Laravel developer and teacher. I created Styde.net, a website dedicated to teach PHP, Laravel, Vue.js and other web technologies to the Spanish community.