Skip to content
This repository was archived by the owner on Jul 16, 2021. It is now read-only.

Adding Route::other for setting route that matches all the requests that didn't match #780

Closed
yaronuliel opened this issue Sep 4, 2017 · 5 comments

Comments

@yaronuliel
Copy link

It would be useful in some cases to have the possibility to add a route that catches all the requests that didn't match any other route (right before NotFoundHttpException is being thrown)

A good use case is for CMS systems that dynamically create pages (page routes/URI are stored in database for example)

This is different from changing the behavior of 404 responses in several ways:

  • 404 response doesn't use controllers for crafting responses
  • changing 404 can only be handled on the App\Exceptions\Handler which is hardcoded in the bootstrap script - and can't be tweaked from packages without ugly workarounds

Currently, in order to achieve similar results - you can create a very broad route like
Route::get( '{any}', ...)- but it has its disadvantages:

  • Not explicit enough that it should catch whatever others didn't (as opposed to all requests)'
  • It must be defined last in order (to prevent overwriting of more specific routes) - which makes it hard to maintain if routes are registered through several packages, or files
@sisve
Copy link

sisve commented Sep 4, 2017

Looks related to #653

@yaronuliel
Copy link
Author

@sisve Indeed 👍

@drbyte
Copy link

drbyte commented Sep 4, 2017

Ya, I did this in one of my projects ... as you say, at the end of routes file, to avoid clashing. Would be nice to have a way to specify Route::other or fallback or whatever.

/**
 * Catchall route
 */
Route::get('{view}', function ($view) {
    try {
        return view($view);
    } catch (\Exception $e) {
        abort(404);
    }
})->where('view', '.*');

@unstoppablecarl
Copy link

unstoppablecarl commented Sep 7, 2017

I have written an experimental package to tackle this exact problem:

https://github.com/unstoppablecarl/laravel-content-pages
https://github.com/unstoppablecarl/laravel-content-pages-example

As I say in the readme, I am not sure if this is a good idea or not.

Really what we need is a generic way to set an alternative route matcher that is run before/after the normal router. Whether you should be able to register multiple before/after route matchers is debatable.

  $matcher = function(Request $request){

    $page = Page::where('path', $request->url())->first();

    // determine if matches
    if($page){
        return Route::match($request->method(), $request->url(), 'PageController@show');
    }
    // ignored if returns falsy
};

Route::before($matcher);
// or
Route::after($matcher);

@themsaid
Copy link
Member

Check laravel/framework#21234

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants