Reputation: 2243
My user uploads a profile picture which is stored in storage/profile_picture/user1.png. I use Filesystem and Storage classes to do so.
To retrieve the image I use {!! 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
Upvotes: 1
Views: 13065
Reputation: 442
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';
}
Upvotes: 2
Reputation: 25589
For something like this I would just override the accessor (aka getter) on your User
model.
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
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.
Upvotes: 2