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 ?