Tutorial Laravel Seeder Import SQL file

0
36

Hello everyone here, today we will share with you about tutorial making laravel seeder to import data from SQL file. This example and easy way how to import your data from sql file to your database laravel project. This step by step tutorial laravel seeder import data from sql file will help you to create laravel seeder to import data from sql data, so let’s scroll and follow step by step below.

Laravel Seeder Import SQL File
Laravel Seeder Import SQL File

Step 1 Install Your Laravel Project
In this tutorial we use Laravel 7, but also, i think this tutorial can implement in other version of Laravel. To install laravel project via composer please run the command line below.

composer create-project --prefer-dist laravel/laravel:^7.0 nameprojecthere

Step 2 Create Connection to Database Mysql and others DB
To setup your db project connection in laravel can use environment file (.env), such as example below.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=databasename
DB_USERNAME=root
DB_PASSWORD=root

Step 3 Create Laravel Seeder to import SQL file
php artisan make:seeder ImportSQL

<?php

use Illuminate\Database\Seeder;

class ImportSQL extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {        
        $path = public_path('IMPORT_DB/pegawais.sql');        
        $sqlfile = DB::unprepared(file_get_contents($path));     
        $db_bin = "D:\wamp64\bin\mysql\mysql5.7.21\bin";
        // PDO Credentials
        $db = [
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'host' => env('DB_HOST'),
            'database' => env('DB_DATABASE')
        ];
        
        exec("$db_bin}\mysql --user={$db['username']} --password={$db['password']} --host={$db['host']} --database {$db['database']} < $sqlfile");
        
        \Log::info('Import SQL Success from sql file '.$path.'');
    }
}

 

Step 4 Run Laravel Seeder to import SQL file
php artisan db:seed –class=ImportSQL

So, if everything is executed then you will find a success message in the folder laravel log “storage\logs\laravel.log” with message such as below.

[2021-01-13 15:18:47] local.INFO: Import SQL Success from sql file D:\wamp64\www\laravel7.com\public\IMPORT_DB/pegawais.sql

Finally, we hope this laravel seeder import data from SQL file can help you. thanks.

LEAVE A REPLY

Please enter your comment!
Please enter your name here