Get the Latest Inserted ID in Laravel

Laravel is a popular PHP framework known for its simplicity and elegance. It provides various features to help developers in their day-to-day work, including a simple and effective way to get the latest inserted ID in a database table.

After inserting data into the table, we need to retrieve that row’s id for upcoming tasks like sending a JSON response or inserting more data to other tables which is related to the inserted row.

Here are several ways to get the ID depending on which method you use to insert data:

Using Eloquent Model

Laravel’s Eloquent model provides a simple way to insert data into the database and retrieve the latest inserted ID. The create() method of the model inserts data into the database and returns the instance of the model with the latest inserted ID.

The save() method can be used the same.

//use create()
$product = Product::create([
    'name' => 'Smasung Galaxy S23',
    'price' => '1000.00',
]);
$id = $product->id;

//
$order = Order::create(['document' => 'Invoice/2022/12']);
$id = $order->value('id');

//use save()
$data = new Invoice;
$data->document = 'Invoice/2020/07';
$data->save();
$id = $data->id;

Using Query Builder

Laravel’s Query Builder provides a simple way to insert data into the database and retrieve the latest inserted ID. The insertGetId() method of the Query Builder inserts data into the database and returns the latest inserted ID.

$id = DB::table('invoices')->insertGetId([
    'document' => 'Invoice/2020/07'
]);

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close