imperium2335 imperium2335 - 4 years ago 209
PHP Question

Laravel route pass variable to controller

How do I pass a hard coded variable to a controller?

My route is:

Route::group(array('prefix' => $locale), function() {
Route::get('/milk', array('as' => 'milk', 'uses' => 'ProductsController@index'));
});


I want to do something like:

Route::get('/milk', array('as' => 'milk', 'uses' => 'ProductsController@index(1)'));


But that doesn't work.

How can this be done?




Sorry if I have not explained well.

I wish to simply hardcode (set in stone by me) the type_id for certain routes like so:

Route::get('/milk', array('as' => 'milk', 'uses' => 'ProductsController@index(1)'));
Route::get('/cheese', array('as' => 'cheese', 'uses' => 'ProductsController@index(2)'));
...


My ProductsController for reference:

class ProductsController extends BaseController {

public function index($type_id) {
$Products = new Products;
$products = $Products->where('type_id', $type_id)->get();
return View::make('products.products', array('products' => $products));
}

}

Answer Source

You can use a closure for your route and then call the controller action:

Route::get('/milk', array('as' => 'milk', function(){
    return App::make('ProductsController')->index(1);
}));

However a nicer way would probably be, to use a where condition and then do the type-to-id conversion in the controller... You will loose the direct alias thought and would have to pass in the product as parameter when generating the URL.

Route::get('{product}', array('as' => 'product', 'uses' => 'ProductsController@index'))
    ->where('product', '(milk|cheese)');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download