Laravel 10 Get the Last Inserted Id Code Example

Mar 16, 2023 . Admin



Hi dev,

This complete article will teach you how to use Laravel 10 to get the last inserted id. I want to discuss with you how to insert an ID using Laravel 10. So I'll show you how to create a model id in Laravel 10. We'll show an illustration of how to get the record's most recent insertion ID in Laravel 10. Learn how to locate the most recent record ID in Laravel 10 to get started.

In this example, I will give you two ways to get the last inserted id in laravel eloquent. We will use create() and insertGetId() functions to get the last inserted id. so, let's take a look at both examples and work with them.

Example 1:

Let's see the controller code 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...

#Laravel 10