Get the Last Inserted Id Using Laravel Eloquent
Solution 1
After save, $data->id
should be the last id inserted.
$data->save();
$data->id;
Can be used like this.
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
For updated laravel version try this
return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
Solution 2
xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement
or DB::insert
, there is another way:
DB::getPdo()->lastInsertId();
Solution 3
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' => '[email protected]',
'votes' => 0
]);
Refer: https://laravel.com/docs/5.1/queries#inserts
Solution 4
For anyone who also likes how Jeffrey Way uses Model::create()
in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable
for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId()
but unfortunately this does not respect the $fillable
whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create
method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...
public function store() {
$input = Request::all();
$id = Company::create($input)->id;
return redirect('company/'.$id);
}
Solution 5
**** For Laravel ****
Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as
$user = new User();
$user->name = 'John';
$user->save();
// Now Getting The Last inserted id
$insertedId = $user->id;
echo $insertedId ;
SoldierCorp
Full-stack web and mobile developer Portfolio: https://edgardorl.com Youtube: http://youtube.com/SoldierCorp0
Updated on October 08, 2021Comments
-
SoldierCorp over 2 years
I'm currently using the below code to insert data in a table:
<?php public function saveDetailsCompany() { $post = Input::All(); $data = new Company; $data->nombre = $post['name']; $data->direccion = $post['address']; $data->telefono = $post['phone']; $data->email = $post['email']; $data->giro = $post['type']; $data->fecha_registro = date("Y-m-d H:i:s"); $data->fecha_modificacion = date("Y-m-d H:i:s"); if ($data->save()) { return Response::json(array('success' => true), 200); } }
I want to return the last ID inserted but I don't know how to get it.
Kind regards!
-
Casey almost 10 yearsActually you can do it right in the insert
$id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
-
Cas Bloem over 9 yearsAn object always returns an object, ofc. This is the only way to go.
-
Rafael over 9 years@Casey doing it this way will not update timestamps in the DB
-
Luís Cruz about 9 yearsBeware that if the id is NOT autoincrement, this will always return
0
. In my case the id was a string (UUID) and for this to work I had to addpublic $incrementing = false;
in my model. -
timgavin over 8 yearsThis example didn't work for me in 5.1, but this did:
$new = Company::create($input);
return redirect('company/'.$new->id);
-
Frank Myat Thu about 8 years
-
Captain Hypertext over 7 yearsExactly what I was looking for the other day! Also,
insertGetId
only works if the id columns is actually called "id". -
SaidbakR about 7 years@milz I have MySQL trigger that generate the uuid for a custom field named
aid
and I have set$incrementing = false;
but It does not returned too! -
Syfer over 6 yearsThis post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
-
GrumpyCrouton over 6 yearsThank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
-
mosid over 6 yearsThis assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
-
Jeffz almost 6 yearsWhat you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
-
Bhavin Thummar over 5 years@Benubird, I have got my solution according your answer.
-
Damilola Olowookere almost 5 years@SaidbakR while true, please can you indicate the section of the Laravel doc where you got this very important information?
-
SaidbakR almost 5 years@DamilolaOlowookere This is what I had found in my application which uses Laravel 5.4.
-
Daantje about 4 yearsThanks! This I could use in my pipeline. So no worries about race conditions and beautiful code.
-
Alex almost 4 yearstwo concurrent users adding the to the company model at the same time. this isn't reliable as the 1st post might get the id of the 2nd if the timing is right. the accepted answer is reliable.
-
Priyanka Patel almost 4 years@Alex kindly check, this is working and the best solution to get last inserted id from records.
-
Alex almost 4 yearsthe updated solution is fine, however it requires more code than the accepted answer. Simply doing
$user->id
is enough after creating to get the inserted id. -
Stefan Pintilie over 3 yearsAnd if you use a specific database connection DB::connection("conn_name")->getPdo()->lastInsertId()
-
Charles Wood over 3 yearsAnd of course, as mentioned in other comments, don't forget that using
insert
will ignore events and$fillable
, so take that into consideration! -
Khalilullah over 3 yearsBeware of using this code as there is no validation here. You should not store any information without validation.
-
Simo about 3 yearsdidn't know about this lastInsertId(). thanks man