Josh Pennington
Josh Pennington

Reputation: 6408

Pass data from routes.php to a controller in Laravel

I am attempting to create a route in Laravel for a dynamic URL to load a particular controller action. I am able to get it to route to a controller using the following code:

Route::get('/something.html', array('uses' => 'MyController@getView'));

What I am having trouble figuring out is how I can pass a variable from this route to the controller. In this case I would like to pass along an id value to the controller action.

Is this possible in Laravel? Is there another way to do this?

Upvotes: 0

Views: 1668

Answers (1)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

You are not giving us enough information, so you need to ask yourself two basic questions: where this information coming from? Can you have access to this information inside your controller without passing it via the routes.php file?

If you are about to produce this information somehow in your ´routes.php´ file:

$information = WhateverService::getInformation();

You cannot pass it here to your controller, because your controller is not really being fired in this file, this is just a list of available routes, wich may or may not be hit at some point. When a route is hit, Laravel will fire the route via another internal service.

But you probably will be able to use the very same line of code in your controller:

class MyController extends BaseController {

    function getView()
    {
        $information = WhateverService::getInformation();

        return View::make('myview')->with(compact('information'));
    }

}

In MVC, Controllers are meant to receive HTTP requests and produce information via Models (or services or repositores) to pass to your Views, which can produce new web pages.

If this information is something you have in your page and you want to sneak it to your something.html route, use a POST method instead of GET:

Route::post('/something.html', array('uses' => 'MyController@getView'));

And inside your controller receive that information via:

class MyController extends BaseController {

    function getView()
    {
        $information = Input::get('information');    

        return View::make('myview')->with(compact('information'));
    }

}

Upvotes: 1

Related Questions