Laravel Import Large SQL File using Seeder Example

By Hardik Savani April 16, 2024 Category : Laravel

Hello Dev,

This example is focused on laravel import large sql file. if you want to see example of laravel import data from sql file then you are a right place. you'll learn laravel seeder large sql file. you can understand a concept of laravel seed from sql file large file.

you can easily import large sql file using seeder in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

If you need to import directly sql file into database then how you will do? and if it's large file then how you can do it. i will give you simple example how to import large sql file using laravel seeder.

so let's simply create seeder with following command and write code as bellow:

php artisan make:seeder ImportTableSeeder

now it's create ImportTableSeeder.php file on seeders folder. so let's update as bellow:

make sure you have one sql file call "data.sql" in public folder

database/seeders/ImportTableSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class ImportTableSeeder extends Seeder

{

/**

* Run the database seeds.

*

* @return void

*/

public function run()

{

$sql = public_path('data.sql');

$db = [

'username' => env('DB_USERNAME'),

'password' => env('DB_PASSWORD'),

'host' => env('DB_HOST'),

'database' => env('DB_DATABASE')

];

exec("mysql --user={$db['username']} --password={$db['password']} --host={$db['host']} --database {$db['database']} < $sql");

\Log::info('SQL Import Done');

}

}

now you can easily run with bellow command:

php artisan db:seed --class=ImportTableSeeder

now it will works for you.

i hope it can help you...

Tags :
Shares