Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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!
by

2 Answers

Bharatgxwzm
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);
pankajshivnani123
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
]);

Login / Signup to Answer the Question.