Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Register a new wildcard route that returns a view if it exists.
*
* @param string $path
* @param string $viewDirectory
* @param array $data
* @return \Illuminate\Routing\Route
*/
\Route::macro('viewDir', function ($path, $viewDirectory = null, $data = []) {
$pathWithSegments = trim($path, '/') . '/{page?}';
$originalPath = $path;
return $this->get($pathWithSegments, function ($path = '') use ($originalPath, $viewDirectory, $data) {
if (is_null($viewDirectory)) {
$viewDirectory = $originalPath;
}
$viewPath = "{$viewDirectory}.{$path}";
if (view()->exists($viewPath)) {
return view($viewPath)->with($data);
}
if (view()->exists($viewPath . '.index')) {
return view($viewPath . '.index')->with($data);
}
abort(404);
})->where('page', '.*');
});

Register the macro by including it in a service provider's register method.

For an example, to see how it works, let's imagine the following route definition:

Route::viewDir('/pages', 'pages');

And the following directory structure for the views:

views/
├── auth/
├── errors/
├── layouts/
├── pages/
│   ├── about-us.blade.php
│   ├── faq.blade.php
│   ├── privacy-policy.blade.php
│   ├── team/
│   │   ├── developers.blade.php
│   │   ├── index.blade.php
│   │   ├── management.blade.php
│   │   └── marketing.blade.php
│   └── terms-of-service.blade.php
└── partials/

The following routes will be generated to match each of the views in the given directory:

/pages/about-us
/pages/faq
/pages/privacy-policy
/pages/team
/pages/team/developers
/pages/team/management
/pages/team/marketing
/pages/terms-of-service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.