简体   繁体   English

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

[英]Laravel 4: protecting routes provided by a controller

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! 提前致谢!

You could use Route Groups for 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');
});

You can put the filter on the constructor of your Controller like this: 您可以将过滤器放在Controller的构造函数中,如下所示:

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

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

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

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()
        {
            //
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM