Laravel show all images from folder - php

I upload from vue 4-5 images to different folders in laravel.
public function uploadImageso2orders(Request $request, $id)
{
$o2order = O2order::findOrFail($id);
$name = $o2order->contactname;
$name2 = str_replace(' ', '_', $name);
$image = $request->file('file');
$imageName = $name2.'.'.time().'.'.$image->extension();
$wwwPath = 'https://api2.api.sk/storage/';
$image->move(storage_path('app/o2/servisne' . '/' . $name2),$imageName);
$imagePath = 'https://api2.api.sk/storage/app/o2/' . ('servisne' . '/' . $name2);
$o2order->servisny = $imagePath;
$o2order->save();
}
This is working fine. In storage/app/o2/servisne_listy/ is folder created and multiple images stored. In sql is written full path to this folder.
I need to show this image or images, sometimes its one sometimes more, not same.
I have this:
public function showImageso2orders(Request $request, $id)
{
$o2order = O2order::findOrFail($id);
$servisny = $o2order->servisny;
return response()->json(['servisny' => $servisny], 200);
}
Its shows only the path from sql, but i need path to every file which is in this directory.
Thanks

May be this help you
$path = storage_path('app/o2/servisne');
$files = File::files($path)

Related

Laravel 8 image upload: Best practices for storing and editing image files

I need assistance to more understand the concept so I can become a better developer. I want to learn how to refactor the code and erase all duplications.
What's the best practices for image uploads? Renaming them correctly?
I have a block of code that handles two attachments:
if( $request->hasFile('LFImage') ) {
$destination = public_path('app/lostFound/lostItems' . $lostFound->LFImage);
if( File::exists($destination) )
{
File::delete($destination);
}
$file = $request->file('LFImage');
$extension = $file->getClientOriginalExtension();
$filename = $lostFound->LFNumber . '-' . $lostFound->lostItem . '.' . $extension;
$file->move('app/lostFound/lostItems', $filename);
$lostFound->LFImage = $filename;
}
if( $request->hasFile('handoverStatement') ) {
$destination = public_path('app/lostFound/handoverStatements' . $lostFound->handoverStatement);
if( File::exists($destination) )
{
File::delete($destination);
}
$file = $request->file('handoverStatement');
$extension = $file->getClientOriginalExtension();
$filename = $lostFound->lostItem . '-' . $lostFound->LFNumber . '.' . $extension;
$file->move('app/lostFound/handoverStatements', $filename);
$lostFound->handoverStatement = $filename;
}
They're exactly the same except with the upload directory.
How can I make it as a one code block across the entire application with changeable file name and location depending on the form?
Some file names require random strings, how can I "Edit" the random string to the file that was uploaded?
Best practice when uploading and storing files in Laravel is using Storage.
It has all needed methods to work with files, you can save the file like this:
use Illuminate\Support\Facades\Storage;
Storage::put('images/', $request->file('LFImage'));
In the documentation provided above, you can find other examples like renaming and moving files
In order to access these files from web as well, you can use the command php artisan storage:link, which creates a symbolic link to storage folder in your public folder. After you create the symbolic link, you can generate URL to the file like this:
asset('storage/test.txt')
To avoid duplications, you can create a function in your controller to create a file. You will then just call this function with different files to keep the file creation code in one place.
you can simply write this
if ($request->hasFile('logo')) {
deleteImageFromDirectory(setting('logo'), "Settings");
$data['logo'] = uploadImageToDirectory( $request->logo , "Settings");
}
and define uploadImageToDirectory function in your helper functions or create a trait
function uploadImageToDirectory($imageFile, $directory = '' ){
$imageName = $imageFile->getClientOriginalName(); // Set Image name
$imageFile->storeAs("/Images/$directory", $imageName, 'public');
return $imageName;
}

How to update image_path in laravel

i'm want to delete existing images and update with new images using in laravel using this method
if($request->hasFile('images')) {
$listingImages = $listing->images;
foreach($listingImages as $listingImage) {
$img_path = 'images/listing/'.$listing->id;
if(File::exists($img_path)) {
File::deleteDirectory($img_path);
$listingImage->delete();
}
foreach ($request->file('images') as $image) {
$listingImage = new ListingImage;
$imageName = time().'.'.$image->getClientOriginalExtension();
$listingImage->listing_id = $listing->id;
$listingImage->image_path = 'images/listing/'.$listing->id."/".$imageName;
$listingImage->save();
$image->move(public_path('images/listing/'.$listing->id),$imageName);
}
}
}
so far i can delete the previous directory and update new image path on the database.
but each time i run the edit listing, I get a Symfony\Component\HttpFoundation\File\Exception\FileException
The file "8 (2).jpg" was not uploaded due to an unknown error. and the old listingImages isn't been deleted on my database.
what proper way can i use to achieve updating multiple listing images?
try Storage::delete() function ref link https://laravel.com/docs/7.x/filesystem#deleting-files
and don't delete Directory i think in future u can need to image in that Directory
if ($request->hasFile('images')) {
$listingImages = $listing->images;
foreach ($listingImages as $listingImage) {
foreach ($request->file('images') as $image) {
$oldImage = $listingImage->image_path;
$listingImage = new ListingImage;
$imageName = time() . '.' . $image->getClientOriginalExtension();
$listingImage->listing_id = $listing->id;
$listingImage->image_path = 'images/listing/' . $listing->id . "/" . $imageName;
$listingImage->save();
$image->move(public_path('images/listing/' . $listing->id), $imageName);
\Storage::delete($oldImage); // it will not work if u r not setup `Storage`
//then u can use unlink
unlink(public_path().'/'.$oldImage); //
}
}
}

