Image does not displayed - How to display an image perhaps dynamically - laravel

I would like to display an employee picture using the url as shown below which I think should work but not. However it does work with the second url which is static. why is this happening?
This the first url that does not work
<img id="message" src="{{url('/profile_picture/' . $employee->picture)}}" style="width: 150px;"/>
This is the second url that does work
<img id="message" src="{{url('/profile_picture/20220615232745.jpg')}}" style="width: 150px;"/>
To save a picture I use the following method
public function ProfileStore(Request $request)
{
$data = User::find(Auth::user()->id);
$data->name =$request->name;
$data->email =$request->email;
if ($request->file('picture')) {
$file = $request->file('picture');
$filename = date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move('profile_picture/', $filename);
$data['picture'] = " $filename";
}
$data->save();
return redirect()->route('profile.index');
}
The route
Route::post('/people/employees/profiles/store', [ProfileController::class, 'ProfileStore'])->name('profile.store');
Route::get('/people/employees/profiles/edit/{id}', [ProfileController::class, 'ProfileEdit'])->name('profile.edit');
My edit method
public function ProfileEdit()
{
$id = Auth::user()->id;
$employee = User::find($id);
return view('fms.people.employee.profiles.profile_edit')->with('employee',$employee);
}

in you profilestore function, when setting the $filename to $data['picture'], you have extra space before it.Remove that space and try again. For ex:
if ($request->file('picture')) {
$file = $request->file('picture');
$filename = date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move('profile_picture/', $filename);
$data['picture'] = "$filename";
}

Related

Laravel download image

I have a function to add an image, and upon successful addition in the database, we have a path like public/images/asd.png. The question is how to make sure that when added to the name of the picture, an ID is added, and we have something like public/images/asd1.png, public/images/asd2.png, etc.
function in Model
public function getOriginImageUrl()
{
return $this->attributes['image'];
}
public function getImageAttribute($value)
{
return Storage::exists($value) ? Storage::url($value) : null;
}
function in Controller
if ($request->hasFile('image')) {
$file = $request->file('image');
$blog->image = $file->storeAs('public/images', $file->getClientOriginalName());
}
Instead of id you can combine time() with image name.
if ($request->hasFile('image')) {
$file = $request->file('image');
$namewithextension = $file->getClientOriginalName(); //Name with extension 'filename.jpg'
$name = explode('.', $namewithextension)[0]; // Filename 'filename'
$extension = $file->getClientOriginalExtension(); //Extension 'jpg'
$uploadname = $name. '-' .time() . '.' . $extension;
$blog->image = $file->storeAs('public/images', $uploadname);
}

Laravel upload multiple files

I'm building a gallery with multiple files functionality.
So far I'm having two issues, but let's paste my code first.
Controller:
public function store(Request $request)
{
$gallery = new GalleryImage();
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery->image = $image->move(public_path().'/uploads/temp/', $name);
//$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
}
}
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
return back()->with('success_message','Images has been uploaded!');
}
View blade:
<form action="{{ route('gallery-images.store') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<input type="hidden" name="gallery_id" value="{{ $gallery->id }}">
<input type="file" name="image[]" id="id_imageGallery" class="form-control" multiple="multiple" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
My first issue when I have my code like this and upload three files, it's successfully storing the files into /uploads/temp directory, but in my database I can see there's only one image uploaded, instead of three.
My second issue is when I change my code and use the commented part (because I want to store those three images into Storage):
$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
I'm getting this error:
Call to a member function storeAs() on array
How can I upload those multiple images into the Storage folder and record them all into the database?
-- EDIT --
I've solved my first issue!
I've simply put the save method and other details inside the loop. I've should have thought about this before :)
Here's my updated code:
public function store(Request $request)
{
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$gallery = new GalleryImage();
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery->image = $image->move(public_path().'/uploads/temp/', $name);
//$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','Images has been uploaded!');
}
Now only thing to do is how to store them into File Storage, instead of the public_path and avoid that error:
Call to a member function storeAs() on array
I've finally solved the issues and I'm posting it, so it may be useful for some.
Here's my code:
public function store(Request $request)
{
if($request->hasFile('image')) {
foreach($request->image as $image) {
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery = new GalleryImage();
$gallery->image = $image->storeAs('public/gallery-images', $name);
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','The images have been uploaded!');
}
Try to implement using the following code, it will give uploaded files url in serialized format
public static function upload_file($file){
$file_name = time();
$file_name .= rand();
$file_name = sha1($file_name);
if ($file) {
$ext = $file->getClientOriginalExtension();
$file->move(public_path() . "/uploads", $file_name . "." . $ext);
$local_url = $file_name . "." . $ext;
$s3_url = url('/').'/uploads/'.$local_url;
return $s3_url;
}
return "";
}
public static function upload_multiple_files($files){
if(is_array($files)){
$return_array = array();
foreach ($files as $file){
if(!empty($file)){
$return_array[] = self::upload_file($file);
}else{
$return_array[] = '';
}
}
return serialize($return_array);
}else{
return NULL;
}
}
//I have updated and commented your code. Try it, It should work.
public function store(Request $request)
{
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$gallery = new GalleryImage();
// laravel auto manages unique name and extension of file.
$gallery->image = $image->store('gallery-images', 'public');
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','Images has been uploaded!');
}

Laravel upload gifs

i am uploading gif for my posts in laravel but gif is like an image its not moving or something like this
<?php
if($request->hasFile('gif')){
$gif = $request->file('gif');
$gif_filename = time() . '.' . $gif->getClientOriginalName();
$gif_location = public_path('/images/' . $gif_filename);
Image::make($gif)->save($gif_location);
}
$post->gif = $gif_filename;
$post->save();
?>
here is the code what I am using I think everything is kinda correct
I use this method
if(Input::hasFile('imagen')) {
$time = Carbon::now()->format('Y-m-d');
$image = $request->file('imagen');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = $time."-".$name;
$image->move(storage_path(),$fileName);
}
Please try this and let me know how it works :)
An easy way to update and save is to do it like this:
public function store(Request $request)
{
$imgLocation = Storage::disk('public')->put(time() . '.' . $request->file('image')->getClientOriginalName(), $request->gif), $request->file('gif'));
// This would save it to the gifs table if you need something like it, otherwise skip this creation
$gif= Gif::create([
'name' => $request->name,
'path' => $imgLocation
]);
if ($gif) {
return response()->json("Success!");
}
return response()->json("Error!"); // or you return redirect()...
}
$image = $request->file('image');
if(isset($image)) {
if($image->getClientOriginalExtension()=='gif'){
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = 'exerciseimages'."-".$name;
$image->move('storage/courseimages/',$fileName);
}
else{
$fileName = 'exerciseimages'.'-'.uniqid().'.'.$image->getClientOriginalExtension();
if(!Storage::disk('public')->exists('courseimages')){
Storage::disk('public')->makeDirectory('courseimages');
}
$amenitiesimg = Image::make($image)->resize(250,250)->stream();
Storage::disk('public')->put('courseimages/'.$fileName, $amenitiesimg);
}
}
else {
$fileName = 'default.png';
}

