How to get the last Inserted id in Laravel?

Here, I will give you a simple example of how to get the last inserted id in Laravel. you can simply get laravel to get the last inserted record id with the below example.

When you create a database, you many a time use the primary key column using the AUTO_INCREMENT attribute which means when you insert a new record into the table then the value of the primary key column will be auto-increment with the unique integer.

Whenever you perform an INSERT or UPDATE on the database table with an AUTO_INCREMENT column then you get the last insert id of the last insert or update query.

In PHP, you use mysqli_insert_id to get the last inserted record id.

In laravel, when you go with DB query builder then you can use inserted() that will insert a record and then return the last inserted record id.

Example 1 :

public function getLastInsertedId()
{
   $id = DB::table('users')->insertGetId([
             'email' => 'thetechstuffs@thetechstuffs.com', 
             'name' => 'TheTechStuffs'
   ]);
   print_r($id); //last inserted id
}

Example 2 :

public function getLastInsertedId()
{
     $user = User::create([
             'email' => 'thetechstuffs@thetechstuffs.com', 
             'name' => 'TheTechStuffs'
     ]);
     print_r($user->id);//last inserted id
}

Thank you for following us and please drop a comment if it’s solved your problem and you learn something new. Thank you and have a great day ahead.

You May Also Like

About the Author: Sumanta Kabiraj

Leave a Reply

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