MySQL Load Data Infile Support For Laravel

Overview

Laravel Load File 💽

Latest Stable Version License

A package to help with loading files into MySQL tables.

This uses MySQL's LOAD DATA statement to load text files quickly into your database.

This is usually 20 times faster than using INSERT statements according to: https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html

Options

This library currently can handle any of the options in a normal LOAD DATA statement except for the partitioned table support. This will be included in a future release of laravel-loadfile.

Further information on the following options that can be passed to the load file builder can be found here:

https://dev.mysql.com/doc/refman/8.0/en/load-data.html

Installation

Requires Laravel 6 or above

composer require ellgreen/laravel-loadfile

Loading files

To use local files you will need to have local_infile enabled for the client and server. To do this on the Laravel side you will need to add the following to the options part of your database config:

'config' => [
    PDO::MYSQL_ATTR_LOCAL_INFILE => true,
],

Simple file import

use EllGreen\LaravelLoadFile\Laravel\Facades\LoadFile;

LoadFile::file('/path/to/employees.csv', $local = true)
    ->into('employees')
    ->columns(['forename', 'surname', 'employee_id'])
    ->load();

Ignoring header row

LoadFile::file('/path/to/employees.csv', $local = true)
    ->into('employees')
    ->columns(['forename', 'surname', 'employee_id'])
    ->ignoreLines(1)
    ->load();

Specifying field options

LoadFile::file('/path/to/employees.csv', $local = true)
    ->into('employees')
    ->columns(['forename', 'surname', 'employee_id'])
    // like this
    ->fieldsTerminatedBy(',')
    ->fieldsEscapedBy('\\\\')
    ->fieldsEnclosedBy('"')
    // or
    ->fields(',', '\\\\', '"')
    ->load();

Specifying line options

LoadFile::file('/path/to/employees.csv', $local = true)
    ->into('employees')
    ->columns(['forename', 'surname', 'employee_id'])
    // like this
    ->linesStartingBy('')
    ->linesTerminatedBy('\\n')
    // or
    ->lines('', '\\n')
    ->load();

Input preprocessing (set)

LoadFile::file('/path/to/employees.csv', $local = true)
    ->into('employees')
    ->columns([
        DB::raw('@forename'),
        DB::raw('@surname'),
        'employee_id',
    ])
    ->set([
        'name' => DB::raw("concat(@forename, ' ', @surname)"),
    ])
    ->load();

Using a different connection

LoadFile::connection('mysql')
    ->file('/path/to/employees.csv', $local = true)
    ->into('employees')
    ->columns(['forename', 'surname', 'employee_id'])
    ->load();

Duplicate-key and error handling

LoadFile::connection('mysql')
    ->file('/path/to/employees.csv', $local = true)
    ->replace()
    // or
    ->ignore()
    ->into('employees')
    ->load();

Loading data into Eloquent Models

Simply add the LoadsFiles trait to your model like so:

use EllGreen\LaravelLoadFile\Laravel\Traits\LoadsFiles;

class User extends Model
{
    use LoadsFiles;
}

Then you can use the following method to load a file into that table:

User::loadFile('/path/to/users.csv', $local = true);

Need to specify options to load the file with?

Add the following method to your Model

class User extends Model
{
    use LoadsFiles;

    public function loadFileOptions(Builder $builder): void
    {
        $builder
            ->fieldsTerminatedBy(',')
            ->ignoreLines(1);
    }
}

Or you can get an instance of the query builder on the fly

User::loadFileBuilder($file, $local)
    ->replace()
    ->ignoreLines(1)
    ->load();

Development

Unit tests

composer test-unit

All tests

You will need to have docker installed for these.

composer check
You might also like...
PHP version of mysqldump cli that comes with MySQL

MySQLDump - PHP Requirements | Installing | Getting started | API | Settings | PDO Settings | TODO | License | Credits This is a php version of mysqld

Symfony 5.2 + api platform project with ELK stack + elastic FileBeats for the log management. All running in 7 docker containers: nginx, php 8, mysql, elastic search, logstash, kibana, fileBeats.

Symfony with ELK and Elastic FileBeats Stack Prerequisites: Make sure that docker and docker-compose are installed in your machine and available for y

A simple PHP and MySQL based internet forum that displays the messages in classical threaded view (tree structure)

my little forum my little forum is a simple PHP and MySQL based internet forum that displays the messages in classical threaded view (tree structure).

phpMyFAQ - Open Source FAQ web application for PHP and MySQL, PostgreSQL and other databases

phpMyFAQ 3.1 What is phpMyFAQ? phpMyFAQ is a multilingual, completely database-driven FAQ-system. It supports various databases to store all data, PHP

