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

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status