How to get last inserted id in laravel PHP Framework?

How to get last inserted id in laravel PHP Framework?

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

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 function getLastInsertedId()
  2. {
  3.     $user = User::create(['name'=>'Ajay Gupta','email'=>'ajay.agrahari09@gmail.com']);
  4.     print_r($user->id);
  5. }

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort serdivan escort sapanca escort karasu escort hendek escort ankara escort
sakarya escort kızlar sakarya escort kaliteli sakarya escort vip sakarya escort elit sakarya escort bayan sakarya escort adresleri.