How to Count Files in a Directory using Laravel?
you are working on laravel framework and you want to count how many image or files in folder and print of front then you can do with laravel "File" class.you can also count in core PHP by using glob() but if you are working on laravel then you have to use 'File' class library and it is easy and more flexible to use.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.
If you also want to remove all the files Or images in specific folder then you can delete by using "File" class function. sometimes we need to delete files in the folder. that way:
Example 1:
Controller File Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
class HomeController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function countFiles() {
$files = File::files(public_path('upload/files'));
$countFiles = 0;
if ($files !== false) {
$countFiles = count($files);
}
return $countFiles;
}
}
Example 2:
Controller File Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class HomeController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function countFiles() {
$files = Storage::allFiles('upload/files');
$countFiles = 0;
if ($files !== false) {
$countFiles = count($files);
}
return $countFiles;
}
}
Try this...
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to use Laravel Variable in JQuery?
- Laravel Cashier Stripe Subscription Example Tutorial
- Laravel Redirect to Route from Controller Example
- How to Get Columns Names from Model in Laravel?
- Laravel Ajax DELETE Request Example Tutorial
- How to Get Environment Variable in Laravel React JS?
- Laravel React JS File Upload Example Tutorial
- Laravel React JS Pagination using Vite Example
- Laravel 9 Custom Email Verification Tutorial
- How to Read XML File in Laravel?
- Laravel Eloquent whereNotNull() Query Example
- Laravel Create JSON File & Download From Text Example