How to Get Last Inserted Id in Laravel 9 Step by Step with Example[Full Tutorial]

How to Get Last Inserted Id in Laravel 9 Step by Step with Example
[Full Tutorial]

Author: Syed Arshad Sultan

Get Last Inserted Id in Laravel 9 – In this tutorial we will discuss how to get last Inserted Id in Laravel 9 with code examples. I assume users already understand Laravel 9 basics like creating the new Laravel Project, database configuration, creating models, controllers and migrations etc.

In this tutorial, I will give you two ways to get last inserted id in Laravel 9 Eloquent. We will use create() and insertGetId() function for getting the last inserted id.  

Example 01:

Let’s see the controller code as below:

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\Product;
    
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $create = Product::create([
                            'name' => 'Mac Pro Laptop',
                            'Details' => 'Mac Pro Laptop',
                            'price' => '$500'
                        ]);
  
        $lastInsertID = $create->id;
          
        dd($lastInsertID);
    }
}

Example 02:

Let’s see the controller code as below:

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use DB;
    
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $lastInsertID = DB::table('products')->insertGetId([
                           'name' => 'Mac Pro Laptop',
                            'Details' => 'Mac Pro Laptop',
                            'price' => '$500'
                        ]);
  
        dd($lastInsertID);
    }
}

Contact:

Any Kind Of Help Or Needs So Contact Me:
Facebook Group: [ https://www.facebook.com/Tutorials-Ocean-185506455425271/ ]
YouTube: https://www.youtube.com/c/TutorialsOcean

Leave a Reply

Your email address will not be published. Required fields are marked *