Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 903
SoldierCorp Avatar asked Jan 13 '14 06:01

SoldierCorp


People also ask

How can I get last insert ID in Laravel?

you can use it and get last ID of inserted record in laravel application. DB::table('users')->insert([ 'name' => 'TestName' ]); $id = DB::getPdo()->lastInsertId();; dd($id); 3) Using create() method. $data = User::create(['name'=>'first']); dd($data->id);

How do you find the last inserted value?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.


1 Answers

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); 
like image 128
xdazz Avatar answered Sep 20 '22 18:09

xdazz