Posted by Arjun on Monday 27th November 2017

Laravel 5.5 - Dynamic templates with View::first

Laravel 5.x Laravel 5.5 Dynamic View::first templates

Laravel 5.5 is introduced a new feature called dynamic view loading and it makes your controllers simple and more expressive when dealing with dynamic templates. Using This feature we can avoid plain old conditional statements to load the appropriate template for the request.

For example, let's assume you have different pages and some page have different layout and stylings requirements. Than dynamic view loading is a perfect candidate for this requirement. Let's see how it will look like

public function page($slug) {
    $page = Page::where('slug',$slug)->first();
    return view()->first("pages/{$slug}","pages/default")->with(compact('page'));
}

The first() method is going to load first matched template, if the template doesn't exist,
then it will fallback to second .. and so .. on, you can pass n number of templates to view::first() method.