【问题标题】:override relation in Laravel在 Laravel 中覆盖关系
【发布时间】:2014-10-05 11:53:42
【问题描述】:

我正在根据用户角色限制访问。

如果user->isAdmin() 返回true,我希望能够以某种方式覆盖belongsToMany 关系以返回全部。

目前有作为 AccountController 的索引方法:

public function index()
{
    if(Auth::user()->isAdmin())   // can this go in beforeFilter? 
        return Account::all();
    else
        return Auth::user()->accounts;
}

在我的用户模型中:

public function accounts()
{
    return $this->belongsToMany("Account");
}

有没有一种不需要在控制器函数中使用 if 语句的简洁方法?

【问题讨论】:

    标签: authentication laravel eloquent relation


    【解决方案1】:

    你不能这样做。

    关系方法必须返回Relationotherwise it throws an error的实例。


    没有什么能阻止你为此创建一个单独的方法:

    AccountController.php

    public function index()
    {
        return Auth::user()->userAccounts();
    }
    

    用户.php

    public function accounts()
    {
        return $this->belongsToMany("Account");
    }
    
    public function userAccounts()
    {
        if ($this->isAdmin()) return Account::all();
    
        return $this->accounts;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多