How to Get Last Inserted Id in Laravel 9?
This post will give you example of laravel 9 get last inserted id. I explained simply about laravel 9 get inserted id. We will look at example of laravel 9 get created model id. We will use how to get last inserted record id in laravel 9. Let's get started with how to get last created record id in laravel 9.
In this example, I will give you two ways to get last inserted id in laravel eloquent. We will use create() and insertGetId() function for getting last inserted id. so, let's take a look at both examples and work with them.
Example 1:
Let's see controller code as below:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$create = User::create([
'name' => 'Hardik Savani',
'email' => 'hardik@gmail.com',
'password' => '123456'
]);
$lastInsertID = $create->id;
dd($lastInsertID);
}
}
Example 2:
Let's see controller code as below:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$lastInsertID = DB::table('users')->insertGetId([
'name' => 'Hardik Savani',
'email' => 'hardik@gmail.com',
'password' => '123456'
]);
dd($lastInsertID);
}
}
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Merge Multiple PDF Files in Laravel 9?
- Laravel 9 User Roles and Permissions Tutorial
- Laravel 9 CRUD with Image Upload Tutorial
- Laravel 9 Razorpay Payment Gateway Integration Example
- Laravel 9 Inertia JS CRUD with Jetstream & Tailwind CSS
- Laravel 9 Stripe Payment Gateway Integration Tutorial
- Laravel 9 Google Recaptcha V3 Example Tutorial
- Laravel 9 Barcode Generator Example
- Laravel 9 Socialite Login with Google Account Example
- Laravel 9 REST API Authentication using Sanctum Tutorial
- Laravel 9 Send Mail using Gmail SMTP Server