I have several routes in web.php:
Route::get('/','PagesController@index');
Route::get('/contact','PagesController@contact');
and so on...
I need to get in my PagesController the current 'module' (index, contact or smth else).
The Controller's code:
class PagesController extends Controller
{
public function index()
{
$menu = new Menu();
$links = $menu->getMenu();
//$header=url()->current(); // returns the full url, e.g. http://test.com/
//$header=Route::current(); // error: Class Route not found
return view("index",['links'=>$links,'header'=>$header]);
}
}
For example, $header should be equal to "/" inside PagesController@index
and $header = "contact"
inside PagesController@contact
.
I need the universal solution for all the modules I'll have in future.
Thanks a lot!
I have not had a chance to test this, however you should be able to achieve this with the following:
Route::get('/{page?}', function($page = 'index') {
return app('App\Http\Controllers\PageController')->{$page}($page);
});
Basically, this is setting a route to have an optional $page
variable. If no page name is passed (e.g. contact
), we default to index
.
We finally use the app()
helper to call the PageController
and then use the ->{$page}()
syntax to call a dynamic controller method (In the default case index
).
Hope this helps.