Import Large sql file in Laravel using Seeder Example

This example will show you how to import large sql file in laravel using database seeder. If you want to upload sql file using command then you can read here in ubuntu or window. Here using this example you can easily import, run or query to import a large sql file in laravel database using seeder.

Read Also: Import SQL file to Database using Command Line in Windows

Read Also: How to import SQL file using the command line in MySQL Database

For running or importing sql file using command you need to create a seeder file by artisan command:

php artisan make:seeder ImportSqlFileSeeder

Now update the below code on your generated seeder

database/seeders/ImportSqlFileSeeder.php

<?php
  
namespace Database\Seeders;
  
use Illuminate\Database\Seeder;
  
class ImportSqlFileSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $sql = public_path('sql_file.sql');
          
        $credentials = [
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'host' => env('DB_HOST'),
            'database' => env('DB_DATABASE')
        ];
  
        exec("mysql --user={$credentials['username']} --password={$credentials['password']} --host={$credentials['host']} --database {$credentials['database']} < $sql");
  
        \Log::info('SQL Imported successfully');
    }
}

Now run the seeder using the following command:

php artisan db:seed --class=ImportSqlFileSeeder

Leave a Comment