Run raw insert query or SQL file in Laravel seeder

Hey, what’s up!
I am working to develop a base structure for one of my SAAS application and the scenario is we need to seed a good amount of data wither through Laravel seeded or from the SQL dump file. So, I want to do it both ways. I want to run the SQL dump file through the Laravel seeder. Here is the solution

First, create a seeder file by artisan command
php artisan make:seeder SqlSeeder

It will create a seeder file in database\seeds\SqlSeeder.php

And now put the below code into run() function in the SqlSeeder.php file
$path = base_path() . '/database/seeds/data.sql';
$sql = file_get_contents($path);
DB::unprepared($sql);

$path: is the path of the dump data.sql file
$sql: storing data.sql file’s content (sql query) through file_get_contents() function.
And executing queries at the 3rd line.

Now run the artisan command
php artisan db:seed --class=SqlSeeder

***Magic*** 😀
Now check the database and thanks me by sharing and comment on this article. 😉

One Reply on “Run raw insert query or SQL file in Laravel seeder”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.