chmoelders
chmoelders

Reputation: 18674

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

Upvotes: 20

Views: 25770

Answers (6)

elad gasner
elad gasner

Reputation: 745

If you want a more testable solution, you can use Service Provider power.

        $this->app->bind(TestController::class, function ($app) {
            return new TestController(request()->testParam);
        });

Upvotes: 1

Mostafa Lavaei
Mostafa Lavaei

Reputation: 2039

UPDATE FOR LARAVEL 8

you can use the route() method to get the value from the route url parameter from laravel 8:

$id = request()->route('id')

Upvotes: 1

Gabriel Stafoca
Gabriel Stafoca

Reputation: 200

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

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

Upvotes: 5

Erusso87
Erusso87

Reputation: 677

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

Upvotes: 15

simon
simon

Reputation: 1

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/

Upvotes: -1

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87729

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

}

Upvotes: 41

Related Questions