Steve Chamaillard
Steve Chamaillard

Reputation: 2339

Have a dynamic optional route parameter in index

I use :

Route::controller('home', 'HomeController');

in my routes to link all routes to my controller.

I have a getIndex() function in my controller that's executed when I go to '/home'.

I have a case where I'd like to route to '/home/slug', but not always.

I tried using getIndex($slug), but it always asks for '/home/index/{slug?}'. I don't want index to appear.

Upvotes: 2

Views: 124

Answers (2)

Steve Chamaillard
Steve Chamaillard

Reputation: 2339

Arthur's answer was :

Route::get('home/{slug}','HomeController@slugedIndex');
Route::controller('home', 'HomeController');

Although it doesn't work, because anything written after 'home/' will now go into the first route (and HomeController@slugedIndex).

I found a workaround though. I took out the route in routes.php :

Route::controller('home', 'HomeController');

Then in my HomeController, I used the missingmethod() that's called whenever a method isn't found in the controller.

Here's the missing method :

public function missingMethod($parameters = array())
{
    $sSlug = is_string($parameters) ? $parameters : '';
    $oObject = Object::where('slug', $sSlug)->first();

    if ($oObject) {
        // slug code
    }
    else {
            // 404 code
    }
}

Upvotes: 4

Arthur Samarcos
Arthur Samarcos

Reputation: 3299

Not possible using implicit controllers, as far as the documentation goes (as it seems to enforce RESTFUL pattern).

But your can create a new route just for that:

   Route::get('home/{slug}','HomeController@slugedIndex');
   Route::controller('home', 'HomeController');

Edit: as pointed by Steve the controller method must come after the get method so one does not overwrite the other.

Upvotes: 4

Related Questions