Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel (5) - Routing to controller with optional parameters

I'd like to create a route that takes a required ID, and optional start and end dates ('Ymd'). If dates are omitted, they fall back to a default. (Say last 30 days) and call a controller....lets say 'path@index'

Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null) {     if(!$start)     {         //set start     }     if(!$end)     {         //set end     }      // What is the syntax that goes here to call 'path@index' with $id, $start, and $end? }); 

Any help would be appreciated. I'm sure there is a simple answer, but I couldn't find anything anywhere.

Thanks in advance for the help!

like image 492
Steve Avatar asked Apr 28 '15 01:04

Steve


People also ask

How do you make an optional parameter in Laravel route?

laravel route optional parameter // You can make a parameter optional by placing a '? ' after the parameter name.

What would be the correct way to declare a route with an optional parameter name?

The route: { path: 'list/:name/:type', loadChildren: './list/list. module#ListModule'}, The :name parameter is required for this route to load correctly, but the :type parameter is optional.

What is route parameter constraint in Laravel?

You always want a route parameter to be constrained by a regular expression; then you can use the pattern method. You can define these patterns in the boot method of your RouteServiceProvider. Global Constraints are used when we have multiple routes, and the same constraints are applied to all the routes.


1 Answers

There is no way to call a controller from a Route:::get closure.

Use:

Route::get('/path/{id}/{start?}/{end?}', 'Controller@index'); 

and handle the parameters in the controller function:

public function index($id, $start = null, $end = null) {     if (!$start) {         // set start     }              if (!$end) {         // set end     }              // do other stuff } 
like image 58
Michael Pittino Avatar answered Sep 25 '22 02:09

Michael Pittino