How to Get the Last Inserted Id Using Laravel Eloquent - TechvBlogs

How to Get the Last Inserted Id Using Laravel Eloquent

In this guide, you will learn how to get the last insert id in Laravel.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

8 months ago

TechvBlogs - Google News

In this article, I'll give you a fast tip on how to find the ID that was most recently inserted in Laravel code. You frequently need to obtain the recently added model ID when working on your Laravel application in order to assign it to another model or process data. This can be done in a variety of ways, depending on whether you're using a model class or Laravel's DB facade.

Let's explore how to obtain the most recently added ID for a model or table in Laravel right away.

1. Using Eloquent Save Method

When you create or update a model in Laravel, you can easily get the ID of the last inserted record by using the save() method.

<?php

$user = new User();
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->save();

$lastInsertId = $user->id;

2. Using Elogquent Create Method

This method is pretty much like the one we talked about before. Instead of using the save() method, here we use the create() method to add a new entry to the model. After we add it, we can easily get the ID of what we just added.

<?php

$user = User::create(['name' => 'John Doe', 'email' => '[email protected]']);
$lastInsertId = $user->id;

3. Using DB Facade

If you want to add a new entry to your model or table using the DB facade in Laravel and get its ID at once, you can use the insertGetId() method. This does both: it adds the entry and gives you back the ID of that entry.

<?php

$lastInsertId = User::insertGetId(['name' => 'John Doe', 'email' => '[email protected]']);

4. Using getPDO() Method

If you want to know the ID of the last added item in a table using Laravel, you can use something called the PDO Object. First, you add the record to the table. Then, you can use the lastInsertId() method on the PDO Object to get that ID.

<?php

$user = DB::table('users')->insert(
    [ 'name' => 'John Doe', 'email' => '[email protected]' ]
); 
$userId = DB::getPdo()->lastInsertId();.

dd($userId);

That's it for now. I hope this little tip helps you. If you've been working with Laravel for a while, you might already know these methods or at least some of them.

Comments (0)

Comment


Note: All Input Fields are required.