Home » Php » Using returning on insert in laravel and postgresql

Using returning on insert in laravel and postgresql

Posted by: admin October 29, 2018 Leave a comment

Questions:

I’m trying to insert values into postgresql 10 with Laravel 5.6. I have a table like this:

test
----
test_id     (identity generated by default, primary key)
test_name

My problem is getting the test_id that was just inserted back.

$test_id = \DB::connection('pgsql')->insert(
    'INSERT INTO test (test_name) VALUES (?) RETURNING test_id', 
    ['hello world']
);

If I print out $test_id, it just prints 1. I’m doing this over a loop, with different names. Everything inserts correctly, but even if test_id is 6 in the database, I keep getting back 1.

How can I correctly return $test_id in Laravel?

Answers: