Search code examples
laravellaravel-8laravel-routing

Laravel - Point all route requests to single view or function


I have a master view and want all my GET routes return the same every time. E.g

Route::get('/user', function() {
  view('layout');
});
Route::get('/user/add', function() {
  view('layout');
});

How to write a single route function so that returns layout view every time? It means in any case or any number of parameters passed, it should always return layout view.


Solution

  • You can use variables in your route definition. This will hit on all routes.

    Route::get('/{route?}', function() {
      view('layout');
    });
    

    A better approach in my opinion is to look how CMS structures do it. And do it with sections of the URL and you can handle it for more customization.

    Route::get('/{model?}/{action?}', function($model, $action) {
        if ($model === 'user') {
            return view('user', compact('action'));
        } 
    
        return view('default');
    });