Md Obydullah Howdy, I am Md Obydullah. I love to write the article which may help others. It's my passion.

Laravel Get Last Inserted ID

Published on April 29, 2019 1 min read

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' => 'obydul2@test.com'
        ]);

        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 = "obydul@test.com";
        $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' => 'obydul3@test.com'];
        $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' => 'obydul4@test.com'
        ]);
        $id = DB::getPdo()->lastInsertId();

        return $id;
    }
}
I hope now you can easily get the last inserted id. 🙂

You're welcome to suggest any article to write!

Md Obydullah Howdy, I am Md Obydullah. I love to write the article which may help others. It's my passion.

Leave a Reply

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