While we all hope to spend our time developing interesting sites and apps, sometimes a site just needs some static pages. Maybe it’s the terms of use or the privacy policy, maybe the site you’re working on is mostly a brochure site. Either way, having a /routes/web.php
file full of
// about page (resources/views/about.blade.php) Route::get('about', function() { return View::make('about'); });
is tedious as heck.
Instead of repeating that block of code endlessly, there’s a handy snippet you can add to your /routes/web.php
file to display all your static pages without having to think at all.
Route::get('{level1}/{level2?}/{level3?}', function (...$args) { $path = implode('.', $args); if (view()->exists($path)) { return view($path); } abort(\Illuminate\Http\Response::HTTP_NOT_FOUND, "Page $path not found"); });
(If you haven’t seen (...$args)
before, it’s known as the splat operator.)
(If you’re using response codes like 404 directly in your code, consider using constants on the Response class instead – aside from the good habit of not including magic numbers in your code, it keeps you from spending all day looking up HTTP status codes.)
This should be the last route in your /routes/web.php
file and it serves as a catch-all for any routes which haven’t been matched yet. It looks for a view file which matches the url and displays it. If no matching view is found, it returns a 404.
Using this snippet requires that your view files and folders mirror the structure of your site – http://mysite.com/small-print/privacy is going to look for a view in /resources/views/small-print/privacy.blade.php.
Be First to Comment