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

  1. Method insertGetId()
  2. Method save()
  3. Method create()
  4. Method lastInsertId()

In any controller, you can use these 4 methods to get the last inserted ID. For testing purposet, let’s register a route:

routes/web.php
<?php

Route::get('test', 'UserController@create');

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()

UserController.php
<?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()

UserController.php
<?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()

UserController.php
<?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()

UserController.php
<?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. ?

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.