Laravel 图片默认

Laravel Image Default

我的用户上传了一张存储在 storage/profile_picture/user1.png 中的个人资料图片。我使用文件系统和存储 类 来这样做。

要检索图像,我使用 {!! 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);

}

}

如果找不到或未上传个人资料图片,我想获取默认图片。我该怎么做?

谢谢,

K

你可以在你的视图中做:

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

或在您的控制器中:

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

对于这样的事情,我将覆盖您的 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) }}">

它会显示他们的照片或默认照片(如果他们没有)。您不再需要缩略图路线。