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