Skip to content

Laravel 5.5 – Dynamic templates with View::first

Last updated on February 17, 2018

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments