如何在Laravel 4中实现用户权限? [英] How to implement user permissions in Laravel 4?
问题描述
我基本上想要的是用户权限.
What I basically want is user permissions.
我的数据库中有一个名为"accounts"的表.有一个名为"group_id"的列. 我想在'group_id'= 3时设置它,那么用户是admin.然后,他可以查看特殊站点,按钮以及类似内容.我试图实现类似的东西:
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:
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.
推荐答案
旧帖子,但是也许有人会觉得有用
Old post, but maybe someone will find this useful
向您的用户模型添加一个方法,如果用户是管理员,则该方法返回true.在我们这里的例子中,只是我们的group_id等于3吗?"
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.');
}
});
最后使用过滤器保护一组路由.在这种简化的情况下,只有管理员用户可以访问/admin
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!");
}
});
基于此信息: http://laravelsnippets.com/snippets/admin-route-filter
这篇关于如何在Laravel 4中实现用户权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!