One of the greatest things about Laravel Excel is its event system – you can easily register closures or classes to be executed during certain events in the import lifecycle, such as before and after the import.
I’ve often wanted to truncate a database table to import the data ‘fresh’ before an import – I can think of twice off the top of my head where I’ve wanted to do this within commercial software. One thing to remember, however, is that all Laravel Excel imports are wrapped in a database transaction. To quote the documentation found here:
The entire import is automatically wrapped in a database transaction, that means that every error will rollback the entire import. When using batch inserts, only the current batch will be rollbacked.
You can of course, disable database transactions entirely if you’d prefer to do it yourself and/or if you really need database truncation, but for the most part, just remember that calling truncate()
on an Eloquent model or table will itself trigger a database transaction and subsequently your import may fail due to the nested transactions if not supported by your DBMS.
If in doubt, simply use Model::query()->delete()
to blitz your table free of entries before your import. Your importer class should implement the WithEvents
interface. Your implementation might look a little like this:
public function registerEvents(): array
{
return [
BeforeImport::class => function (): void {
// Don't call truncate, call delete!
Model::query()->delete();
},
];
}