How to get last inserted id in laravel PHP Framework – onlinecode.org

How to get last inserted id in laravel PHP Framework – onlinecode

In this post we will give you information about How to get last inserted id in laravel PHP Framework – onlinecode. Hear we will give you detail about How to get last inserted id in laravel PHP Framework – onlinecodeAnd how to use it also give you demo for it if it is necessary.

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.



Example:

  1. public functiongetLastInsertedId()
  2. {
  3.     $id= DB::table('users')->insertGetId(
  4.          ['email'=>'ajay.agrahari09@gmail.com','name'=>'Ajay Gupta']
  5.     );
  6.     print_r($id);
  7. }
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.



Example:

  1. public functiongetLastInsertedId()
  2. {
  3.     $user= User::create(['name'=>'Ajay Gupta','email'=>'ajay.agrahari09@gmail.com']);
  4.     print_r($user->id);
  5. }
public function getLastInsertedId()
{
	$user = User::create(['name'=>'Ajay Gupta','email'=>'ajay.agrahari09@gmail.com']);
	print_r($user->id);
}

mysqli_insert_id() function will return zero if table does not have autoincremented column so make sure table must have a column with AUTO_INCREMENT attribute.

Hope this code and post will helped you for implement How to get last inserted id in laravel PHP Framework – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

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

  +  57  =  62

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US