Search code examples
phpdatabaselaravellaravel-query-builder

In Laravel 8, how to insert data into a configured database in config/database.php?


In config/database.php (Laravel 8) this is configured:

'connections' => [
    'my_db' => [
        'driver' => 'mysql',
        'host' => 'xx.xx.xxx.xxx',
        'port' => '3306',
        'database' => 'Sqlxxx',
        'username' => 'Sqlxxxx',
        'password' => 'passxxx',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
    ],
   'other_db' => [
        ...
    ],
],

I try to save some data, but it doesn't work.

DB::connection('my_db')->beginTransaction();

$data = [];
$data["A"] = "a";
$data["B"] = "b";

$pdo = DB::connection('my_db')->getPdo();

if ($pdo) {
    DB::connection('my_db')
        ->table('my_table')
        ->insert($data);
}

DB::connection('my_db')->commit();

I specify that the connection to the DB my_db works, because I can get data from it. I have the impression that it can read data but not save them.

EDIT:

  • I have multiple connections defined in config/database.php
  • my_db is a database outside of my project
  • There is no error message; just a blank page (APP_DEBUG is set to true and APP_ENV to "local")
  • I added DB::connection('my_db')->beginTransaction(); to the beginning of the script, to no avail.
  • It doesn't work in the following way either: DB::connection('my_db')->insert('insert into my_table (A, B) values (?, ?)', ['a', 'b']);
  • I'm freaking out. Updating works, inserting doesn't. This works: DB::connection('my_db')->table('my_table')->where('id', '1')->update(['a' => '111']);

Solution

  • SOLVED: It was my mistake. I was trying to create a new record forgetting to indicate all the NOT NULLABLE ones. I could have figured it out by the fact that the update worked while the insertion did not. I confirm that DB::connection('my_db')->table('my_table')->insert($data); works perfectly.