Laravel deploy: storage image doesn't work correctly

After deploying my laravel project from local to Apache web server, all works correctly except images link. Here the code:
Images are stored in:
storage/app/public/photos
after i've run command:
php artisan storage:link
Images are linked at:
public/storage/photos
Controller:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photo = $file->storeAs('public/photos', 'foto-' . time() . '.' . $extension);
$user->photo = $photo;
$user->save();
}
Images are uploaded correctly on storage/app/public/photos and correctly linked in public/storage/photos but it doesn't display on frontend.
in blade, i've tried to use Storage::url to retrieve the path
{{Storage::url($user->photo)}}
and asset()
{{asset($user->photo)}}
in both cases, image doesn't exist
The public path of image is:
http://mywebsite.com/storage/photos/foto-1522914164.png
You should Use url function to show your image like below way.
url($user->photo);
I'd suggest to change the controller code as follows:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'foto-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$user->photo = 'photos/' . $photoFileName;
$user->save();
}
Then you can use {{asset($user->photo)}} in your blade.
on my webspace, it seems that the only way to display image correctly is to create a custom route that read and serve the image.
i'm solved like this:
i'm storing only image name in db:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'photo-' . $model->id . '.-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$store = $photoFileName;
}
then, i've create custom route that read images and display them:
Route::get('storage/{filename}.{ext}', function ($filename, $ext) {
$folders = glob(storage_path('app/public/*'), GLOB_ONLYDIR);
$path = '';
foreach ($folders as $folder) {
$path = $folder . '/' . $filename . '.' . $ext;
if (File::exists($path)) {
break;
}
}
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header('Content-Type', $type);
return $response;
});
in blade, i'm using Storage to display image:
{{ Storage::url($photo->photo) }}}

I want to delete the stored image while update new image

I want to delete the stored image while update new image
public function update($id)
{
$users = AdminLogin::find($id);
if(Input::hasFile('image_file'))
{
$file = Input::file('image_file');
$name = time() . '-' . $file->getClientOriginalName();
$file = $file->move(('uploads/images'), $name);
$users->image_file= $name;
}
$users->save();
return response()->json($users);
}
You can write this. This will solve your problem
public function update($id)
{
$users = AdminLogin::find($id);
if(Input::hasFile('image_file'))
{
$usersImage = public_path("uploads/images/{$users->image_file}"); // get previous image from folder
if (File::exists($usersImage)) { // unlink or remove previous image from folder
unlink($usersImage);
}
$file = Input::file('image_file');
$name = time() . '-' . $file->getClientOriginalName();
$file = $file->move(('uploads/images'), $name);
$users->image_file= $name;
}
$users->save();
return response()->json($users);
}
This will delete the previous image and update the new image
Well, the answer is technically incorrect. What if the save operation fails, since you have deleted that image the current record will not have an image anymore.
So to overcome this problem you can adjust your code like:
if(Input::hasFile('image_file'))
{
$file = Input::file('image_file');
$name = time() . '-' . $file->getClientOriginalName();
$file = $file->move(('uploads/images'), $name);
$users->image_file= $name;
}
$users->save();
if(Input::hasFile('image_file'))
{
$usersImage = public_path("uploads/images/{$users->image_file}"); // get previous image from folder
if (File::exists($usersImage)) { // unlink or remove previous image from folder
unlink($usersImage);
}
}

Resources