【问题标题】:Prioritizing Laravel 4 routes优先考虑 Laravel 4 条路线
【发布时间】:2014-05-23 01:51:28
【问题描述】:

我有这样的路线:

Route::group(array('before' => 'installed'), function() {

    Route::group(array('before' => 'auth_admin', 'prefix' => 'admin'), function()
    {

        Route::group(array('prefix' => 'gag'), function() {

            Route::get('/', 'Admin\\GagController@index');
            Route::get('delete/{id}','Admin\\GagController@delete');

        });

    });

});

我需要阻止用户删除我的demo 应用程序中的内容。所以我在我的实际路线之前添加了以下代码。

if(App::environment() === 'demo')
{
     Route::get('admin/gag/delete/{id}', function() {
          die("You can't delete anything on demo application.");
     });
}

//Actual routes are at the below.

但是,当Route::get('delete/{id}','Admin\\GagController@delete'); 存在时它不起作用。不知何故,Laravel 忽略了我的 if 块并优先考虑这条路线。 (虽然 if 块在顶部。)

看起来 routes.php 在解析路由后解析我的 if 块。

我怎样才能让 Laravel 优先考虑我的演示路线?我只是想限制对此类功能的访问。

附言。我不想在 if 块中添加所有路由。我只想优先考虑 if 块中的路由。

【问题讨论】:

    标签: php laravel laravel-4 routing


    【解决方案1】:

    路由过滤器更适合做这种限制:

    Route::filter('checkDemo', function()
    {
        if (App::environment() === 'demo')
        {
            return Redirect::to('home')->withMessage('You can''t delete anything on demo application.');
        }
    });
    

    并将过滤器设置为您的路线:

    Route::group(array('prefix' => 'gag', 'before' => 'checkDemo'), function() 
    {
      ...
    });
    

    或者你可以只过滤那个特定的路由:

    Route::get('delete/{id}', array('before' => 'checkDemo', 'uses' => 'Admin\\GagController@delete'));
    

    【讨论】:

    • 是的,但是我需要复制 gag 前缀下的所有路由。我只需要覆盖 delete/{id} 路由。
    • 您不需要复制它们,您可以仅在您尝试覆盖的那条路线中添加过滤器。刚刚编辑。
    • 没错,但我有点希望我能把它们写在一个单独的地方,这样管理起来会更容易一些。您的解决方案看起来也很酷。如果没有其他方法可以做到这一点,我会选择这个作为答案。
    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    相关资源
    最近更新 更多