christian-schoenefeld/seeds-from-sql
Laravel package demonstrating how to seed a database from a .sql file. Includes an SQLSeeder that imports SQL using DB::unprepared; run via php artisan db:seed --class=SQLSeeder (after migrate) or as part of DatabaseSeeder.
To leverage this package for SQL imports, start by installing it via Composer:
composer require vendor/package-name
The core feature introduced in v1.0.3 is the ability to import SQL directly using Laravel's DB::unprepared() method. This is useful for:
First use case: Import a .sql file into your database:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
// Read SQL file
$sql = File::get(database_path('imports/sample.sql'));
// Execute raw SQL
DB::unprepared($sql);
For Laravel Artisan integration, create a custom command:
php artisan make:command ImportSqlCommand
str_replace() to modify placeholders (e.g., replace :table with actual table names).$sql = str_replace(':prefix', config('database.connections.mysql.prefix'), $sql);
DB::transaction(function () use ($sql) {
DB::unprepared($sql);
});
$queries = explode(';', $sql);
foreach ($queries as $query) {
if (trim($query)) {
DB::unprepared($query);
}
}
DB::connection()->getPdo()->prepare()).$this->app->bind('sqlImporter', function () {
return new SqlImporter(DB::connection());
});
event(new SqlImportStarted('users.sql'));
DB::unprepared($sql);
event(new SqlImportCompleted());
if (app()->environment('local')) {
DB::unprepared($sql);
}
Transaction Limits:
DB::unprepared() bypasses Laravel’s query builder, so transactions may not roll back if an error occurs mid-import. Use explicit transactions (as shown above).Schema Conflicts:
DB::statement() with CREATE TABLE).SET FOREIGN_KEY_CHECKS = 0;
-- Your SQL here
SET FOREIGN_KEY_CHECKS = 1;
Character Encoding:
$sql = mb_convert_encoding($sql, 'UTF-8', 'UTF-8');
Performance:
ALTER TABLE table_name DISABLE KEYS;
-- Insert data
ALTER TABLE table_name ENABLE KEYS;
DB::enableQueryLog();
DB::unprepared($sql);
dd(DB::getQueryLog());
COPY for faster bulk inserts instead of INSERT statements.PRAGMA foreign_keys=OFF).$parsed = parseSqlFile('dump.sql');
// Validate $parsed['tables'], $parsed['queries'], etc.
DB::listen(function ($query) {
if (str_contains($query->sql, 'INSERT')) {
// Log affected rows
}
});
DB::connection()->getDoctrineSchemaManager():
$schema = DB::connection()->getDoctrineSchemaManager();
$backup = $schema->createSchemaSQL($schema->listTableDetails());
File::put(storage_path('backups/schema.sql'), $backup);
Note: This assessment assumes the package is lightweight and focuses on raw SQL imports. For feature-rich alternatives (e.g., Laravel’s built-in Schema::create() or packages like spatie/laravel-import), evaluate trade-offs based on use case. Always test in a staging environment first.
How can I help you explore Laravel packages today?