Is it possible to pass a route parameter to controller constructor in Laravel?

断了今生、忘了曾经 提交于 2019-12-06 17:12:39

问题


Is it possible to inject a route-paramter (or an route segment) to the controller-constructor?

You find some code to clarify my question.

class TestController{

    protected $_param;

    public function __construct($paramFromRoute)
    {
        $this->param = $paramFromRoute;
    }

    public function testAction()
    {
        return "Hello ".$this->_param;
    }
}

----------------------------------------------------

App::bind('TestController', function($app, $paramFromRoute){
    $controller = new TestController($paramFromRoute);
    return $controller;
});

----------------------------------------------------

// here should be some magic
Route::get('foo/{bar}', 'TestController'); 

回答1:


It's not possible to inject them, but you have access to all of them via:

class TestController{

    protected $_param;

    public function __construct()
    {
        $id = Route::current()->getParameter('id');
    }

}



回答2:


Laravel 5.3.28

You can't inject the parameter... But, you can inject the request and get it from the router instance, like this:

//route: url_to_controller/{param}
public function __construct(Request $request)
{
   $this->param = $request->route()->parameter('param');
}



回答3:


In Laravel 5.4, you can use this to request the parameter:

public function __construct(Request $request) {
   $id = $request->get("id");
}



回答4:


Lastly, but most importantly, you may simply "type-hint" the dependency in the constructor of a class that is resolved by the container, including controllers, event listeners, queue jobs, middleware, and more. In practice, this is how most of your objects are resolved by the container.

http://www.golaravel.com/laravel/docs/5.1/container/



来源:https://stackoverflow.com/questions/25766894/is-it-possible-to-pass-a-route-parameter-to-controller-constructor-in-laravel

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