When building dynamic components or pages sometimes we want to display a custom template if it exists or otherwise falls back on a default one.
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:
https://www.youtube.com/watch?v=n32SwdlvAPI
Using View:: first
The view()->first() method allows us to replace the following code:
if (view()->exists('template1')) {
return view('template1', $data);
}
return view('1template2', $data);
With a simpler, more expressive version:
return view()->first(
['template1', 'template2'], $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:
return view()->first([
"pages/{$page->slug}",
"pages/category-{$page->category->slug}",
"pages/default-template"
], $data);
Remember you can also use this feature using its facade version:
\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.
No comments:
Post a Comment