2015-10-16 98 views
1

我的用戶上傳存儲在storage/profile_picture/user1.png中的個人資料圖片。我使用Filesystem和Storage類來做到這一點。Laravel圖片默認

要檢索圖像我用{!! Html::image(route('profile.thumbnail', $user->profilepic_filename), "Your Picture Here", ['class'=>'img-responsive']) !!}

在我的控制器我有

public function thumbnail($filename) 
{ 
    $user = User::where('profilepicture_filename', '=', $filename)->firstOrFail(); 
    $file = Storage::disk('local_profile')->get($user->profilepicture_filename); 


    //$file = URL::asset('/images/default_profilepicture.png'); //doesn't work 

    return (new Response($file, 200))->header('Content-Type', $mime); 

} 

}

我想獲得一個默認的形象,如果沒有找到資料圖片或沒有上傳。我該怎麼做?

感謝,

ķ

回答

0

這樣的事情我只想覆蓋您的User型號上的訪問器(又名getter)。

http://laravel.com/docs/master/eloquent-mutators#accessors-and-mutators

任何數據庫列,如profilepicture_filename可它的使用get___Attribute方法,其中___是駝峯列名檢索後進行操作

class User 
{ 
    /** 
    * @return string 
    */ 
    public function getProfilepictureFilenameAttribute() 
    { 
     if (! $this->attributes['profilepicture_filename'])) { 
      return '/images/default_profilepicture.png'; 
     } 

     return $this->attributes['profilepicture_filename']; 
    } 
} 

現在你只需要做

<img src="{{ asset($user->profilepicture_filename) }}"> 

它會顯示他們的圖片或默認,如果他們沒有。您不再需要縮略圖路線。

1

你可能只是做在您查看:

@if(!file_exist($file->name)) <img src="/path/to/default.png"> @else <img src="{{$file->name}}"> @endif 

或在你的控制器:

if(!$file) 
    { 
     $file = '.../default/blah.png'; 
    }