Laravel开发结构

时间:2016-12-10 03:32:05

标签: php laravel laravel-5.2

我正在开发一个应用程序,其中我有不同角色的视图。

例如,我有一个包含5个字段的表单。它可能有3个字段用于角色1,而角色5的所有字段在提交时都可用。

现在,在我以图形方式或使用表格显示表单数据的情况下,我可以选择为某些角色显示5个列或字段,为其他角色显示较少的字段。

现在我正在做if if逻辑在控制器的每个动作中确定角色然后将相应的数据传递给视图,你如何管理呢?我想知道。

请在阅读前仔细阅读'给我看一些代码:('

编辑: 还有一个问题,假设有一个用户类,并且在我可以做的视图中与类型类有1对1的关系:

{{ Auth::user()->type->key }}

或者像

这样复杂的
{{ Auth::user()->as_member->claims->sum('amount_claimed') }}

这是一个复杂的关系,作为会员的用户有很多主张,我在这里总结一下。在控制器中执行此操作然后将它们作为值传递会更好吗?

1 个答案:

答案 0 :(得分:0)

一般来说,用户和角色共享多对多关系。用户可以拥有许多角色,许多用户可以共享角色。

要实现它,需要三个数据库表 1.用户
2.角色
3. role_user(数据透视表)

然后可以在模型中将关系定义为

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany('App\Roles');
    } 

    //suppose you currently want to assign each user only one role
    //however also want to provision multiple roles for user in future
    //then you can define a virtual/calculated attribute to your model
    //to simplify usage considering each user has only one role

    public function getRoleAttribute()
    {
        return $this->roles[0]->name;  //name is a field on the roles table
    }  

    protected $appends = ['role'];  //to ensure that the calculated attribute is available to ajax/json/api requests as well

}


class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}  

假设您有三个用户作为样本数据

User1有角色'用户'

User2有角色'经理'

User3有角色'管理员'

现在,您可以使用示例视图(如

)测试功能
<h4>Current user is {{auth()->user()->name}} having a role of {{auth()->user()->role}}</h4>

<div class="example-form">
    <h4 class="all">Visible to all - User1, User2, User3</h4>  
    @if( (auth()->user()->role ==='Manager') || (auth()->user()->role ==='Admin'))
         <h4>Visible to Manager and Admin only - User2 and User3</h4>
    @endif
    @if(auth()->user()->role === 'Admin')
         <h4>Visible only to Administrator - User3</h4>
    @endif
</div>  

希望这是你的目标 - 我的理解还可以。

但是,既然您已经提到过使用Laravel 5.2,那么更好的方法是使用Laravel 5.2提供的开箱即用授权。

参考Authorization documentation

相关问题