Laravel 5 Ways to Get Last Inserted Id

In this article, I am gonna show you 5 different ways to get last inserted record ID in MySQL database with Laravel.

Last Id Laravel

Using insertGetId() method

You can use insertGetId method to get last inserted id when you are using DB class to insert data into the database.

You can use method chaining here. For example

Laravel provides DB class to play with the database if you are not familiar with eloquent then you can use formal SQL queries that will work.


Using lastInsertId() method

You can use lastInsertId(). But be careful if you are run this on directly after DB::insert() it will not work.

You need PDO object to run this method. For example


Core SQL Query

Very simple and easiest very to use SQL Query. Like this:

It will give you an array of Id column which was last inserted id.


Using create() method.

Laravel provides a model class or eloquent class feature which is very powerful. Default when you use the eloquent model to insert your data it will give you collection or object of your last inserted record.

From that object, you can fetch id key. For example


Using save() method.

If you are using save method then also it’s very easy to get the last ID. Ideally, it’s similar to create() method.

The method save() will store your last record into your model class instance. You can get id key from that instance.

For example

Leave a Reply

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