Sort storage files by modified date in Laravel - laravel

I'm building a personal blog using Laravel 8, where the articles are displayed from .md files (no database). Everything works perfectly, but I'm struggling to sort those .md files by the modified date or creation date. Files are placed into the storage folder
Current code:
// Getting files from storage:
$files = Storage::disk('articles')->allFiles();
$articles = [];
foreach ($files as $file) {
$storage = Storage::disk('articles')->get($file);
array_push($articles, $storage);
$collection = collect($articles);
}
$array = collect($articles);
$articles = $this->paginate($array);
return view('pages.home', compact('articles'));
I've tried to get file details using the filemtime() function, but I get the following error:
$filePath = Storage::path($file);
$fileDate = filemtime($filePath);
dd($fileDate);
ErrorException
filemtime(): stat failed for C:\my-project\storage\app\article-file.md
stat function returns the same error.
Storage is linked, file exists, it returns the right path...
I'm out of ideas...

Laravel already has method to read last modify file metadata
Storage::lastModified($name);
Link to documantation:
https://laravel.com/docs/8.x/filesystem#file-metadata

Related

how to save dompdf file to storage and name the file dynamicly in laravel

does anyone know how to save generated pdf file and name it dynamicly using dompdf in laravel?
i always encounter this error
failed to open stream: No such file or directory
while trying to generated pdf file and save it to project directory.
here its my controller code
$bills = Tagihan::join('pesanan', 'tagihan.id_pesanan', 'pesanan.id_pesanan')
->join('kendaraan', 'pesanan.id_kendaraan', 'kendaraan.id_kendaraan')
->join('kategori_mobil', 'kendaraan.id_kategori_kendaraan', 'kategori_mobil.id_kategori')
->join('users', 'pesanan.id_pengguna', 'users.id')
->where('pesanan.id_pesanan', $save->id_pesanan)
->select('pesanan.*', 'users.*', 'tagihan.*', 'kendaraan.*', 'kategori_mobil.nama_kategori')
->first();
$today = Carbon::now('GMT+7')->toDateString();
$pdf = new PDF();
$pdf = PDF::loadView('admin.tagihan.pdf', compact('bills','today'));
file_put_contents('public/bills/'.$noOrder.'.pdf', $pdf->output() );
return redirect()->route('pesananIndex');
i want to save my pdf file with custom string with $noOrder.'pdf', but when i use static name like this
file_put_contents('public/bills/bubla.pdf', $pdf->output());
i had no error, any solution?
You can getOriginalContent from http response into a variable then push it to your file.
$pdf = PDF::loadView('admin.tagihan.pdf', compact('bills','today'));
$content = $pdf->download()->getOriginalContent();
Storage::put('public/bills/bubla.pdf',$content);
...
Storage::disk('local')->makeDirectory('/pdf/order');
$pdf = PDF::loadView('PDF.Order.OrderPDF-dev', ['invoiceDetail'=>$invoiceDetail]);
$path = 'storage/pdf/order/';
$pdf->save($path . $fileName);
return url($path.$fileName);
In my example first i created folder for PDF. makeDirectory(...) will create folder if exist or not.
$path is location where i want to put my file in Dir. do not use absolute path or public path function here. only define location where you want to create file.
I am creating file in Storage folder. so i added storage/.....

Laravel : To rename an uploaded file automatically

I am allowing users to upload any kind of file on my page, but there might be a clash in names of files. So, I want to rename the file automatically, so that anytime any file gets uploaded, in the database and in the folder after upload, the name of the file gets changed also when other user downloads the same file, renamed file will get downloaded.
I tried:
if (Input::hasFile('file')){
echo "Uploaded</br>";
$file = Input::file('file');
$file ->move('uploads');
$fileName = Input::get('rename_to');
}
But, the name gets changed to something like:
php5DEB.php
phpCFEC.php
What can I do to maintain the file in the same type and format and just change its name?
I also want to know how can I show the recently uploaded file on the page and make other users download it??
For unique file Name saving
In 5.3 (best for me because use md5_file hashname in Illuminate\Http\UploadedFile):
public function saveFile(Request $request) {
$file = $request->file('your_input_name')->store('your_path','your_disk');
}
In 5.4 (use not unique Str::random(40) hashname in Illuminate\Http\UploadedFile). I Use this code to ensure unique name:
public function saveFile(Request $request) {
$md5Name = md5_file($request->file('your_input_name')->getRealPath());
$guessExtension = $request->file('your_input_name')->guessExtension();
$file = $request->file('your_input_name')->storeAs('your_path', $md5Name.'.'.$guessExtension ,'your_disk');
}
Use this one
$file->move($destinationPath, $fileName);
You can use php core function rename(oldname,newName) http://php.net/manual/en/function.rename.php
Find this tutorial helpful.
file uploads 101
Everything you need to know about file upload is there.
-- Edit --
I modified my answer as below after valuable input from #cpburnz and #Moinuddin Quadri. Thanks guys.
First your storage driver should look like this in /your-app/config/filesystems.php
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'), // hence /your-app/storage/app/public
'visibility' => 'public',
],
You can use other file drivers like s3 but for my example I'm working on local driver.
In your Controller you do the following.
$file = request()->file('file'); // Get the file from request
$yourModel->create([
'file' => $file->store('my_files', 'public'),
]);
Your file get uploaded to /your-app/storage/app/public/my_files/ and you can access the uploaded file like
asset('storage/'.$yourModel->image)
Make sure you do
php artisan storage:link
to generate a simlink in your /your-app/public/ that points to /your-app/storage/app/public so you could access your files publicly. More info on filesystem - the public disk.
By this approach you could persists the same file name as that is uploaded. And the great thing is Laravel generates an unique name for the file so there could be no duplicates.
To answer the second part of your question that is to show recently uploaded files, as you persist a reference for the file in the database, you could access them by your database record and make it ->orderBy('id', 'DESC');. You could use whatever your logic is and order by descending order.
You can rename your uploaded file as you want . you can use either move or storeAs method with appropiate param.
$destinationPath = 'uploads';
$file = $request->file('product_image');
foreach($file as $singleFile){
$original_name = strtolower(trim($singleFile->getClientOriginalName()));
$file_name = time().rand(100,999).$original_name;
// use one of following
// $singleFile->move($destinationPath,$file_name); public folder
// $singleFile->storeAs('product',$file_name); storage folder
$fileArray[] = $file_name;
}
print_r($fileArray);
correct usage.
$fileName = Input::get('rename_to');
Input::file('photo')->move($destinationPath, $fileName);
at the top after namespace
use Storage;
Just do something like this ....
// read files
$excel = $request->file('file');
// rename file
$excelName = time().$excel->getClientOriginalName();
// rename to anything
$excelName = substr($excelName, strpos($excelName, '.c'));
$excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;
$excel->move(public_path('equities'),$excelName);
This guy collect the extension only:
$excelName = substr($excelName, strpos($excelName, '.c'));
This guy rename its:
$excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;

