How to get the last inserted ID using Laravel Eloquent?


Eloquent is a new object relational mapper (ORM) that helps to interact with database. With Eloquent each table has a mapping Model that takes care of all the operations on that table.

Model in laravel represents the table in the database. For example if you have table customers, the model name will be customer, for users it will be user, employees it will be employee. The table name has to be plural and the model name has to be singular. This is a pattern followed, but that does not stop you from using the naming convention of your choice for table name and model name.

Using Laravel Eloquent model you can make use of insertGetId() method to get the inserted ID. Syntax for insertGetId() is −

Model::insertGetId([field=>value, field2=>value…])

The method insertGetId() returns the last inserted id from the table.

Example 1

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $Userid = User::insertGetId([ 'name' => 'Janvi Singh', 'email' => 'janvi@gmail.com', 'password' => 'janvi123' ]); echo $Userid; } }

Output

The output of the above code is −

1001

Example 2

Using DB facade you can also make use of insertGetId() to get the last inserted ID as shown in the example below −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class UserController extends Controller { public function index() { $Userid = DB::table('users')->insertGetId([ 'name' => 'Akansha Singh', 'email' => 'akansha@gmail.com', 'password' => 'akansha123' ]); echo $Userid; } }

Output

The output of the above code is

1002

Example 3

Another way to get the last inserted ID from the table is as shown below −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $user = new User(); $user->name = 'Tomas'; $user->email = 'tomas@gmail.com'; $user->password='tomas123'; $user->save(); echo $lastinsertedId = $user->id; } }

The user object is created and save() method is used to insert into users table. To get the last inserted id you can make use of $user->id;

Output

The output of the above code is −

1003

Example 4

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $user = User::create(['name'=>'Seema Singh', 'email'=>'seema@gmail.com', 'password'=>'seema123']); echo $lastUserId = $user->id; } }

In above the create() method is used to insert user details in users table. The user->id returns the last inserted id.

Output

The output of the above code is −

1004

Updated on: 30-Aug-2022

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements