October CMS - How To Correctly Route
I've been reviewing the documentation for October CMS routing (https://octobercms.com/docs/plugin/registration#routing-initialization), but I think that I am missing something. I have a page called 'deals' that renders some basic information along with a plugin (called 'deals') component. The page normally appears at the url:
http://www.example.com/deals
However, I want to create a route so that if someone visits the url:
http://www.example.com/deals2
it will automatically route them back to
http://www.example.com/deals
I know that I should create a routes.php file in my plugin directory. However, when I try using
Route::get('/deals2', function()
{
return View::make('deals');
});
It complains that it can't find the 'deals' view. What am I doing wrong?
Additionally, how can I route it so that my homepage
http://www.example.com
would route to
http://www.example.com/deals
Answer
In OctoberCMS, and Laravel which it's based on, to redirect one route to another you can do this:
// Redirect /deals2, /deals3, ... to /deals
Route::get('{dealSlug}', function($dealSlug) {
return redirect('deals');
})->where('dealSlug', '^deals[0-9]+');
// Redirect homepage to /deals
Route::get('/', function() {
return redirect('deals');
}
The first route uses a route parameter with a regex constraint and will redirect any request that starts with /deals
and ends with a number to your /deals
route. That means it will route /deals1
, /deals2
, /deals3
, etc to /deals
.
The second route will redirect your homepage to /deals
.
Of course, redirecting will cost an extra request. If you don't want to do that, then you could do the redirect in Apache or Nginx.
As per your comment, if you wanted to redirect /deals[any-number]/[anything]
to /deals/[that-same-anything]
then you would add an optional route parameter to the first route. That would look like this:
// The new first route
Route::get('{dealSlug}/{extra?}', function($dealSlug, $extra = '') {
return redirect('deals/' . $extra);
})->where('dealSlug', '^deals[0-9]+');
Of course, if that /deals/[anything]
route doesn't exist, then you'll get a 404.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?