how to get last inserted id in laravel 8?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Now in this example, i will share with you a very simple example of how to get last inserted id in laravel 8 application. We can do it very simply in laravel 8 to get last inserted record id with simple example.

When we create a new database,we maximum a time use primary key column by using the AUTO_INCREMENT attribute that means when we insert new data into the table then the value of primary key column will be auto-increment with a unique positive integer number.

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

In PHP application, we can use mysqli_insert_id to get last inserted record id.

But in laravel application, when we go with by using DB query builder then we can use insertGetId() function that will insert a record and then also it is return us last inserted record id.

Example 1:

public function getLastInsertedId()
    {
        $id = DB::table('users')->insertGetId(
                ['email' => 'xyz@gmail.com', 'name' => 'Mehul']
        );

        dd($id);
    }

Example 2:

 public function getLastInsertedId()
    {
        $user = User::create(['name'=>'Mehul' , 'email'=>'xyz@gmail.com']);

        dd($user->id);
    }

Read Also : Laravel Collection Sum Column Example

Thanks for read. I hope it help you. For more you can follow us onĀ facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →