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

How to Retrieve the Last Inserted ID Using Laravel Eloquent?

Susan Sarandon
Release: 2024-12-04 05:44:14
Original
678 people have browsed it

How to Retrieve the Last Inserted ID Using Laravel Eloquent?

Retrieving Last Inserted ID via Laravel Eloquent

To insert data and retrieve the last inserted ID in Laravel Eloquent, follow these steps:

1. Insert Data:

$data = new Company;
$data->fill($post);
$data->save();
Copy after login

2. Obtain Last Inserted ID:

After the save operation, access the id attribute of the $data object. This attribute represents the last inserted ID:

$lastInsertId = $data->id;
Copy after login

3. Return ID:

In your controller, return the last inserted ID as a JSON response:

return response()->json(['success' => true, 'last_insert_id' => $lastInsertId], 200);
Copy after login

Example Code:

public function saveDetailsCompany()
{
    $post = Input::all();

    $data = new Company;
    $data->nombre = $post['name'];
    $data->direccion = $post['address'];
    $data->telefono = $post['phone'];
    $data->email = $post['email'];
    $data->giro = $post['type'];
    $data->fecha_registro = date("Y-m-d H:i:s");
    $data->fecha_modificacion = date("Y-m-d H:i:s");

    $data->save();

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

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template