How to Get the Last Inserted Id in Laravel 10?
Hi dev,
You will learn how to use laravel 10 obtain last inserted id from this comprehensive guide. I would want to share with you laravel 10 obtain inserted id. I'm going to demonstrate how to build a model id in Laravel 10 now. In Laravel 10, we'll see an example of how to obtain the record's most recent insertion ID. Let's begin by learning how to locate the most recent record ID in Laravel 10.
In this example, I will give you two ways to get the last inserted id in laravel eloquent. We will use create() and insertGetId() functions to get the last inserted id. so, let's take a look at both examples and work with them.
Example 1:
Let's see the controller code 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' => '[email protected]',
'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' => '[email protected]',
'password' => '123456'
]);
dd($lastInsertID);
}
}
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial