Laravel - How to count number of files in folder and remove all files in folder?

By Hardik Savani September 3, 2022 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 and laravel 9 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:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use File;

class HomeController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function countImages() {

$files = File::files(public_path('textPrintImage'));

$filecount = 0;

if ($files !== false) {

$filecount = count($files);

}

return $filecount;

}

/**

* Write code on Method

*

* @return response()

*/

public function removeImages() {

File::cleanDirectory(public_path('textPrintImage'));

return back();

}

}

Try this...

Tags :