0

I'm working within Laravel Spark and am inserting values into a MySQL table. I'm performing a series of inserts such as

DB::table('nameOfTable')->insert(['id' =>  $user['id']]);
DB::table('nameOfTable')->insert(['name' =>  $user['name']]);

The values are being inserted into the table properly, but each value is being placed on its own row. There's got to be a simple reason, but I haven't found any luck doing searches. Thanks in advance.

  • 4
    Yes, your'e executing two separate inserts, so you'll get two rows inserted.... that's the way insert works.... however, you can do a single insert with multiple values: `DB::table('nameOfTable')->insert(['id' => $user['id'], 'name' => $user['name']]);` – Mark Baker May 26 '16 at 22:45
  • And looking in the [Laravel docs](https://laravel.com/docs/5.2/queries#inserts) might have helped – Mark Baker May 26 '16 at 22:47
  • @Mark Baker please post that as an answer next time , good work – Achraf Khouadja May 27 '16 at 00:50

1 Answers1

3

Each line of code you have in your question was designed to insert a row by itself. In order to insert more than one value in the same row (AKA insert various column values in the same row), all you have to do is include more values inside the array that is being passed to the insert function:

DB::table('nameOfTable')->insert(['id' =>  $user['id'],'name' =>  $user['name']]);

The previous line of code should work fine. I personally prefer to write the code as follows since it is cleaner to read for us mortals xD:

DB::table('nameOfTable')->insert(array(
    'id' =>  $user['id'],
    'name' =>  $user['name']
));
Webeng
  • 7,050
  • 4
  • 31
  • 59
  • Thanks for the reply. The problem is that I'm executing an if statement for each insert prior to inserting it; I suppose I could nest these if statements in the first insert, but I'll probably try to find a work-around. Thanks! – HannahHunt May 27 '16 at 17:22
  • @HannahHunt no problem hannah :). Oh and if this answer is the one that worked for you, please accept it (green checkmark) so that future readers and users know it worked for you. – Webeng May 27 '16 at 17:53