Hey, you are here because you’re struggling to get ID of a row right after the insert command. Then you are at correct place. This operation works if you have an auto-increment id. So,There are several ways to get the last inserted id. Let I share you some of them with simple examples:

  • Using save() method

If you are inserting by instantiating new object of the your model class, then you can get the id as follows:

$book = new Book;
$book->name = 'Laravel Warrior';
$book->save();
$lastId = $book->id;
  • Using create() method

What if you are inserting by using create method? Here is how you can get the last inserted id:

$book = Book::create(['name'=>'Laravel Warrior']);
$lastId = $book->id;
  • Using insertGetId() method

This is explained in official docs of laravel. Here is how:

$id = DB::table('books')->insertGetId(
    ['name' => 'Laravel warrior']
);
$lastId = $id;
  • And the last, Using lastInsertId() method

In this method you’ll need a Pdo object. Imagine I’ve already inserted the data before. Then here how to retrieve last inserted id:

$lastId = DB::getPdo()->lastInsertId();

I hope this helps you a lot. If you know other ways please share us below in the comment.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *