Home » Php » Named routes with optional url $param(s) – Laravel 4

Named routes with optional url $param(s) – Laravel 4

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’ve ran into a bit of a quirk with L4 (possibly symfony2?) routing for which I can’t seem to find any resources online or in the wonderful Code Bright, and came up empty in IRC.

I’m trying to use optional params with a named route through a controller, but receive an error when loading the view.

Route:

Route::get('/topic/{topicID?}', array(
    'as'    => 'topicDetails',
    'uses'  => '[email protected]'
));

Controller:

class TopicController extends BaseController {

    public function showTopic($topicID = null)
    {
        $data['topicID'] = $topicID;
        return View::make('topic_view', $data);
    }
}

View

<a href="{{ route('topicDetails') }}">XXX</a>

Error:

Parameter "topicID" for route "topicDetails" must match "[^/]++" ("" given) to generate a corresponding URL.

I’m assuming this isn’t passing the null value to the $param but I’m not familiar enough with L4 to figure out why it isn’t working, and I’ve exhausted all my resources.

Any clues would be greatly appreciated Thanks!

Answers:

this

<a href="{{ route('topicDetails') }}">XXX</a>

should be

<a href="{{ route('topicDetails', null) }}">XXX</a>