【问题标题】:add new attribute to laravel eloquent collection向 laravel eloquent 集合添加新属性
【发布时间】:2018-02-25 10:05:47
【问题描述】:

我想在我的 eloquent 模型中添加一个额外的计算属性 我想在我的刀片中使用它作为$user->avatarImg 我的模型方法看起来像

 public function avatarImg()
 {

     if($this->hasMedia('avatar')) {
         $image = $this->getMedia('avatar');
         $img = \Intervention\Image\ImageManagerStatic::make($image[0]->getPath())->encode('data-url');
     }
     elseif ($this->blob->file) {
         $img = 'data:image/jpeg;base64,'. base64_encode($this->blob->file);
     } else {
         $img = '';
     }


     $this->user->put('avatarImg', $img);

     dd($this->user);

     return $img;

 }

但我尝试的方法不起作用:

Call to a member function put() on null 

我该如何正确地做到这一点?

【问题讨论】:

标签: laravel-5 model eloquent attributes


【解决方案1】:

您的模型中似乎不存在属性 user。 如果这是用户模型,请尝试

$this->put('avatarImg', $img);

【讨论】:

  • 感谢您的反馈。以前尝试过也不起作用Call to undefined method Illuminate\Database\Query\Builder::put()
  • 试试 $this->avatarImg = $img;
  • $collection = new Collection(array($this)); $collection->put('avatarImg', $img);
  • 这样做不会修改模型属性,我在 dd(Auth::user()) 之后这样做,但我没有看到新属性
猜你喜欢
  • 2017-04-29
  • 2018-05-02
  • 2019-09-21
  • 1970-01-01
  • 2020-08-21
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
相关资源
最近更新 更多