When you design database, you often use primary key column using the AUTO_INCREMENT attribute that means when you insert new record into the table then value of primary key column will be autoincrement with unique integer.
Whenever you perform an INSERT or UPDATE on database table with an AUTO_INCREMENT column then you get the last insert id of last insert or update query.
In PHP, you use mysqli_insert_id
to get last inserted record id.
In laravel, when you go with DB query builder then you can use insertGetId()
that will insert a record and then return last inserted record id.
- public function getLastInsertedId()
- {
- $id = DB::table('users')->insertGetId(
- ['email' => 'ajay.agrahari09@gmail.com', 'name' => 'Ajay Gupta']
- );
- print_r($id);
- }
If you are inserting a record using Laravel Eloquent then you don't need to use insertGetId()
function to get last inserted id. You can simply use create
method to insert a new record into. The inserted model instance will be returned to you from the method.
- public function getLastInsertedId()
- {
- $user = User::create(['name'=>'Ajay Gupta','email'=>'ajay.agrahari09@gmail.com']);
- print_r($user->id);
- }