How to Count Files in a Directory using Laravel?

By Hardik Savani April 16, 2024 Category : 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...

Tags :
Shares