Delete wildcard files with Storage facade in Laravel - laravel

Is there a way which allows you to delete files with a wildcard through the Storage facade in Laravel?
use Illuminate\Support\Facades\Storage;
Storage::disk('foo')->delete('path/TO_DELETE*');
I may have a list like this
path/TO_DELETE_1
path/TO_DELETE_2
path/TO_KEEP_1
path/TO_PROCESS_1
But I want to delete only the files. I want to avoid path manipulation as much as possible

Suppose if you have files start with a_1.jpg,a_2.jpg then
$files = Storage::disk("public")->allFiles();
foreach ($files as $file){
if(Str::startsWith($file,"a_")){
Storage::disk('images')->delete($file);
}
}
or for multiple folder search
$directories = Storage::disk('public')->directories();
foreach ($directories as $directory){
$files= Storage::disk('public')->allFiles($directory);
foreach ($files as $file){
if(Str::startsWith($file,$directory."/"."a_")){
Storage::disk('public')->delete($file);
}
}
}
Another way is using File facade.
File::delete(File::glob(storage_path('app/public/*/a_*.*')));
For example you have multiple folders inside storage/app/pubic/ then you can specify like this.
app/public/*/a_*.*'
Here
First * is any folder inside public folder.
a_* means any file start from a_.
.* is any extension.
For last one i took help from this post
Ref:Delete files with wildcard in Laravel

The sub question here is how to get a list of filtered files in Laravel. This works pretty well:
$fileFilter = "someStringFilenameContains";
$files = collect($fileSource->files())->filter(function ($value) {
return str_contains($value, $fileFilter);
})->toArray();
You can modify str_contains (strstr(), substr() for instance) to suit your needs - anything that returns a truth value really.
This will give you an array of filenames that match your $fileFilter
then to answer the OP:
$fileSource->delete($files);

Related

generate Word document with dynamic variables using Laravel

This is the first time that I try to generate a Word document with Laravel.
I have in database columns that I should to generate in a Word document.
For example I have the following database:
I should generate a document file which contains hello John for example
So all the elements that is inside '<<>>' are a dynamic variables .
How can I get from database the value of the column preamble and set the variable name in the same time?
I found that exists a package names phpwordn but I found that I should have a template that is a word file with dynamic variables n but in my case I have no template I have all the components of my Word file in the database.
Is it possible to do that?
If you have any idea or an example to do that help me.
You can use preg_replace_callback() to convert all special tags to their corresponding values. In your case a tag has a form of <<foo>>, so here it goes:
$values = [
'me' => 'user14053977',
'saviour' => 'RoboRobok',
];
$template = 'My name is <<me>> and <<saviour>> saved me!';
$result = preg_replace_callback(
'#<<(\w+)>>#',
function (array $matches) use ($values): string {
[$tag, $tagName] = $matches;
return $values[$tagName] ?? $tag;
},
$template
);
// $result is now "My name is user14053977 and RoboRobok saved me!"
It's a pure PHP code. Now it's just the matter of using the values in Laravel and injecting $result to your Word document.

Laravel Store only filename when uploading a file

I have the following code to upload and store the file.
$user->update([
'display_profile' => request()->display_profile->storeAs('avatars', $name,'public')
]);
This stores the file in the display_profile as avatars/filename.jpg.
Since I have multiple versions of the files for displaying around the views I am using prefixes like follow
thumb_filename.jpg
small_filename.jpg
large_filename.jpg
I will need to do a lot of string replace to insert the prefix in place to show the right version of the images. Is there anyway I can save just the filename in the database insteat of the full path?
If not whats the best way to show my files in the view?
I use this approach mostly:
$file = $request->file('display_profile');
$name = $file->getClientOriginalName() . '.' . $file->extension();
$file->storeAs('public/avatars', $name);
$user->update([
'display_profile' => $name
]);
When you retrieve a file from the request, this will be converted as an UploadedFile object. You can easily retrieve the original name as follow
$file = $request->display_profile;
$user->update([
'display_profile' => $file->getClientOriginalName()
]);
For your second question I suggest you to create a relation with a Image class where you can store all the image conversion you require. But this can be a little tricky and may require time to be coded. Fortunately there are tons of libraries that can handle this for you. My favourite is Laravel medialibrary

Batch printing PDF files with laravel

I have a program that can print an individual PDF when on a students file. I'm doing this using niklasravnsborg/laravel-pdf package in Laravel 5.7. It's working great because I can just stream the pdf from a view into the browser then print from there.
Now I'm wanting to batch print the PDF's at the end of the day instead of one by one. How can I do this? There's no documentation for this on the package repository.
Several ways I've thought of doing this: one, save each PDF as an image file then try to print all files in that folder at the end of the day. If I do this, how would I print all files in that folder?
Next: does anyone know a way to maybe append a new PDF to a variable containing all the previously looped pdf's?
For example:
$finalpdf;
$students = Student::all();
foreach($students as $student){
$pdf = PDF::loadView('pdf.document', $student);
$finalpdf .+ $pdf; //i know this line doesn't work, but how to alter it?
return $pdf->save('document.pdf');
}
After a few days of playing around, hopefully this solution helps someone in the future. I used another package called "lara pdf merger". By writing my files to a save destination, adding those files to a merged file, then deleting the saved files after download, I was able to get my functionality. This is my controller code:
use PDF;
use Illuminate\Filesystem\Filesystem;
use LynX39\LaraPdfMerger\Facades\PdfMerger;
public function batchPrint(){
$pdfMerger = PDFMerger::init();
$i = 0;
$students = Student::whereDate('updated_at', Carbon::today('America/Los_Angeles'))->get();
foreach ($students as $student) {
$pdf = PDF::loadView('printTables', compact('student'));
$pdf->save('pdf/document'.$i.'.pdf');
$pdfMerger->addPDF('pdf/document'.$i.'.pdf');
$i++;
}
$pdfMerger->merge();
$pdfMerger->save("file_name.pdf", "browser");
$file = new Filesystem;
$file->cleanDirectory('pdf');
}

Serving a stored file with a controller and best place to store file

I'm creating a feed in CSV file format for products in magento.
We already have some CSV files generated on the fly and returned by magento controller.
But I would like to pre-generate the file and save it in some place and directly return the file upon request.
Where is the best place to save this file?
And how can I return it from controller?
BTW, the file is rarely accessed, so I don't want to store it in memcache, just as a generic file.csv
Creating a directory under {Magento Base Install Path}/var/ would be a logical place to cache the file.
To return the file from the controller you can use:
$fileName = 'file.csv'
$filePath = Mage::getBaseDir('var') . '/csvfilecache/' . $fileName;
$content = array('type' => 'filename', 'value' => $filePath);
$this->_prepareDownloadResponse($fileName, $content, 'text/csv');
See Mage_Core_Controller_Varien_Action::_prepareDownloadResponse

How to import data from a file into Redis database?

I am a very NOOB in Redis and this is the first time that I am using this application.I hope you can help me.
I am trying to create a list of words from a dictionary and put in into Redis database. I have a text file containing 200,000 words. How can I put it in my database?
I am using Laravel and My Redis configuration is working fine, because I am able to execute this command.
$redis = Redis::connection();
Redis::set('name', 'MYname');
$name = Redis::get('name');
echo $name;
Thanks in advance!
What is the dictionary used for?
If it is just 200,000 words, you can simply put all of them into a set.
for word in text_file:
Redis::sadd('dictionary_name', word)
and use
Redis::sismember('dictionary_name', word)
to check whethor or not the word is in the dictionary.
Here's documentation about redis set
Finally, I am able to upload my data through this command.
$filename = 'file.txt';
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
$redis = Redis::connection();
Redis::sadd('dictionary', $array);

Resources