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:


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.