How to Get Last Inserted Id in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Are you looking for example of laravel get last inserted id. This article will give you simple example of laravel get inserted id. I’m going to show you about laravel get created model id. This tutorial will give you simple example of how to get last inserted record id in laravel.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions as well.

If you are working with DB::table() then you have to use insertGetId() for insert data into database. this function always return inserted record id(primary key).it is very simple way to get id, in following example you can see and understand more:

Example 1:

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

Tags :
Shares