Get the Last Inserted Id Using Laravel Eloquent
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!
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 ;