Home >Backend Development >PHP Tutorial >How to Retrieve the Last Inserted ID Using Laravel Eloquent?
Retrieving Last Inserted ID via Laravel Eloquent
To insert data and retrieve the last inserted ID in Laravel Eloquent, follow these steps:
1. Insert Data:
$data = new Company; $data->fill($post); $data->save();
2. Obtain Last Inserted ID:
After the save operation, access the id attribute of the $data object. This attribute represents the last inserted ID:
$lastInsertId = $data->id;
3. Return ID:
In your controller, return the last inserted ID as a JSON response:
return response()->json(['success' => true, 'last_insert_id' => $lastInsertId], 200);
Example Code:
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"); $data->save(); return response()->json(['success' => true, 'last_insert_id' => $data->id], 200); }
The above is the detailed content of How to Retrieve the Last Inserted ID Using Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!