Get the Last Inserted Id Using Laravel Eloquent

647,742

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 ;
Share:
647,742
SoldierCorp
Author by

SoldierCorp

Full-stack web and mobile developer Portfolio: https://edgardorl.com Youtube: http://youtube.com/SoldierCorp0

Updated on October 08, 2021

Comments

  • SoldierCorp
    SoldierCorp over 2 years

    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!

  • Casey
    Casey almost 10 years
    Actually you can do it right in the insert $id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
  • Cas Bloem
    Cas Bloem over 9 years
    An object always returns an object, ofc. This is the only way to go.
  • Rafael
    Rafael over 9 years
    @Casey doing it this way will not update timestamps in the DB
  • Luís Cruz
    Luís Cruz about 9 years
    Beware that if the id is NOT autoincrement, this will always return 0. In my case the id was a string (UUID) and for this to work I had to add public $incrementing = false; in my model.
  • timgavin
    timgavin over 8 years
    This example didn't work for me in 5.1, but this did: $new = Company::create($input); return redirect('company/'.$new->id);
  • Frank Myat Thu
    Frank Myat Thu about 8 years
    @Rafael, if you want to update timestamps using insertGetId, kindly check here
  • Captain Hypertext
    Captain Hypertext over 7 years
    Exactly what I was looking for the other day! Also, insertGetId only works if the id columns is actually called "id".
  • SaidbakR
    SaidbakR about 7 years
    @milz I have MySQL trigger that generate the uuid for a custom field named aid and I have set $incrementing = false; but It does not returned too!
  • Syfer
    Syfer over 6 years
    This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
  • GrumpyCrouton
    GrumpyCrouton over 6 years
    Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
  • mosid
    mosid over 6 years
    This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
  • Jeffz
    Jeffz almost 6 years
    What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
  • Bhavin Thummar
    Bhavin Thummar over 5 years
    @Benubird, I have got my solution according your answer.
  • Damilola Olowookere
    Damilola Olowookere almost 5 years
    @SaidbakR while true, please can you indicate the section of the Laravel doc where you got this very important information?
  • SaidbakR
    SaidbakR almost 5 years
    @DamilolaOlowookere This is what I had found in my application which uses Laravel 5.4.
  • Daantje
    Daantje about 4 years
    Thanks! This I could use in my pipeline. So no worries about race conditions and beautiful code.
  • Alex
    Alex almost 4 years
    two concurrent users adding the to the company model at the same time. this isn't reliable as the 1st post might get the id of the 2nd if the timing is right. the accepted answer is reliable.
  • Priyanka Patel
    Priyanka Patel almost 4 years
    @Alex kindly check, this is working and the best solution to get last inserted id from records.
  • Alex
    Alex almost 4 years
    the updated solution is fine, however it requires more code than the accepted answer. Simply doing $user->id is enough after creating to get the inserted id.
  • Stefan Pintilie
    Stefan Pintilie over 3 years
    And if you use a specific database connection DB::connection("conn_name")->getPdo()->lastInsertId()
  • Charles Wood
    Charles Wood over 3 years
    And of course, as mentioned in other comments, don't forget that using insert will ignore events and $fillable, so take that into consideration!
  • Khalilullah
    Khalilullah over 3 years
    Beware of using this code as there is no validation here. You should not store any information without validation.
  • Simo
    Simo about 3 years
    didn't know about this lastInsertId(). thanks man