Php 基于上下文的Laravel身份验证过滤器

Php 基于上下文的Laravel身份验证过滤器,php,laravel,Php,Laravel,使用laravel,我们可以在routes文件中控制一些Auth设置,也可以在controller构造函数中控制一些Auth设置,但是我需要找到更好的方法来实现这一点,并且不确定路由是否可以处理它 对于我的用户,我允许他们自己和管理员编辑它们。我的控制器看起来像这样 function edit($id) { $user = User::findOrFail($id); if(!Auth::user()->isAdmin() && $user->id !

使用laravel,我们可以在routes文件中控制一些Auth设置,也可以在controller构造函数中控制一些Auth设置,但是我需要找到更好的方法来实现这一点,并且不确定路由是否可以处理它

对于我的用户,我允许他们自己和管理员编辑它们。我的控制器看起来像这样

function edit($id)
{
    $user = User::findOrFail($id);
    if(!Auth::user()->isAdmin() && $user->id != Auth::user()->id)
    {
        return Redirect::route('users.index')->withError('Unable to access that user');
    }
    return View::make('users.edit', compact('user'));
}
这是可以的,但是在我的更新代码中,我还必须执行相同的身份验证/用户检查,以确保用户或管理员只能对自己进行更改

所以我们得到了一个双向上,在一些控制器中,这是重复3次。另一个上下文示例是论坛帖子,发布者或管理员可以编辑它


路由筛选器是否有办法处理此问题?

这可能对您有用,也可能不有用,我的应用程序中也存在类似问题,用户只能访问自己的用户配置文件,但管理层可以访问任何人的

我的路线如下:

Route::get('user_profile/{user_id?}', array('as' => 'user_profile', 'uses' => 'UserController@get_user_profile'))->where(array('user_id' => '[0-9]+', 'tab' => '[A-Za-z]+'))->before('auth');
Route::when('user_profile/*', 'management');
这将应用一个管理过滤器,如果用户试图转到特定的用户,如果没有提供ID,则默认为他们自己的配置文件

Route::filter('management', function()
{
    if(Helper::managementStatus() === NOT_MANAGEMENT)
        return Redirect::route('home')
            ->with('flash_error', 'You must be logged in as a manager to view this page!');

});
或者,您可以创建类似以下内容的过滤器:

Route::filter('management', function()
{
    $user = User::findOrFail(Input::get('user_id'));
    if(!Auth::user()->isAdmin() && $user->id != Auth::user()->id)
    {
        return Redirect::route('users.index')->withError('Unable to access that user');
    }
}
然后将该过滤器应用于相关路由

我希望这会有帮助