Laravel: How To Sort Files By Uploaded Date ?

Link Copied To Clipboard !

sort-files-by-date-laravel Frameworks

Laravel is one of the most used PHP frameworks to build web applications. It offers variety of functionalities required to reduce the development time and cost. Considering file system managements, laravel itself provides some facades to handle files and folders.

By associating laravel file facade with collections, we can treat file object or file array as a collection. This makes each file instance as a collection model, similar to any other model objects, allowing us to use collection functions like filter, map, sortBy etc.

How To Sort Files By Uploaded Date In Laravel ?

public function getFiles($dir){
    return collect(File::allFiles($dir))
        ->filter(function ($file) {
            return in_array($file->getExtension(), ['png', 'gif', 'jpg']);
        })
        ->sortBy(function ($file) {
            return $file->getCTime();
        })
        ->map(function ($file) {
            return $file->getBaseName();
        });
}

You may apply any collection function as per requirement. For example, to sort in descending order, you may use sortByDesc .

Alternatively, you may also use following method to sort files by uploaded date. It uses more of a core php approach though.

$files = File::files(public_path() . '/storage/uploads');
//following line sorts the files according to uploaded time
usort($files, function ($x, $y) {
      return filemtime($x) < filemtime($y);
});
$files = collect($files)->map(function($file){
            return '/storage/uploads/' . $file->getBaseName();
})->toArray();

You May Also Like