1

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?

2
  • Can you try $test_id->test_id Commented May 23, 2018 at 19:10
  • @berkaykılıç I get an error: Trying to get property 'test_id' of non-object Commented May 23, 2018 at 19:13

2 Answers 2

4

Can use insertGetId, eg:

$id = DB::table('users')->insertGetId(
    [ 'name' => 'first' ]
);

or try this:

$id = DB::getPdo()->lastInsertId();

In your case this worked:

$id = DB::connection('pgsql')
    ->table('test')
    ->insertGetId(['test_name' => 'hello world'], 'test_id');

https://laravelcode.com/post/laravel-55-get-last-inserted-id-with-example

Sign up to request clarification or add additional context in comments.

3 Comments

Using insertGetId gives me the error: Call to undefined method Illuminate\Database\PostgresConnection::insertGetId(). Any idea why?
ah, guess method doesnt belong to post gres connection but to the query builder. updated answer, maybe u can see a way to use it.
I'm using multiple types of databases so DB::table wouldn't work. I did figure it out based on the table method. If you want to update your answer I can accept it, otherwise I'll post my own. The final query looks like: $test_id = DB::connection('pgsql')->table('test')->insertGetId(['test_name' => 'hello world'], 'test_id'); I guess as a second parameter you can specify what you want it to return.
1

kind of old but I've just solved this issue in a funny way and wanted to share my answer.

It's kind of weird but the use of select and selectOne laravel function is the key:

// Single row insertion
$insertion = DB::selectOne("INSERT INTO cities (user_uuid, postal_code) VALUES (?, ?) RETURNING uuid", [$name, $postal_code]);

echo $insertion->uuid;


// Multiple rows insertion
$insertion = DB::select("INSERT INTO cities (user_uuid, postal_code) VALUES (?, ?), (?, ?) RETURNING uuid", [$name, $postal_code, $name, $postal_code]);

foreach($insertion as $city) {
    echo $city->uuid;
}

Have fun :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.