0

I have this route declared on laravel:

Route::get('pages/{page}/{slug}', 'Common\Pages\CustomPageController@show')
    ->middleware(['web', 'prerenderIfCrawler']);

This route works fine and works if you make requests to:

https://example.com/pages/1/test-page
https://example.com/pages/2/other-page
https://example.com/pages/3/url-test

The problem is that I need a more friendly url as well as.

 https://example.com/test-page
 https://example.com/other-page
 https://example.com/url-test

I want remove the suffix called pages, The numbers for the pages will never change and will be static for each one.

I've tried to make static routes for each one but can't get it to work.

Route::get('other-page', array('as' => 'other-page', function() {
    return App::make('Common\Pages\CustomPageController')->show(2);
}))->middleware(['web', 'prerenderIfCrawler']);

I would appreciate a little help.

Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
Jonathan Nuñez
  • 432
  • 6
  • 19

2 Answers2

1

You could always get the URL segment in the Controller and use that to know what page you are on. If you don't want to do that you could pass extra information in the 'action' to specify the page:

Route::middleware(['web', 'prerenderIfCrawler'])->group(function () {
    Route::get('test-page', [
        'uses' => 'Common\Pages\CustomPageController@show',
        'page' => 'test-page',
    ]);
    ...
});

Then you can get this extra information in the Controller:

public function show(Request $request)
{
    $page = $request->route()->getAction('page');

    ...
}

If you knew all the pages you can use a route parameter with a regex constraint to restrict it to only those page names:

Route::get('{page:slug}', ...)->where('page', 'test-page|other-page|...');

public function show(Page $page)
{
     ...
}
lagbox
  • 48,571
  • 8
  • 72
  • 83
1

You could just make use of a wildcard to catch your routes like this:

Route::get('/{slug}', 'Common\Pages\CustomPageController@show')
    ->middleware(['web', 'prerenderIfCrawler']);

Then in your controller:

public function show($slug)
{
    $page = Page::where('slug', $slug)->first();
    // ...
}

Just be careful with where you place the route. It should be at the end of your routes otherwise it will catch all the request of your app.

// ...
// my other routes
// ...
Route::get('/{slug}', ...);

By the way, if you want to bind your page models using the slug attribute do this:

Route::get('/{page:slug}', 'Common\Pages\CustomPageController@show')->//...
              ^^^^^^^^^

Then in your controller:

public function show(Page $page)
{                    ^^^^^^^^^^
    // ...
}

Check this section of the docs.

Kenny Horna
  • 13,485
  • 4
  • 44
  • 71