Can I use Laravel 5 Middleware to allow packages to override app routes?

跟風遠走 提交于 2019-12-01 19:56:44

问题


I would like to be able to override the routes defined in app/Http/routes.php with a route in a package.

For example, in app/Http/routes.php I might have this:

Route::get('/search/{type?}',['as' => 'search','uses' => 'SearchController@search']);

I want to be able to define this in /vendor/author/package/src/Http/routes.php:

Route::get('/search/properties', ['as' => 'properties','uses' => 'PropertyController@search']);

The app/Http/routes.php file is loaded first so the route in their is used, not the package.

In Laravel 4 I would do this using App::before or App::after, giving them a priority.

Like so in the package routes:

App::before(function() {
    Route::get('/search/properties', ['as' => 'properties','uses' => 'PropertyController@search']);
});

I don't know how to achieve this in Laravel 5. I found this https://mattstauffer.co/blog/laravel-5.0-middleware-filter-style, but don't know how to use that to do what I want.

Edit: The Laravel 4 way of doing this would allow this priority to be set per route, so I'm not just loading all of the package routes before the app.


回答1:


You should be able to change the order in which routes are registered by changing the order of service providers in config/app.php.

Currently it probably looks somewhat like this:

'providers' => [
    // ...
    'App\Providers\RouteServiceProvider',
    // ...
    'Vendor\Package\PackageServiceProvider',
],

Now just change the order so the package is loaded first:

'providers' => [
    // ...
    'Vendor\Package\PackageServiceProvider',  // register package routes first
    'App\Providers\RouteServiceProvider',
    // ...
],

To just prioritize specific routes you can (ab)use the service providers register() method. I don't really like method but it works and I couldn't find anything better...

When the service providers are loaded the register() method of every provider is called. After that (and in the same order) the boot() method. That means independent of the order of your providers the register() method in your package will always be called before the boot() method in the RouteServiceProvider. This could look somewhat like this:

class PackageServiceProvider extends ServiceProvider {
    public function boot(){
        // register the regular package routes
    }

    public function register(){
        // register route "overrides"
        // for example like this: (obviously you could also load a file)
        app('router')->get('/search/properties', ['as' => 'properties','uses' => 'PropertyController@search']);
    }
}


来源:https://stackoverflow.com/questions/28832146/can-i-use-laravel-5-middleware-to-allow-packages-to-override-app-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!