Home >Backend Development >PHP Tutorial >How to Retrieve the Last Inserted ID with Laravel Eloquent?

How to Retrieve the Last Inserted ID with Laravel Eloquent?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 07:36:15617browse

How to Retrieve the Last Inserted ID with Laravel Eloquent?

How to Get the Last Inserted Id Using Laravel Eloquent

In Laravel, the save() method persists the model to the database. Upon successful insertion, the model's id property is automatically populated with the last inserted ID.

Example Code

Consider the following code snippet:

public function saveDetailsCompany()
{
    // ... code to populate the $data model ...

    $data->save();

    return response()->json(['success' => true, 'last_insert_id' => $data->id], 200);
}

In this example, after successfully inserting the data using save(), the $data->id property will contain the last inserted ID. The response()->json() function is then used to return the ID along with a success message.

The above is the detailed content of How to Retrieve the Last Inserted ID with Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn