dongliu6848 2015-03-10 20:00
浏览 23
已采纳

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

I have a Laravel 4 application with a resource Poll

// routes.php
Route::resource('polls', 'PollController');

I do not want anyone to be able to list all the polls, except if the user is authenticated and if (s)he is an admin. This was my solution:

// PollController.php
public function index() {

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

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

This code works just fine, but it is not very clean code. For once, I make this the "admin check" in a few places. Also it does not feel like it follows the practice of "A function should be doing just 1 thing".

I was wondering if there is a cleaner way to handle cases where the response changes depending on whether the user is logged in and is an admin?

  • 写回答

1条回答 默认 最新

  • doubi1910 2015-03-10 20:05
    关注

    Use Route Groups and Auth Filters.

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

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

    Example

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

    Here is a great tutorial series on Laravel in general (and your topic); http://culttt.com/2013/09/16/use-laravel-4-filters/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真