Laravel: get last Insert id from query builder

Viewed 17044

I am new in laravel and trying to get last inserted id from this query:

DB::select("INSERT INTO current_survey (`name`, `created_by`, `description`)  SELECT `name`, `created_by`, `description` FROM survey WHERE id=survey_id");

this query working well, can any one suggest me how this is possible in laravel?

Thanks

4 Answers

According to laravel document

https://laravel.com/docs/5.8/queries#inserts

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

If you primary field column name is id then simply use

$lastInsertId = DB::table('tablename')->insertGetId($data);

When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named id. If you would like to retrieve the ID from a different "sequence" for example product_id, you may pass the column name as the second parameter to the insertGetId method.

$lastInsertId = DB::table('tablename')->insertGetId($data, 'product_id');

laravel documentation : insertGetId

Related