Laravel Get Last Inserted ID
In this article, I am going to share how to get the last inserted ID in Laravel. I will show some ways to get the last inserted ID. Let’s see the methods:
Table of Contents
In any controller, you can use these 4 methods to get the last inserted ID. For testing purposet, let’s register a route:
<?php
Route::get('test', '[email protected]');
Now create a controller named UserController by this command:
php artisan make:controller UserController
Now open the controller from app>>Http>>Controllers
and paste the following code to test any method:
Step 1 : Method insertGetId()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\User;
class UserController extends Controller
{
public function create()
{
$id = DB::table('users')->insertGetId([
'name' => 'Md. Obydullah',
'email' => '[email protected]'
]);
return $id;
}
}
Step 2 : Method save()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\User;
class UserController extends Controller
{
public function create()
{
$user = new User();
$user->name = "Md. Obydullah";
$user->email = "[email protected]";
$user->save();
return $user->id;
}
}
Step 3 : Method create()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\User;
class UserController extends Controller
{
public function create()
{
$input = ['name' => 'Md. Obydullah', 'email' => '[email protected]'];
$user = User::create($input);
return $user->id;
}
}
Step 4 : Method lastInsertId()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\User;
class UserController extends Controller
{
public function create()
{
DB::table('users')->insert([
'name' => 'Md. Obydullah',
'email' => '[email protected]'
]);
$id = DB::getPdo()->lastInsertId();
return $id;
}
}
I hope now you can easily get the last inserted id. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)