Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
get last insert id in laravel

How to get last insert id in laravel with example ?

Aman Jain, March 5, 2022February 22, 2024

In this article i will learn you to get last insert id in laravel, In laravel we can execute our queries in two ways first is using the laravel eloquent and other one is DB builder. so in the both pattern we can get the last inserted i in laravel. Whenever we insert a row it return a auto increment id which we can use for further processing or may to send back to client browser.

In laravel eloquent we can easily create a Model and then we can insert the row using this model hence we can take an example of articles table. So for this article we need to create a Model, Suppose We have a Model \App\Models\Article and wanted to use in our controller to insert the data in this table

Here is the simple syntax to get the last insert id in laravel

Syntax to use get last insert id in laravel

$article= new Article();
$article->title="test";
$article->save();

$article->id  -> here is the last insert id
  

we can easily get the last inserted id by calling the auto incremented column name. As we can see here we called id column name to fetch the last inserted id. we can send response as below

return response()->json(array('success' => true, 'last_insert_id' => $article->id), 200);

Also in db query builder we can get the last inserted id as below

\DB::table("articles")->insert(["title"=>"test"]);

\DB::getPdo()->lastInsertId(); // last insert Id

or using method insertGetId

$insertedId=\DB::table("articles")->insertGetId(["title"=>"test"]);

Eloquent example to get the last insert id in laravel

We will use Model article and Article controller to insert the row. After successful inserting the row we will send back the inserted id to the response

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Article;
  
class ArticleController extends Controller
{
     
    public function store(Request $request)
    {
        $article = new Article;
        $article->title = "Test";
        $article->author = "Michel";
        $article->email = "Michel@yopmail.com";
        $article->save();
        
        return response()->json(['success' => true, 'last_insert_id' => $article->id]);
   }
}

Output will be

{'success': true, 'last_insert_id' : 9}

Db Builder example to get the last insert id in laravel

We will use article table and Article controller to insert the row. After successful inserting the row we will send back the inserted id to the response

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Article;
  
class ArticleController extends Controller
{
     
    public function store(Request $request)
    {
         $id = \DB::table('articles')->insertGetId([
            'title' => 'Test',
            'author' => "Michel",
            'email' => "Michel@yopmail.com"
        ]);
         //or

         \DB::table('articles')->insert([
            'title' => 'Test',
            'author' => "Michel",
            'email' => "Michel@yopmail.com"
         ]); 
         $id = \DB::getPdo()->lastInsertId();

        return response()->json(['success' => true, 'last_insert_id' => $id]);
   }
}

Output will be

{'success': true, 'last_insert_id' : 9}

Also Read : How to Use hasOne Relationship in Laravel with Example ?

Related

Php Laravel laravellast insert idphp

Post navigation

Previous post
Next post

Related Posts

Php file_get_contents Post and Get Request with Headers in Laravel

file_get_contents Post and Get Request with Headers in Laravel ?

June 13, 2022June 13, 2022

In this article i will show you to send file_get_contents post and get request with headers in laravel. As we know file_get_contents is php inbuilt core function used to access the local file and remote URLs. File_get_contents is used to read the file in different modes and to send the…

Read More
Php How to add column in laravel migration

How to Add Column in Existing Table Laravel migration ?

February 15, 2022June 30, 2022

Adding column to existing table are easy as creating a new table and adding columns to it. In laravel migration we can add new colum to existing table using the same method we used in create migrations . Major difference between creating new table and updating new table is Schema::create…

Read More
Laravel Laravel Components

Laravel artisan command to generate controllers, Model, Components and Migrations

August 22, 2021October 4, 2022

Laravel is robust framework of php which provides rapid development and security for low and high level projects. It have many features like Laravel Components, Validation, eloquent, migrations, artisnan security etc. Let’s have look artisan commands of laravel artisan. There is a command which gives you list of all available…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version