Laravel 4 - Return the id of the current insert

Stefan Bogdanescu

Founder & Senior Architect · 2026-06-29

Laravel Company

Laravel Query Builder: How to Return the ID of a Just-Inserted Row

As developers working with relational databases through an ORM like Laravel, one of the most common tasks is inserting new records and immediately needing the primary key (ID) generated by the database upon insertion. When using the raw insert() method on the Query Builder, this process can sometimes be confusing regarding what exactly is returned.

If you are working with a scenario similar to the code snippet provided, where you perform an insert operation and need that newly created ID back in the same function call, understanding the underlying behavior of the database driver is crucial.

Let's dive into your specific problem and explore the correct, robust way to retrieve the ID of the row just inserted.

The Pitfall of insert()

In your provided code:

$results = DB::table('pm_conversations')->insert(
    array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);

return $results;

When you use the standard insert() method on a query builder instance, it primarily returns the number of rows affected by the insertion, not the actual IDs of the inserted records. This is because the raw execution often doesn't return the specific row identifiers directly in this context.

To solve this, we need to leverage the underlying database capabilities that Laravel exposes through its facade methods.

The Solution: Using insertGetId()

The correct approach when inserting data using the Query Builder is to use the insertGetId() method immediately following the insertion call. This method specifically queries the database for the ID of the last inserted row, making it the perfect tool for this requirement.

Here is how you can refactor your function to reliably return the newly created conversation ID:

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

public static function createConversation( $toUserId )
{
    $now = date('Y-m-d H:i:s');
    $currentId = Auth::user()->id; // Assuming Auth is correctly set up

    // 1. Perform the insertion and capture the result (which is usually the row count)
    $insertedRows = DB::table('pm_conversations')->insert(
        array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
    );

    // 2. Use insertGetId() to retrieve the ID of the last inserted row
    $newConversationId = DB::table('pm_conversations')
                        ->insertGetId(); // This retrieves the ID of the most recently inserted row

    return $newConversationId;
}

Explanation of Best Practices

The key difference here is introducing a second query: DB::table('pm_conversations')->insertGetId().

  1. insert(): Executes the bulk insert operation and tells you how many rows were affected (e.g., 1).
  2. insertGetId(): Immediately after the insertion, this method leverages the database's auto-increment mechanism (like MySQL's LAST_INSERT_ID()) to fetch the primary key value generated for that new row.

This pattern ensures that you are correctly interacting with the underlying data persistence layer. When building complex data interactions in Laravel, understanding these specific facade methods is fundamental to writing efficient and correct database operations—a core principle emphasized by the documentation at laravelcompany.com.

Summary and Conclusion

In summary, when using the Laravel Query Builder's insert() method and needing the ID of the newly created record, do not rely solely on the return value of insert(). Instead, chain a subsequent call to insertGetId() on the same table to retrieve the auto-generated primary key. This provides a reliable and idempotent way to handle data creation workflows.

By mastering these specific database interaction patterns, you move beyond simple CRUD operations and start writing code that is robust, predictable, and highly efficient. Keep exploring the powerful features available in Laravel, as they simplify complex backend logic tremendously.