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