2

My laravel application successfully uploads and stores my files where I want them to. However, I don't want to store the public url of the file in the database, and instead get them on the fly (they're stored in my public directory) and show a list of links to the uploads.

How can I retrieve File objects from just the strings returned by File::files(public_path() . "/files/uploads"); so I can get the name, size, modified date, etc?

Thanks in advance for any help!

Josh Allen
  • 987
  • 12
  • 30

2 Answers2

3

You can do the following:

foreach (File::files(public_path() . '/fonts') as $path)
{
    File::size($path);         // file size
    File::name($path);         // file name (no extension)
    File::extension($path);    // file extension
    File::mimeType($path);     // file mime type
    File::lastModified($path); // file last modified timestamp
    // and so on...
}

You can see all methods available in the Illuminate\Filesystem\Filesystem class API.

Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • 2
    Is there a way in Laravel to return a File instance object and do something like `$file->size()`? I think that is what the OP is asking.. – nivix zixer May 26 '15 at 15:57
  • This works great, though there's gotta be a better way than manually calling those methods and passing the string each time. Is there an easier way to initialize a file object that stores that information (rather than building the array/object manually)? – Josh Allen May 26 '15 at 16:00
  • 1
    @nivixzixer's answer actually uses object instances instead of the Laravel's static facades, so that's a better solution to your issue. – Bogdan May 26 '15 at 16:02
2
foreach (File::allFiles($directory) as $file)
{
    /* $file should be a Symfony\Component\Finder\SplFileInfo object */
    $file->getSize();
    $file->getFilename();
    $file->getType();
}

Documentation for the SplFileInfo. (Thanks @Bogdan!)

nivix zixer
  • 1,611
  • 1
  • 13
  • 19
  • 1
    Unfortunately File::get() returns the physical contents of the file, not a file object from the file path. – Josh Allen May 26 '15 at 15:53
  • Ah. It's been a few months since I played with Laravel's File class. – nivix zixer May 26 '15 at 15:54
  • File::allFiles() returns an array of strings of the absolute path of the file, not an SplFileInfo instance. – Josh Allen May 26 '15 at 15:58
  • 2
    @JoshAllen actually `File::files` returns an array of strings, @nivixzixer correcty pointed out that `File::allFiles` returns an array of [`SplFileInfo`](http://php.net/manual/en/class.splfileinfo.php) instances. – Bogdan May 26 '15 at 16:00
  • I completely overlooked that! This is answer I was looking for! Laravel's documentation really needs to point out that files returns an array while allFiles returns a SplFileInfo instance. Thank you both so much for your help! – Josh Allen May 26 '15 at 16:04