How to pass a static variable to a Laravel route?

天大地大妈咪最大 提交于 2019-12-23 19:42:36

问题


I try to rewrite Symfony routes to Laravel routes. The problem is that some Symfony routes take defaults and go the same controller. Can I add some arguments to the Laravel routes to accomplish the same?

e.g. Symfony yaml

 path: /account/
    defaults:
        _controller: "legacy.controller.fallback:Somefunt"
        pag_act: "secret"
        m_act: "home"

 path: /account2/
        defaults:
            _controller: "legacy.controller.fallback:Somefunt"
            pag_act: "public"
            m_act: "home"

e.g. laravel

Route::any('/account', 'SomeSymfonyController@Somefunt');

As you can see: the defaults for these 2 Symfony routes are different (pag_act), can I pass this in Laravel too?


回答1:


Route::any('/account', 'SomeSymfonyController@Somefunt')
      ->defaults('pag_act', 'secret');

Route::any('/account2', 'SomeSymfonyController@Somefunt')
      ->defaults('pag_act', 'public');

and in your SomeSymfonyController Somefunt method

public function Somefunt(Request $request)
{
    dd($request->route('pag_act')); // Returns 'secret' or 'public' based on route
}



回答2:


Simply create another Route::

Route::any('/account', 'SomeSymfonyController@secretFunt');
Route::any('/account2', 'SomeSymfonyController@publicFunt');

In your SomeSymfonyController you could say this:

public function secretFunt()
{
    $pag_act = 'secret';
    $m_act = 'home';
}

public function publicFunt()
{
    $pag_act = 'public';
    $m_act = 'home';
}

In case secretFunt() does the same as publicFunt(), but only the $pag_act's value is different: we don't want duplicate content whenever we process this $pag_act variable. So we can create a function for that:

public function funtHandler($act)
{
    $pag_act = $act;
    $m_act = 'home';
}

public function secretFunt()
{
    $pag_act = 'secret';
    $this->funtHandler($pag_act);
}

public function publicFunt()
{
    $pag_act = 'public';
    $this->funtHandler($pag_act);
}


来源:https://stackoverflow.com/questions/44796752/how-to-pass-a-static-variable-to-a-laravel-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!