php - Laravel 5.4+ : Mutator/Accessor for uploaded image -
i'm trying use mutator store , retrieve users gravatar.
in user model have :
public function getgravatarattribute($gravatar){ if($gravatar){ $image = storage::disk('local')->get('public/avatars/'.$gravatar.'.jpg'); return new response($image, 200); } $hash = md5(strtolower(trim($this->attributes['email']))); return "http://www.gravatar.com/avatar/$hash?s=256"; } public function setgravatarattribute($gravatar){ if(is_object($gravatar) && $gravatar->isvalid()){ $image = image::make($gravatar)->fit(256, 256); storage::disk('local')->put('public/avatars/'.$this->id . '.' . $gravatar->getclientoriginalextension(), $image->response()); $this->attributes['gravatar'] = $this->id; } }
in blade file :
<img id="avatar" src="{{ $user->gravatar }}" alt="your image" width="256" height="256"/>
the mutator works nicely : image stored in storage/app/public/avatars
directory. problem accessor : if use dd($image);
before return can see datas it's not displayed in html page
you trying echo response facade string, need return image path file.
you can use url function on storage facade image path:
if($gravatar){ $image = storage::disk('local')->url('public/avatars/'.$gravatar.'.jpg'); return $image; }
because using value src:
src="{{ $user->gravatar }}"
https://laravel.com/docs/5.4/filesystem#file-urls
edit
from docs:
remember, if using local driver, files should publicly accessible should placed in storage/app/public directory. furthermore, should create symbolic link @ public/storage points storage/app/public directory.
once done returned url should display image.
Comments
Post a Comment