I have competition website, where I use web routes like this:
Route::get('results/{year?}', 'Results')->where('year', '[0-9]+');
This allows to sneak-peak into current year "unpublished" results, just by "hacking" URL.
I’d like to create custom routes for every year, so after I want publish results – I change routes file only. Is it possible in Laravel?
I red Laravel docs and tried to search for this problem, yet I was unable to find exact query for my problem, as there is lots of other similar questions with extra parameters.
I tried to experiment with possible route definitions, something like this, which do not work:
Route::get('results_2023', 'Results', ['year' => 2023])->where('year', '[0-9]+');
Route::get('results_2024', 'Results', ['year' => 2024])->where('year', '[0-9]+');
What I do not want – it’s redirect (URL transformation), so anyone using URL results_2025 would be redirect to results/2025, which I want to avoid.
3
Answers
You could use the
defaults
method of theRoute
object to set default parameters that will be passed to the action:I would advice not to always change the route nor the controller for that matter. But you can add a custom validation inside the controller’s method.
web.php
ResultController.php
Did not test code but it should be enough for you to edit and get the result you want.
As mention by other answer, you can use
defaults
method for passing parameter value from your route to your controller.but just additional thing,
assume you have in your controller
you should either remove the optional year
or have the year optional but provide a default value if you want the
/results
to have a default yearThen for additional routes without year parameter, just provide a default year value