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); //
}
}
}
Related
I am trying to delete an image that is saved in storage/app/public after one day.
I followed this answer but cannot manage to make it work. This is my first time doing anything on kernel.php so appreciate it if someone can help me figure out what Im doing wrong or if theres an easier way to do it.
Controller
// set path
$pathMedia = "/media" . "/" . $aid . '-' . uniqid() . ".jpg";
// store received image
Storage::disk("public")->put($pathMedia, $image);
// insert new received media
$media = new ReceivedMedia();
$media->media = $pathMedia;
$media->type = 'image';
$media->delete_at = Carbon::now()->addDays(1)->format('Y-m-d');
$media->save();
Kernel.php
use Carbon\Carbon;
$schedule->call(function () {
$files = DB::table('received_media')->whereDate('delete_at', Carbon::now()->format('Y-m-d'))->get();
foreach ($files as $file) {
$mediaPath = public_path('storage') . $file->media;
if ($file->media != null && File::exists($mediaPath)) {
unlink($mediaPath);
}
$file->delete();
}
})->daily();
You are storing the file in Storage and trying to delete it from the public folder.
You should delete it from the storage instead of public
if (Storage::disk('public')->exists($file->media)) {
Storage::disk('public')->delete($file->media);
}
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)
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');
My controller code where i store the file name into a database table and also moving the file to a folder.
The issue is that i am storing the original name of a file in database table, in contrast i am moving files with uniqueid() and time() . It will arise issues in future. because in database table file name and moved file are with different names.
What i want is to store the file name into database table and move the file to folder with with uniqueid() and time().
Code :
if(Input::hasFile('profile_pic')){
$pic = Input::file('profile_pic');
$mobile->photo1 = $pic[0]->getClientOriginalName();
$mobile->photo2 = $pic[1]->getClientOriginalName();
$mobile->photo3 = $pic[2]->getClientOriginalName();
$mobile->photo4 = $pic[3]->getClientOriginalName();
$mobile->photo5 = $pic[4]->getClientOriginalName();
foreach ($pic as $k=>$file){
if(!empty($file)){
$file->move(public_path() . '/uploads/', time() . uniqid() . '-' . $k . '-laptop');
}
}
}
You will need to store the destination path into a variable and then reuse it to move the file and to store its value in the database
if(Input::hasFile('profile_pic')){
$pic = Input::file('profile_pic');
$mobile->photo1 = $pic[0]->getClientOriginalName();
$mobile->photo2 = $pic[1]->getClientOriginalName();
$mobile->photo3 = $pic[2]->getClientOriginalName();
$mobile->photo4 = $pic[3]->getClientOriginalName();
$mobile->photo5 = $pic[4]->getClientOriginalName();
foreach ($pic as $k=>$file){
if(!empty($file)){
$destinationPath = public_path() . '/uploads/', time() . uniqid() . '-' . $k . '-laptop';
$file->move($destinationPath);
// and you may store the path here to the database
// like yourObject->filePath = $destinationPath;
// yourObject->save();
}
}
}
I have a class that uses Assetic to generate some css files to disk. I'll jump right into the code.
In my layout header, I'm doing something like this:
$assetify = new Assetify();
$assetify->setDebug(true);
$assetify->setAssetDirectory(BASE_DIR . '/public/assets');
$assetify->setOutputDirectory(BASE_DIR . '/public/assets/generated');
$assetify
->addStylesheet('/assets/css/bootstrap-2.3.2.css')
->addStylesheet('/assets/css/select2-3.4.3.css')
->addStylesheet('/assets/css/main.css');
echo $assetify->dump();
My "Assetify" class runs this through Assetic. I'll paste what I hope are only the relevant portions from the dump() function:
// The Asset Factory allows us to not have to do all the hard work ourselves.
$factory = new AssetFactory($this->assetDirectory, $this->debug);
$factory->setDefaultOutput('/generated/*.css');
// The Filter Manager allows us to organize filters for the asset handling.
// For other filters, see: https://github.com/kriswallsmith/assetic
$fm = new FilterManager();
$fm->set('yui_css', new Yui\CssCompressorFilter('/usr/local/bin/yuicompressor-2.4.7.jar'));
$fm->set('yui_js', new Yui\JsCompressorFilter('/usr/local/bin/yuicompressor-2.4.7.jar'));
$factory->setFilterManager($fm);
// The Asset Manager allows us to keep our assets organized.
$am = new AssetManager();
$factory->setAssetManager($am);
// The cache-busting worker prefixes every css with what amounts to a version number.
$factory->addWorker(new CacheBustingWorker());
$assetCollection = array();
foreach ($assetGroups as $assetGroup) {
foreach ($assetGroup as $media => $items) {
$fileCollection = array();
foreach ($items as $item) {
// Add this asset to the asset collection.
$fileCollection[] = new FileAsset($item);
}
$assetCollection[] = new AssetCollection($fileCollection);
}
}
$assetCollection = new AssetCollection($assetCollection);
$am->set('base_css', $assetCollection);
// Generate the required assets. Prefixing a filter name with a question mark
// will cause that filter to be omitted in debug mode.
$asset = $factory->createAsset(
array('#base_css'),
array('?yui_css')
);
// Configure an internal file system cache so we don't regenerate this file on every load.
$cache = new AssetCache(
$asset,
new FilesystemCache($this->outputDirectory)
);
// And generate static versions of the files on disk.
$writer = new AssetWriter($this->assetDirectory);
$writer->writeAsset($cache);
This generates two different files, 87229eb-f47a352.css and a37c1589762f39aee5bd24e9405dbdf9. The contents of the files are exactly the same. The 87229eb-f47a352.css file seems to get generated every single time, and the other file is not regenerated unless the contents of the files change (this is what I would like). If I comment out the $writer->writeAsset($cache), no files are written to disk.
What obvious configuration am I missing? I appreciate the help, thank you.
I was able to roughly replicate your code and got the same results.
I was trying to get the same results as what I think you require but ended up writing my own code to cache and serve static files.
It's not complete by any means but it is working. It has the following features:
You can choose to cache files for different pages if you specify $filename
You can choose to create versions of your released files or delete previous versions
A cached file will be generated to your target folder only if changes have made to a source file
You just need to put the code in to a class or function and return the url to serve.
Hope it helps :)
<?php
use Assetic\Factory\AssetFactory;
use Assetic\AssetManager;
use Assetic\FilterManager;
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Filter\JSMinFilter;
// JavaScript Collection
$js_collection[] = new FileAsset(SCRIPT_PATH . 'jquery.js');
$js_collection[] = new FileAsset(SCRIPT_PATH . 'production.js');
if (file_exists(SCRIPT_PATH . $page_info['name'] . '.js')) {
$js_collection[] = new FileAsset(SCRIPT_PATH . $page_info['name'] . '.js');
}
// CSS Collection
$css_collection[] = new FileAsset(STYLE_PATH . 'theme.css');
if (file_exists(STYLE_PATH . $page_info['name'] . '.css')) {
$css_collection[] = new FileAsset(STYLE_PATH . $page_info['name'] . '.css');
}
// The Filter Manager allows us to organize filters for the asset handling.
$fm = new FilterManager();
$fm->set('js', new JSMinFilter());
$js = new AssetCollection (
$js_collection
);
$js->setTargetPath(SCRIPT_PATH . 'static');
$css = new AssetCollection (
$css_collection
);
$css->setTargetPath(STYLE_PATH . 'static');
$am = new AssetManager();
$am->set('js', $js);
$am->set('css', $css);
//** TO DO: put the below in a class and return the static file names **//
// options
$seperator = '-';
$filename = $page_info['name'];
$versions = false;
// get a list of all collection names
$collections = $am->getNames();
// get each collection
foreach ($collections as $collection_name) {
// get the collection object
$collection = $am->get($collection_name);
// ensure file types are identical
$last_ext = false;
foreach ($collection as $leaf) {
$ext = strtolower(pathinfo($leaf->getSourcePath(), PATHINFO_EXTENSION));
if (!$last_ext || $ext == $last_ext) {
$last_ext = $ext;
} else {
throw new \RuntimeException('File type mismatch.');
}
}
// get the highest last-modified value of all assets in the current collection
$modified_time = $collection->getLastModified();
// get the target path
$path = $collection->getTargetPath();
// the target path must be set
if (!$path) {
throw new \RuntimeException('Target path not specified.');
}
// build the filename to check
$file = ($filename) ? $filename . $seperator . $modified_time . '.' . $ext : $modified_time . '.' . $ext;
$cached_file = $path . '/' . $file;
// the file doesn't exist so we need to minify, dump and save as new cached file
if (!file_exists($cached_file)) {
// create the output dir if it doesnt exist
if (!is_dir($path) && false === #mkdir($path, 0777, true)) {
throw new \RuntimeException('Unable to create directory ' . $path);
}
// apply the filters
if ($fm->has($collection_name)) {
$collection->ensureFilter($fm->get($collection_name));
}
// If not versioned, delete previous version of this file
if (!$versions) {
if ($filename) {
foreach (glob($path . '/' . $filename . $seperator . '*.' . $ext) as $searchfile) {
#unlink($searchfile);
}
} else {
foreach (glob($path . '/*.' . $ext) as $searchfile) {
#unlink($searchfile);
}
}
}
// put the contents in the file
if (false === #file_put_contents($cached_file, $collection->dump())) {
throw new \RuntimeException('Unable to write file ' . $cached_file);
}
}
// return the cached file
echo 'output: ' . $cached_file . '<br>';
}
exit;
?>