9

Here is my code

 $users = DB::table('users')->insert(array(
     'email_id' => $email_id,
     'name' => $name,
 ));

 $lastInsertedID = $users->lastInsertId();
           
 return $lastInsertedID;

I want to get last inserted id for particular record. I have tried using Eloquent ORM. but it didn't work.

Any help would be grateful.

Thank You.

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Bhavin Shah
  • 2,462
  • 4
  • 22
  • 35
  • 2
    http://stackoverflow.com/questions/21084833/laravel-get-last-insert-id-using-eloquent and http://stackoverflow.com/questions/27873777/how-to-get-last-insert-id-in-eloquent-orm-laravel and http://smileyhappycoder.co.uk/server-side/fetching-last-insert-id-laravel/ – Alive to die - Anant Jun 22 '16 at 13:22

5 Answers5

30

Use insertGetId()

$id = DB::table('users')-> insertGetId(array(
    'email_id' => $email_id,
    'name' => $name,
));
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
aynber
  • 22,380
  • 8
  • 50
  • 63
3

Follow the code to get last inserted id by using ->insert()

$lastInsertedID = DB::table('users')
                     ->insert( array(
                         'email_id' => $email_id,
                         'name' => $name
                         )
                     )
                    ->lastInsertId();
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Majbah Habib
  • 8,058
  • 3
  • 36
  • 38
3

Here are the following methods to get last inserted id

Eloquent

Method 1

$user = new User();
$user->name = "Test";
$user->save();
dd($user->id);

Method 2

$user = User::create(['name' => 'Test']);
dd($user->id);

Query Builder

Method 3

In this method Primary Key must me id. If its other then id for example some_id then this method will throw exception.

$id = DB::table('users')->insertGetId(['name' => 'Test']);
dd($id);

Method 4

This method is usefull if you are using DB Facade and have Custom Primary Key like some_id.

DB::table('users')->insert(['name' => 'Test']);
dd(DB::getPdo()->lastInsertId());  
Dhairya Lakhera
  • 4,445
  • 3
  • 35
  • 62
1

$id = DB::getPdo()->lastInsertId();

0

Do you mean you inserted record id? You can get the following way:

//UserController.php

$user  = new User;
$user->name = $request->name;
$user->email = $request->email;
if($user->save()){
    echo "User's record id is ".$user->id; *//$user->id is your lastest record id*
}
yekyawaung
  • 201
  • 2
  • 7