Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

marco987's avatar

How to insert data into a configured database in config/database?

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

'connections' => [ 'my_db' => [ 'driver' => 'mysql', 'host' => '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.

I have multiple connections defined in config/database 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']);

0 likes
3 replies
marco987's avatar
marco987
OP
Best Answer
Level 1

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.

Please or to participate in this conversation.