1

In short: seeding is working fine with mysql while breaks with sqlite. The broken code is like DB::table('user')->insert($users);

Seed code:

<?php
public function run() {
    DB::table('user')->delete();
    $users = array();
    $birth = new DateTime('1980-03-12');
    while ($i++ < 50) {
        $users[$i]['email'] = "[email protected]";
        $users[$i]['password'] = User::password('test');
        $users[$i]['enabled'] = 1;
        $users[$i]['name'] = 'Name';
        $users[$i]['surname'] = 'Surname';
        $users[$i]['birthDate'] = $birth;
    }
    DB::table('user')->insert($users); //<- This line is broken when using sqlite.
}

My default database driver is mysql, now i am trying to switch to sqlite for the testing environment. So, under

app/config/testing/database.php

i have this config, inside 'connections' ('default' key is 'sqlite')

'sqlite' => array(
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ),

Now, if i issue

php artisan migrate --seed, this is working fine.

If i issue

php artisan migrate --seed --env=testing, this is NOT working

The DB::table('user')->insert($users); above is failing, infact when i comment that out the seeding works fine. The error at command line is

ErrorException","message":"array_keys() expects parameter 1 to be array, null given [...] /laravel/framework/src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php","line":52

What's wrong here?

1 Answer 1

3

Looking at line 52 we find:

$names = $this->columnize(array_keys($values[0]));

This is used to build the column list part of the query (INSERT INTO (column1, column2) VALUES...)

$values is in your case $users, but it does not have a 0 index. Why? while ($i++ < 50) increments $i before entering the loop body so the first index of $users will be 1, not 0 as the Laravel SQLite insert implementation needs.

Fix it like this:

$i = 0;
while ($i < 49) {
    ...
    $i++;
}

Why does the MySQL implementation work? This is what the corresponding line looks like in this implementation:

$columns = $this->columnize(array_keys(reset($values)));
Sign up to request clarification or add additional context in comments.

1 Comment

If anyone is interested I submitted a pull request for this github.com/laravel/framework/pull/2405

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.