karmendra karmendra - 1 month ago 11
PHP Question

Laravel Image Default

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

Answer

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.