Search code examples
phplaravelurlparameterscontroller

Pass extra parameter to PHP Laravel Controller, based on URL


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.


Solution

  • You could use the defaults method of the Route object to set default parameters that will be passed to the action:

    Route::get('results_2023', 'Results')->defaults('year', 2023);