Laravel 4:保护控制器提供的路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17512407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:06:09  来源:igfitidea点击:

Laravel 4: protecting routes provided by a controller

phplaravellaravel-4

提问by Josh

I'm building a Laravel 4 app and I want to protect my admin area so it is only accessible if the user is logged in/authenticated.

我正在构建一个 Laravel 4 应用程序,我想保护我的管理区域,以便只有在用户登录/验证后才能访问它。

What is the best way to do this?

做这个的最好方式是什么?

The Laravel docs say you can protect a route like this:

Laravel 文档说你可以保护这样的路线:

Route::get('profile', array('before' => 'auth', function()
{
// Only authenticated users may enter...
}));

But what happens when my route looks like this:

但是当我的路线看起来像这样时会发生什么:

Route::resource('cms', 'PostsController');

How do I protect a route that is directing to a controller?

如何保护指向控制器的路由?

Thanks in advance!

提前致谢!

回答by Markus Hofmann

You could use Route Groupsfor this purpose.

为此,您可以使用路由组

So for example:

例如:

Route::group(array('before' => 'auth'), function()
{
    Route::get('profile', function()
    {
        // Has Auth Filter
    });

    Route::resource('cms', 'PostsController');

    // You can use Route::resource togehter with 
    // direct routes to the Resource Controller
    // so e.g. Route::post('cms', 'PostsController@save');
});

回答by Melvin

You can put the filter on the constructor of your Controller like this:

您可以像这样将过滤器放在控制器的构造函数上:

public function __construct()
    {
        $this->beforeFilter('auth');

        $this->beforeFilter('csrf', array('on' => 'post'));

        $this->afterFilter('log', array('only' =>
                            array('fooAction', 'barAction')));
    }

回答by DevZer0

In your PostsController you can put a closure in the constructor to do the same before logic as the previous route.

在您的 PostsController 中,您可以在构造函数中放置一个闭包,以执行与先前路由相同的逻辑。

    public function __construct()
    {
        $this->beforeFilter(function()
        {
            //
        });
    }