Intervention/Image save function always create corrupted files (0 byte)

I want to save images with the Image class from Intervention after they have been cropped. My Problem is, that images created this way dont show in the browser. I cant even open them in my filesystem => all the files have 0 bytes.
My Controller:
public function store(Request $request)
{
$this->validate($request, [
'image' => 'required',
'link' => 'nullable|url|max:255',
'description' => 'max:255'
]);
$image = $request->file('image');
$filename = 'carousel_' . time() . '.' . $image->getClientOriginalExtension();
$this->cropAndSaveCarouselimage($image, $request->image_crop_x, $request->image_crop_y, $request->image_crop_width, $request->image_crop_height);
$carousel = new CarouselImage();
$carousel->link = $request->link;
$carousel->description = $request->description;
$carousel->filename = $filename;
$carousel->save();
return redirect(route('carouselimages.index'))->with('success', 'Carouselimage added successfully...');
}
public function cropAndSaveCarouselimage($originalImage, $image_crop_x, $image_crop_y, $image_crop_width, $image_crop_height)
{
if (isset($originalImage)) {
$filename = 'carousel_' . time() . '.' . $originalImage->getClientOriginalExtension();
$carouselImagesPath = public_path('/storage/resources/images/carousel') . $filename;
$imageToCrop = Image::make(File::get($originalImage));
$imageToCrop
->crop($image_crop_width, $image_crop_height, $image_crop_x, $image_crop_y)
->save($carouselImagesPath, 100);
}
}
This should create a new cropped image in the given public path. But it only creates a 0 byte file.
When I dont try $imageToCrop->...->save();
but $imageToCrop->...->response();
and return this as response of the store function, the cropped image is shown in my browser.
tcj answered/resolved my question/problem!
The problem was the missing / at the end of the $carouselImagesPath.
So i changed it to: $carouselImagesPath = public_path('/storage/resources/images/carousel/') . $filename;
Now everything works as expected.

Saving files locally with Laravel

I'm saving files locally in Laravel, however I'm having issues getting the right URL and accessing the files.
I've setup a symlink with Artisan:
php artisan storage:link
When saving, I add public/ to the name, so the files are placed in the /storage/app/public/ directory, which works.
if ($request->hasFile('files')) {
$files = array();
foreach ($request->file('files') as $file) {
if ($file->isValid()) {
$name = time() . str_random(5) . '.' . $file->getClientOriginalExtension();
Storage::disk('public')->put($name, $file);
$files[] = $name;
}
}
if (count($files) > 0) {
$response->assets = json_encode($files);
}
}
The name is stored in the database
["1524042807kdvws.pdf"]
Then the assets are returned as part of a JSON object via my API for Vue
if (count($response->assets) > 0) {
$assets = array();
foreach (json_decode($response->assets, true) as $asset) {
$assets[] = asset($asset);
}
$responses[$key]->assets = $assets;
}
Which returns http://127.0.0.1:8000/1524042807kdvws.pdf but that 404s. I've gotten myself a little confused I think, so any pointers or help would be appreciated.
So I found my answer on another post
I needed to wrap the $file in file_get_contents();
Storage::disk('public')->put($name, $file);
and instead of asset() I used:
Storage::disk('public')->url($asset['file']);
Check this docs. https://laravel.com/docs/5.5/filesystem#the-public-disk
As it shows there instead of
$name = 'public/' . time() . str_random(5) . '.' . $file->getClientOriginalExtension();
you can just have
$name = 'time() . str_random(5) . '.' . $file->getClientOriginalExtension();
Storage::disk("public")->put($name, $file); // assuming you have the public disk that comes by default
Then when you want to get an url, you can use the asset function
asset('storage/foo.txt');

Flysystem local asset from outside public folder in Laravel 4

I have the following method that will get an asset depending on which CDN is used:
public function getAsset($filename, $dir = null, $prefix = null)
{
$extension = File::extension($filename);
$name = File::name($filename);
$filename = $dir . $prefix . $name . '.' . $extension;
if(Flysystem::getDefaultConnection() == 'awss3') return Flysystem::getAdapter()->getClient()->getObjectUrl('xxxx', $filename);
if(Flysystem::getDefaultConnection() == 'local') return Flysystem::getAdapter()->getClient()->getObjectUrl($filename);
}
When 'local' storage is selected (in a config) I want to be able to get the asset from the app/storage/temp/media/ directory and display them to the as an image in a tag, how can I modify the above to work like that?
How do I even get an asset from outside the public directory anyway?

Categories