Laravel 图片默认
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33179753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Image Default
提问by karmendra
My user uploads a profile picture which is stored in storage/profile_picture/user1.png. I use Filesystem and Storage classes to do so.
我的用户上传了存储在 storage/profile_picture/user1.png 中的个人资料图片。我使用文件系统和存储类来做到这一点。
To retrieve the image I use {!! Html::image(route('profile.thumbnail', $user->profilepic_filename), "Your Picture Here", ['class'=>'img-responsive']) !!}
检索我使用的图像 {!! Html::image(route('profile.thumbnail', $user->profilepic_filename), "Your Picture Here", ['class'=>'img-responsive']) !!}
In my Controller I have
在我的控制器中,我有
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);
}
}
}
I want to get a default image if the profile picture is not found or not uploaded. How can I do so?
如果未找到或未上传个人资料图片,我想获取默认图片。我该怎么做?
Thanks,
谢谢,
K
钾
采纳答案by andrewtweber
For something like this I would just override the accessor (aka getter) on your User
model.
对于这样的事情,我只会覆盖User
模型上的访问器(又名 getter)。
http://laravel.com/docs/master/eloquent-mutators#accessors-and-mutators
http://laravel.com/docs/master/eloquent-mutators#accessors-and-mutators
Any database column, such as profilepicture_filename
can be manipulated after it's retrieved using a get___Attribute
method, where ___ is the column name in Camel Case
任何数据库列,例如profilepicture_filename
可以在使用get___Attribute
方法检索后对其进行操作,其中 ___ 是 Camel Case 中的列名
class User
{
/**
* @return string
*/
public function getProfilepictureFilenameAttribute()
{
if (! $this->attributes['profilepicture_filename'])) {
return '/images/default_profilepicture.png';
}
return $this->attributes['profilepicture_filename'];
}
}
Now you simply have to do
现在你只需要做
<img src="{{ asset($user->profilepicture_filename) }}">
And it will display either their picture or the default if they don't have one. You no longer need the thumbnail route.
如果他们没有,它将显示他们的图片或默认值。您不再需要缩略图路线。
回答by futureweb
you could just do in you view:
您可以在您的视图中执行以下操作:
@if(!file_exist($file->name))
<img src="/path/to/default.png">
@else
<img src="{{$file->name}}">
@endif
or in your controller:
或在您的控制器中:
if(!$file)
{
$file = '.../default/blah.png';
}