Laravel 4 - 改进代码以检查身份验证

Laravel 4 - Improve code to check for Authentication

我有一个 Laravel 4 带有资源 Poll

的应用程序
// routes.php
Route::resource('polls', 'PollController');

我不希望任何人能够列出所有民意调查,除非用户已通过身份验证并且他(她)是管理员。这是我的解决方案:

// PollController.php
public function index() {

    if (Auth::check() && Auth::user()->admin) {
        return View::make('polls.index', Poll::all());
    }

    return View::make('polls.create', []);
}

此代码工作正常,但不是很好clean code。这一次,我在几个地方将其设为 "admin check"。而且感觉不像是遵循"A function should be doing just 1 thing".

的做法

我想知道是否有更简洁的方法来处理响应根据用户是否登录和管理员而变化的情况?

使用路由组和身份验证过滤器。

http://laravel.com/docs/4.2/routing#route-groups

http://laravel.com/docs/4.2/security#protecting-routes

示例

Route::group(array('before' => 'auth'), function()
{
  // Route::resource('poll', 'PollController');
  // Additional routes
}

这是关于 Laravel 总体(以及您的主题)的精彩教程系列; http://culttt.com/2013/09/16/use-laravel-4-filters/