A simple and extensible fixture loader for PHP 7.3+, supporting SQLite and MySQL

Flowder Flowder is a (really) simple fixture loader for PHP 7.3+, supporting SQLite and MySQL. Using Flowder in PHP 7.2 or below? Try version 1 instea

A Symfony application for managing and automating regular backups of MySQL databases.
A Symfony application for managing and automating regular backups of MySQL databases.

DbSaver DbSaver is an application written by Bastien LOUGHIN allowing you to make automatic daily backups (and manual backups) for your MySQL database

TO DO LIST WITH LOGIN AND SIGN UP and LOGOUT using PHP and MySQL please do edit the _dbconnect.php before viewing the website.

TO-DO-LIST-WITH-LOGIN-AND-SIGN-UP TO DO LIST WITH LOGIN AND SIGN UP and LOGOUT using PHP and MySQL please do edit the _dbconnect.php before viewing th

Connect and work with MySQL/MariaDB database through MySQLi in PHP. This is an introductory project, If you need a simple and straightforward example that takes you straight to the point, you can check out these examples.
Connect and work with MySQL/MariaDB database through MySQLi in PHP. This is an introductory project, If you need a simple and straightforward example that takes you straight to the point, you can check out these examples.

First MySQLi PHP Connect and work with MySQL/MariaDB database through MySQLi in PHP. The above exercises are designed for students. This is an introdu

Very easy to use PDO MYSQL API. Just Include in PHP file and get it working.

CRUD-MYSQL-API Very easy to use PDO MYSQL API. Just Include in PHP file and get it working. INSTALATION Step 1: git clone https://github.com/arhex-lab

Comments
  • How to handle

    How to handle "NULL" strings?

    Hello,

    is there a way to handle columns that have NULL as a string?

    After the import that column doesnt have the word NULL and it is empty.

    Thank you for your great package.

    opened by K2ouMais 2
Releases(2.0.0)
Owner
Ellis Green
Ellis Green
MySQL Spatial Data Extension integration with Laravel.

Laravel MySQL Spatial extension Laravel package to easily work with MySQL Spatial Data Types and MySQL Spatial Functions. Please check the documentati

Joseph Estefane 741 Jan 9, 2023
Small script for importing the KvK (Dutch Chamber of Commerce) Open Data Set (CSV file) to a MySQL database.

KvK-CSV-2-SQL Small script for importing the KvK (Dutch Chamber of Commerce) Open Data Set (CSV file) to a MySQL database. Table of content KvK-CSV-2-

BASTIAAN 3 Aug 5, 2022
ATK Data - Data Access Framework for high-latency databases (Cloud SQL/NoSQL).

ATK Data - Data Model Abstraction for Agile Toolkit Agile Toolkit is a Low Code framework written in PHP. Agile UI implement server side rendering eng

Agile Toolkit 257 Dec 29, 2022
A mysql database backup package for laravel

Laravel Database Backup Package This package will take backup your mysql database automatically via cron job. Installing laravel-backup The recommende

Mahedi Hasan Durjoy 20 Jun 23, 2021
Laravel Code Generator based on MySQL Database

Laravel Code Generator Do you have a well structed database and you want to make a Laravel Application on top of it. By using this tools you can gener

Tuhin Bepari 311 Dec 28, 2022
Get MYSQL statement from query builder in laravel helper

Get MYSQL statement laravel This package allows to get mysql statement that query builder in laravel made it for debugging purposes. Basic usage Dump

Ahmed Helal 9 Jul 15, 2022
Extend Jenssegers/laravel-mongodb to support transaction function

Laravel Mongodb (Transactional support) Introduction Jensseger's laravel-mongodb extension package is very popular among Laravel developers, but it la

Iman RJ 10 Nov 1, 2022
Independent query builders for MySQL, PostgreSQL, SQLite, and Microsoft SQL Server.

Aura.SqlQuery Provides query builders for MySQL, Postgres, SQLite, and Microsoft SQL Server. These builders are independent of any particular database

Aura for PHP 424 Dec 12, 2022
A web interface for MySQL and MariaDB

phpMyAdmin A web interface for MySQL and MariaDB. https://www.phpmyadmin.net/ Code status Download You can get the newest release at https://www.phpmy

phpMyAdmin 6.4k Jan 5, 2023
A validating SQL lexer and parser with a focus on MySQL dialect.

SQL Parser A validating SQL lexer and parser with a focus on MySQL dialect. Code status Installation Please use Composer to install: composer require

phpMyAdmin 368 Dec 27, 2022