Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 225
imperium2335 Avatar asked Nov 10 '14 13:11

imperium2335


People also ask

What is prefix in Laravel route?

Route PrefixesThe prefix method may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin : Route::prefix('admin')->group(function () { Route::get('/users', function () { // Matches The "/admin/users" URL.

How can I get route name in Laravel?

You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request: $route = Route::current(); $name = Route::currentRouteName(); $action = Route::currentRouteAction();

What is reverse routing in Laravel?

Laravel reverse routing is generating URL's based on route declarations. Reverse routing makes your application so much more flexible. For example the below route declaration tells Laravel to execute the action “login” in the users controller when the request's URI is 'login'.


1 Answers

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 be to use a where condition and then do the type-to-id conversion in the controller. You will lose the direct alias though 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)');
like image 82
lukasgeiter Avatar answered Sep 21 '22 01:09

lukasgeiter