Laravel (5) - Routing to controller with optional parameters

Steve picture Steve · Apr 28, 2015 · Viewed 86.2k times · Source

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!

Answer

Michael Pittino picture Michael Pittino · Apr 28, 2015

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
}