Customising The fallbackPlaceholder In Laravel's Fallback Route

There is a neat feature in Laravel called a Fallback Route. This is the route which will handle the request if none of the others can:

Route::fallback(Controller::class);

The fallback method is simply a convenience function which expands to the following:

Route::get('{fallbackPlaceholder}', Controller::class)
    ->where('fallbackPlaceholder', '.*')
    ->fallback();

Knowing this, we can easily rename the fallbackPlaceholder parameter by defining our own route and chaining the fallback() method:

Route::get('{myPlaceholderName}', Controller::class)
    ->where('myPlaceholderName', '.*')
    ->fallback();

But Why..?

Good question! In my particular case I'm using the FallbackRoute to handle all requests and wanted to use implicit binding to fetch the model:

Rather than:

Route::fallback(Controller::class);
Route::bind('{fallbackPlaceholder}', fn (string $slug): Page => Page::whereSlug($slug)->sole());

We can just do:

Route::get('{page}', Controller::class)
    ->fallback();

Bonus points if you spotted the edge case this introduces for the homepage. We can add a dedicated route for this. This has the side benefit of giving the route to the homepage a name.

Popular Reads

Subscribe

Keep up to date

Please provide your email address
Please provide your name
Please provide your name
No thanks