Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last inserted id in Laravel?

Tags:

php

laravel

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.

like image 772
Bhavin Shah Avatar asked Jun 22 '16 13:06

Bhavin Shah


2 Answers

Use insertGetId()

$id = DB::table('users')-> insertGetId(array(
    'email_id' => $email_id,
    'name' => $name,
));
like image 198
aynber Avatar answered Oct 10 '22 02:10

aynber


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());  
like image 43
Dhairya Lakhera Avatar answered Oct 10 '22 02:10

Dhairya Lakhera