Print File Info in Laravel

I want to print the list of all files along with the information about them like created, updated and size. Currently, I use
$files = File::allFiles('downloads');
But, this just gives me the filename. Is there a better way or is there any property for the same thing that I am missing?
As per the documentation. If you really want complete info for each file.
You can try something like this
$files = Request::allFiles()
$fullInfo = [];
foreach($files as $file)
{
$fullInfo[$file] = UploadedFile::createFromBase($file)
}
Ref: this line 429 to 455
Edit:
Sorry my bad even UploadedFile::createFromBase will return object
I think we don't have option in laravel to dump every properties of file. You can access each property by calling the functions like getClientOriginalName.
Or try native method $_FILES to
$files = $request->file('file');
foreach ($files as $file) {
$file_name = $file->getClientOriginalName();
}

How to display file which had already upload laravel 5.2?

I upload file in to my database and moved that file as same name in documents folder in a root path like below :)
public function store(PslCall $call,Request $request)
{
$this->validate($request, $this->rules);
$uploadDestinationPath = base_path() . '/documents/';
$current_id = Document::where('call_id',$call->id)->count()+1;
if ($request->hasFile('file'))
{
$file =$request->file;
$fileName = $file->getClientOriginalName();
$file->move($uploadDestinationPath, $call->id.'_'.$current_id.'_'.$fileName);
}
$input = $request->all();
$input['file'] = $call->id.'_'.$current_id.'_'.$fileName;
$input['call_id'] = $call->id;
Auth::user()->documents()->create($input);
return Redirect::route('calls.documents.index',$call->id)->with('message','You have successfully submitted');
}
its works perfect now im display in my index page all the files like below :)
<td>{{strtoupper($document->title)}}</td>
<td>{{$document->file}}</td>
now my route file i have route to display my file like this :
Route::get('documents/{file}',function() {
return 'hi';
});
here im getting hi output when i click <td>{{$document->file}}</td> this path
but i want know how to display file which i upload same file name ?
As documentation says if you want to display the file content then you may use inside your route function something like:
return response()->file('pathToFile');
If download the file is what you want, then try to use instead:
return response()->download('pathToFile');

Laravel 4 get image from url

OK so when I want to upload an image. I usually do something like:
$file = Input::file('image');
$destinationPath = 'whereEver';
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
if( $uploadSuccess ) {
// save the url
}
This works fine when the user uploads the image. But how do I save an image from an URL???
If I try something like:
$url = 'http://www.whereEver.com/some/image';
$file = file_get_contents($url);
and then:
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
I get the following error:
Call to a member function move() on a non-object
So, how do I upload an image from a URL with laravel 4??
Amy help greatly appreciated.
I don't know if this will help you a lot but you might want to look at the Intervention Library. It's originally intended to be used as an image manipulation library but it provides saving image from url:
$image = Image::make('http://someurl.com/image.jpg')->save('/path/saveAsImageName.jpg');
$url = "http://example.com/123.jpg";
$url_arr = explode ('/', $url);
$ct = count($url_arr);
$name = $url_arr[$ct-1];
$name_div = explode('.', $name);
$ct_dot = count($name_div);
$img_type = $name_div[$ct_dot -1];
$destinationPath = public_path().'/img/'.$name;
file_put_contents($destinationPath, file_get_contents($url));
this will save the image to your /public/img, filename will be the original file name which is 123.jpg for the above case.
the get image name referred from here
Laravel's Input::file method is only used when you upload files by POST request I think. The error you get is because file_get_contents doesn't return you laravel's class. And you don't have to use move() method or it's analog, because the file you get from url isn't uploaded to your tmp folder.
Instead, I think you should use PHP upload an image file through url what is described here.
Like:
// Your file
$file = 'http://....';
// Open the file to get existing content
$data = file_get_contents($file);
// New file
$new = '/var/www/uploads/';
// Write the contents back to a new file
file_put_contents($new, $data);
I can't check it right now but it seems like not a bad solution. Just get data from url and then save it whereever you want

Resources