Post Details

How to Get Last Inserted Id in Laravel 10?
13 Dec

How to Get Last Inserted Id in Laravel 10?

Hi Guys,

This extensive guide will teach you how to get the last inserted ID Laravel 10. I would like to share with you the 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 the last inserted record ID in Laravel 10. Let's get started with how to get the 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:

<?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' => 'test',
                            'email' => 'test@gmail.com',
                            'password' => '123456'
                        ]);
  
        $lastInsertID = $create->id;
          
        dd($lastInsertID);
    }
}

Example 2:

<?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' => 'test',
                            'email' => 'test@gmail.com',
                            'password' => '123456'
                        ]);
  
        dd($lastInsertID);
    }
}

 

0 Comments

Leave a Comment