How to Get Last Inserted Id in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Select Specific Columns in Laravel Eloquent Model?
- Laravel Eloquent whereRelation() Condition Example
- Laravel Eloquent Group By Year with Sum Example
- Laravel Eloquent When Condition Example
- Laravel Copy Record using Eloquent Replicate Example
- Laravel Eloquent Sum Multiple Columns Example
- Laravel Eloquent withSum() and withCount() Example
- Laravel Eloquent updateOrCreate Example
- Delete All Records from Table in Laravel Eloquent
- How to Get Last Record from Database in Laravel?
- Laravel Eloquent Group By with Multiple Columns Example
- How to Get Last Executed Query in Laravel?
- Laravel Join with Subquery in Query Builder Example
- How to Get Query Log in Laravel Eloquent?