ndev ndev - 1 month ago 6
PHP Question

Laravel 5.1 - Commands not running as expected

I have some commands that run with the scheduler, some of them are not working as expected, the code works fine if placed in an external file. but when ran as a command with the scheduler it doesn't do anything, no files are deleted & there is no output from the file.

Command:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DirectoryIterator;

class CleanExports extends Command {

protected $name = 'clean:exports';

public function fire() {
$folderName = 'exports';

if (file_exists($folderName)) {
$i = 0;
foreach (new DirectoryIterator($folderName) as $fileInfo) {
if ($fileInfo->isDot()) {
continue;
}
if (time() - $fileInfo->getCTime() >= 1*24*60*60) {
unlink($fileInfo->getRealPath());
}
$i++;
}

echo $i.' files cleaned';
}

}
}


Kernel.php

<?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 = [
\App\Console\Commands\Inspire::class,
'\App\Console\Commands\CleanExports',
];

/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule) {
$schedule->command('inspire')
->hourly();

$schedule->command('clean:exports')->everyMinute()->sendOutputTo('temp/errors.txt');


}

Answer

The reason you not going to be getting any output from this is because it file_exists('exports') is going to return false.

Try adding the absolute path instead:

$folderName = public_path('exports');

Also, just for good measure and to check this is correct add an else to output something if the directory doesn't exist.

Hope this helps!

Comments