How to Get Last Inserted Id in Laravel 10?
Hey Artisan,
This extensive guide will teach you laravel 10 get last inserted id. I would like to share with you laravel 10 get inserted id. I’m going to show you about laravel 10 get created model id. We will look at an example of how to get last inserted record id in laravel 10. Let's get started with how to get last created 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' => '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 Get Current Full URL in Laravel 10?
- Laravel 10 Many to Many Eloquent Relationship Tutorial
- Laravel 10 Socialite Login with Google Account Example
- How to Generate QR Code in Laravel 10?
- How to Create Custom Error Page in Laravel 10?
- Laravel 10 Ajax CRUD Tutorial Example
- How to Generate Barcode in Laravel 10?
- Laravel 10 Get Current Logged in User Data Example
- Laravel 10 Select2 Ajax Autocomplete Search Example
- Laravel 10 Guzzle Http Request Example
- Laravel 10 Auth with Livewire Jetstream Example
- Laravel 10 Bootstrap Auth Scaffolding Tutorial
- Laravel 10 Generate PDF File using DomPDF Example
- Laravel 10 File Upload Example Tutorial