Laravel从模型中图片的相对路径获取绝对路径


  在模型product.php中增加以下方法.数据库图片字段为image.存储的图片相对路径 

 public function getImageUrlAttribute()
    {
        // 如果 image 字段本身就已经是完整的 url 就直接返回
        if (Str::startsWith($this->attributes['image'], ['http://', 'https://'])) {
            return $this->attributes['image'];
        }
        return \Storage::disk('public')->url($this->attributes['image']);
    }

Laravel 的模型访问器会自动把下划线改为驼峰,所以 image_url 对应的就是 getImageUrlAttribute
因此在模板中图片路径就得写$product->image_url

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM