I created a folder named temp in the public directory. I need to write a function that cleans the daily temp folder. How can I delete the files in the folder?
Asked
Active
Viewed 1,183 times
-1
-
So at the end of the day you need to delete all the files inside ```public/temp``` right ? – ManojKiran A Nov 05 '21 at 06:39
-
Storage::disk("public_path")->delete($temporary_file->your_path); you can delete file with this method – Hasan Çetin Nov 05 '21 at 08:09
-
As well as the generic PHP duplicate already posted, there are also many Laravel duplicates. Please try searching before posting a new question. https://stackoverflow.com/questions/36420312/laravel-delete-directory-from-public, https://stackoverflow.com/questions/47007356/laravel-file-storage-delete-all-files-in-directory, https://stackoverflow.com/questions/41207731/deleting-a-folder-with-files-in-laravel ... – Don't Panic Nov 05 '21 at 11:25
1 Answers
0
First step an custom artisan command named ClearTemp on app/Concole/Commands/ClearTemp.php. ClearTemp.php Content:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class ClearTemp extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'clear_temp';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clear all file inside temp folder';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
//
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->cleanDirectory('temp');
}
private function cleanDirectory($path, $recursive = false)
{
$storage = Storage::disk('public');
foreach ($storage->files($path, $recursive) as $file) {
$storage->delete($file);
}
}
}
Second step define the working frequency time of your job.In this case will be daily on app/Console/kernel.php kernel.php content:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
// EnsureQueueListenerIsRunning::class
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('clear_temp')->daily();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
Finally check your artisan command:
php artisan clear_temp
And make sure to activate your system cron job to check the exact time to run your function.

Zrelli Majdi
- 1,204
- 2
- 11
- 16