Laravel route pass variable to controller
I feel like the tidiest way to do this is probably with route constraints:
Route::get('{milk}', [ 'as' => 'milk', 'uses' => 'ProductsController@index' ])
->where('milk', 'milk'); // matches the named arg {milk} (param 1)
// to the regex literal 'milk' (param 2)
It has some redundancy, but if you want to do it purely from your routes, I'd go with this.
For making SEO-friendly names though, you could use Sluggable to generate a unique slug for each product, then create the following route:
Route::get('{product}', [ 'as' => 'product', 'before' => 'product-slug', 'uses' => 'ProductsController@index' ])
->where('product', '[a-z0-9]+[a-z0-9\-]*'); // valid slug syntax
And this filter:
Route::filter('product-slug', function($route) {
$slug = $route->getParameter( 'slug' );
if (is_numeric($slug)) { // if the slug is an ID
$product = Product::findOrFail($slug); // try to find the product
return Redirect::route('product', $product->slug); // and redirect to it
}
});
I have used this to pass values to the controller...
route:
Route::get('user/{user}/usermanage', array('as' => 'userdata.usermanage', 'uses' => 'yourController@getUserDetails'));
//{user} - holds some value...
in controller:
public function getUserDetails($id)
{
...
}
if want dynamic :
$var = "Lists";
Route::get('something', array('as' => 'something', 'uses' => 'yourController@get'.$var));
hope this helps...
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)');