【问题标题】:how can I show the user's image like a function on user model?如何像用户模型上的功能一样显示用户的图像?
【发布时间】:2020-04-22 14:18:12
【问题描述】:

当我尝试制作一个显示用户头像的功能时,我无法解决此错误。

我需要帮助!谢谢

代码:

class User extends Authenticatable
{
    ....

    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }

    public function getAvatar()
    {
        if($this->image->url)
        {
            $image = $this->image->url;
        }else{
            $image = "https://www.gravatar.com/avatar/" . md5( strtolower( trim( $this->email ) ) ) . "?d=mp";
        }

        return $image;
    }
}

【问题讨论】:

  • 表示$this->imagenull
  • 你推荐什么条件?
  • 检查我的答案

标签: php laravel eloquent model


【解决方案1】:

您可以将代码修复为:

class User extends Authenticatable
{
    ....

    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }

    public function getAvatar()
    {
        if($this->image)
        {
            $image = $this->image->url;
        }else{
            $image = "https://www.gravatar.com/avatar/" . md5( strtolower( trim( $this->email ) ) ) . "?d=mp";
        }

        return $image;
    }
}

【讨论】:

    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多