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 Laravel CRUD with Search, Image and Pagination

Laravel 10 CRUD Example Tutorial with Search, Image and Pagination

March 12, 2023July 3, 2024

This article will cover the implementation of CRUD operations along with Search, Image uploading, and Pagination in Laravel. In addition to CRUD operations, we will also cover form validation, unique validation, Flash messages, and viewing uploaded images. It is crucial to learn all aspects of CRUD and beyond, including uploading…

Read More
Php How to Concat Two Columns in Laravel Eloquent Query With Search

How to Concat Two Columns in Laravel Eloquent Query With Search ?

June 22, 2022June 22, 2022

In this article we will learn to use aggregate function concat in laravel eloquent with search and query builder. Concat is used to join two columns and in laravel eloquent there is no method for concat but we can use DB builder to use native MySQL Methods. In MySQL or…

Read More
Php Laravel encrypt and decrypt strings

How to encrypt and decrypt string in laravel 8 ?

January 26, 2022January 26, 2022

Laravel provides inbuilt library to encrypt and decrypt the strings. Laravel usage OpenSSL to provide AES-256 encryption which creates long encrypted string. Encryption and decryption is a technique to hide the useful some information in a form which is not readable. In this tutorial i will show you to encrypt…

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

  • June 2025
  • 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

  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • 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
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version