如何在 Laravel 4 中实现用户权限?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17914302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement user permissions in Laravel 4?
提问by dynamitem
What I basically want is user permissions.
我基本上想要的是用户权限。
I've got an table called 'accounts' in my database. There is a column called 'group_id'. I want to set it when the 'group_id' = 3, then the user is admin. Then he can view special sites, buttons, and things like that. I've tried to implement something like that:
我的数据库中有一个名为“帐户”的表。有一列名为“group_id”。我想在'group_id' = 3 时设置它,然后用户是管理员。然后他可以查看特殊的站点、按钮和类似的东西。我试图实现类似的东西:
public function ($roleName) {
$role = $this->roles;
if ($role->name == $roleName) {
return true;
}
return false;
}
Also, I don't know what and how the model is needed, do I need an new one and things like that.
另外,我不知道需要什么以及如何需要模型,我是否需要一个新模型之类的东西。
回答by Jason Macgowan
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?"
向您的 User 模型添加一个方法,如果用户是管理员,则该方法返回 true。在我们这里的例子中,它只是“我们的 group_id 是否等于 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
最后使用过滤器来保护一组路由。我这个简化的情况,只有管理员用户可以访问/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
基于这篇文章:http: //laravelsnippets.com/snippets/admin-route-filter