How to Get the Last Inserted Id in Laravel 10?

Spread the love

Hello Guys,

Discover How to get the Last Inserted ID in Laravel 10: A Comprehensive Guide

In this comprehensive guide, you will learn how to effectively retrieve the last inserted ID in Laravel 10. We will discuss methods for inserting a Laravel 10 ID and demonstrate how to create a model ID in Laravel 10. You’ll also find an example of obtaining the most recent insertion ID in Laravel 10.

We’ll explore two techniques for retrieving the most recently entered ID in Laravel Eloquent. These methods involve using the create() and insertGetId() procedures. Join us as we delve into both scenarios and put them to use.

Get the Last Inserted Id in Laravel 10 Examples:

Example 1:

Explore the Controller Code for Your Review

Also Read: How to DISABLE SPECIFIC DATES in Bootstrap Datetimepicker

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

Example 2:

Exploring Controller Code: A Detailed Dive into Controller Code Examples

Also Read: How to Resize Images Before Upload in LARAVEL 10

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

Discover the best in Laravel blog through our thoughtfully crafted content.

Leave a Comment