How to implement user permissions in Laravel 4?

江枫思渺然 提交于 2019-12-06 02:34:31

Old post, but maybe someone will find this useful

Add a method to your User model that returns true if the user is an admin. In our case here, it's simply "is our group_id equal to 3?"

// models/User.php
class User extends Eloquent 
{
    ... 
    public function isAdmin()
    {
        return $this->group_id == 3;
    }

}

Next add a filter that can be used to protect routes

// filters.php
Route::filter('admin', function($route, $request)
{
    if ( ! Auth::user()->isAdmin())
    {
        return App::abort(401, 'You are not authorized.');
    }
});

Finally use the filter to protect a group of routes. I this simplified case, only an admin user could access /admin

// routes.php
Route::group(array('before' => array('auth|admin')), function()
{
    Route::get('/admin', function()
    {
        return Response::make("You're an admin!");
    }
});

Based on this post: http://laravelsnippets.com/snippets/admin-route-filter

I suggest Authority for Laravel 4

I personally use Verify package for user management.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!