Skip to content

Instantly share code, notes, and snippets.

@willishq
Last active August 9, 2019 21:46
Show Gist options
  • Save willishq/cf2b1fa1cfb788954df0f0b7a7fe7f61 to your computer and use it in GitHub Desktop.
Save willishq/cf2b1fa1cfb788954df0f0b7a7fe7f61 to your computer and use it in GitHub Desktop.
Create a Route macro to route pages to follow a defined pages folder within your views in Laravel.
<?php
//service provider boot method
public function boot()
{
Route::macro('pages', function ($root = 'pages', $prefix = null) {
Route::get($prefix . '/{page?}', function ($path = 'home') use ($root) {
$path = str_replace('/', '.', $path);
$page = trim(sprintf("%s.%s", $root, $path), '.');
if (!view()->exists($page)) {
abort(404);
}
return view($page);
})->where('page', '.*');
});
parent::boot();
}
/** Usage */
Route::pages();
// localhost:8000 -> views/pages/home.blade.php
// localhost:8000/test -> views/pages/test.blade.php
Route::pages('privacy', 'privacy-policy');
// localhost:8000/privacy-policy -> views/privacy/home.blade.php
// localhost:8000/privacy-policy/test -> views/privacy/test.blade.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment