【问题标题】:Laravel model not exist attribute detectionLaravel 模型不存在属性检测
【发布时间】:2019-10-05 09:10:24
【问题描述】:

我有带有字段的 User 模型:

id
name
email
password

为什么 Laravel 在请求不存在的属性期间不返回错误。请求不存在的属性时如何返回错误?

代码:

$user = User::findOrFail(1);

echo $user->name; // This attribute exist in out table and we can continue...
echo $user->location; // Attribute `location` doesn't defined and we can't continue!!!

【问题讨论】:

  • 它将返回null,您可以使用is_null检查并根据需要返回错误。
  • 如何在错误处理程序 (Exceptions\Handler.php) 上为所有模型执行此操作? @PrafullaKumarSahu
  • 这不是例外,所以我认为您不会将其作为例外处理,但是您在这种情况下面临的问题是什么,请告诉我,也许我可以给出其他看法给它。
  • 我只希望使用我的应用程序 API 的用户不要请求不存在的表字段。 @PrafullaKumarSahu
  • 您能否展示您的用户如何能够请求不同的表格字段?您应该为此实际使用验证。

标签: laravel exception eloquent laravel-5.8


【解决方案1】:

您可以覆盖您的模型getAttributeValue 方法,如下所示:

class User extends Authenticatable
{
    ...

    public function getAttributeValue($key)
    {
        $value = parent::getAttributeValue($key);
        if ($value) {
            return $value;
        }
        throw new \Exception("Attribute Does Not Exists!");
    }

   ...
}

【讨论】:

    【解决方案2】:

    您可以像下面的代码一样覆盖模型中的 __get 方法:

    public function __get($key)
    {
        if (!array_key_exists($key, $this->attributes))
            throw new \Exception("{$key attribute does not defined !!! }", 1);
    
        return $this->getAttribute($key);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 2014-06-17
      • 2017-07-27
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多