doujia1679 2018-11-03 05:50
浏览 121
已采纳

获取Controller Laravel内的当前路线

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!

  • 写回答

1条回答 默认 最新

  • dongying3744 2018-11-03 06:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部