Question

I want to build fancy url in my site with these url patterns:

  • http://domain.com/specialization/eye
  • http://domain.com/clinic-dr-house
  • http://domain.com/faq

The first url has a simple route pattern:

Route::get('/specialization/{slug}', 'FrontController@specialization');

The second and the third url refers to two different controller actions:

  • SiteController@clinic
  • SiteController@page

I try with this filter:

Route::filter('/{slug}',function()
{
    if(Clinic::where('slug',$slug)->count() == 1)
        Route::get('/{slug}','FrontController@clinic');

    if(Page::where('slug',$slug)->count() == 1)
        Route::get('/{slug}','FrontController@page');
});

And I have an Exception... there is a less painful method?

Was it helpful?

Solution

To declare a filter you should use a filter a static name, for example:

Route::filter('filtername',function()
{
    // ...
});

Then you may use this filter in your routes like this way:

Route::get('/specialization/{slug}', array('before' => 'filtername', 'uses' => 'FrontController@specialization'));

So, whenever you use http://domain.com/specialization/eye the filter attached to this route will be executed before the route is dispatched. Read more on documentation.

Update: For second and third routes you may check the route parameter in thew filter and do different things depending on the parameter. Also, you may use one method for both urls, technically both urls are identical to one route so use one route and depending on the param, do different things, for example you have following urls:

http://domain.com/clinic-dr-house
http://domain.com/faq

Use a single route for both url, for example, use:

Route::get('/{param}', 'FrontController@common');

Create common method in your FrontController like this:

public function common($param)
{
    // Check the param, if param is clinic-dr-house
    // the do something or do something else for faq
    // or you may use redirect as well
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top