Get Last Inserted Id in Laravel

In this blog, we will be going to understand to get the last inserted id in laravel. I will show you two examples with different functions so that whenever you will use them you have two perspectivess to get the last inserted id. 

We will be going to use create() and insertGetId() functions to get the last inserted id. 


Example 1: Get the Last Inserted Id in Laravel Using create()


<?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' => 'Rahul Gupta',

                            'email' => 'rahul@gmail.com',

                            'password' => '123456'

                        ]);

        $lastInsertID = $create->id        

        dd($lastInsertID);

    }

}


Example 2: Get the Last Inserted Id in Laravel Using insertGetId()


<?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' => 'Rahul Gupta',

                            'email' => 'rahul@gmail.com',

                            'password' => '123456'

                        ]);

        dd($lastInsertID);

    }

}


I hope you understood the use of Laravel Eloquent Query Order By Length of Column, if you have any doubt comment below.