Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'); 
like image 251
chmoelders Avatar asked Sep 10 '14 13:09

chmoelders


People also ask

What are routes in Laravel explain Route handling with controller and route parameters?

Routing in Laravel allows you to route all your application requests to its appropriate controller. The main and primary routes in Laravel acknowledge and accept a URI (Uniform Resource Identifier) along with a closure, given that it should have to be a simple and expressive way of routing.

What is Route parameter in Laravel?

Laravel routes are located in the app/Http/routes. php file. A route usually has the URL path, and a handler function callback, which is usually a function written in a certain controller.

Can we pass in multiple parameters to a route?

Passing Multiple Parameters Using Route to Controller In this example, will first define a route with multiple parameters and then we will add a controller method accepting multiple parameters. Then we will setup a link with named route having multiple parameters.


2 Answers

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');
    }

}
like image 102
Antonio Carlos Ribeiro Avatar answered Oct 17 '22 00:10

Antonio Carlos Ribeiro


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');
}
like image 33
Erusso87 Avatar answered Oct 16 '22 22:10

Erusso87