ItSolutionStuff.com

How to Get Last Inserted Id in Laravel?

By Hardik Savani • April 16, 2024
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

šŸ“ŗ Subscribe on YouTube

We Are Recommending You

ā˜…

How to Select Specific Columns in Laravel Eloquent Model?

Read Now →
ā˜…

Laravel Eloquent whereRelation() Condition Example

Read Now →
ā˜…

Laravel Eloquent Group By Year with Sum Example

Read Now →
ā˜…

Laravel Eloquent When Condition Example

Read Now →
ā˜…

Laravel Copy Record using Eloquent Replicate Example

Read Now →
ā˜…

Laravel Eloquent Sum Multiple Columns Example

Read Now →
ā˜…

Laravel Eloquent withSum() and withCount() Example

Read Now →
ā˜…

Laravel Eloquent updateOrCreate Example

Read Now →
ā˜…

Delete All Records from Table in Laravel Eloquent

Read Now →
ā˜…

How to Get Last Record from Database in Laravel?

Read Now →
ā˜…

Laravel Eloquent Group By with Multiple Columns Example

Read Now →
ā˜…

How to Get Last Executed Query in Laravel?

Read Now →
ā˜…

Laravel Join with Subquery in Query Builder Example

Read Now →
ā˜…

How to Get Query Log in Laravel Eloquent?

Read Now →