intervle - app/Console/Commands/ImportEventData.php
<?php
namespace App\Console\Commands;
use App\Models\Event;
use Illuminate\Console\Command;
class ImportEventData extends Command
{
protected $signature = 'events:import {file}';
protected $description = 'Import events from a CSV file';
public function handle()
{
$file = $this->argument('file');
$handle = fopen($file, 'r');
if (fgetcsv($handle) !== ['date', 'description']) {
$this->error();
return Command::FAILURE;
}
$count = 0;
while (($row = fgetcsv($handle)) !== false) {
[$date, $description] = $row;
if (!strtotime($date)) {
$this->warn("Invalid date: $date");
continue;
}
Event::firstOrCreate([
'date' => $date,
'description' => $description
]);
$count++;
}
fclose($handle);
$this->info("$count events successfully imported.");
return Command::SUCCESS;
}
}