Categories
Laravel

How to get last inserted id in Laravel

In this post, I would like to show the different ways to get last inserted ID from the database table when working with Laravel PHP Framework. In the core PHP, we will get last inserted ID with mysqli_insert_id() or PDO::lastInsertId() methods, but in Laravel framework you don’t need have to use those methods.

In the Laravel framework, we can interact with the database using query builder and Eloquent ORM, Here in this post I will show you getting last inserted ID in both approaches.

Laravel’s Query builder

While working with Query builder you can use insertGetId() method, that will insert a record and then return last inserted record id as a response.

Laravel’s Eloquent ORM

While working with Eloquent ORM, we can use create() method to insert data into the database table and it will return the inserted model instance, form that instance object we can grab the last inserted ID

By Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

Leave a Reply

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