Get the Last Inserted Id Using Laravel Eloquent

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for Get the Last Inserted Id Using Laravel Eloquent

Get the Last Inserted ID Using Laravel Eloquent: A Simple and Effective Solution 🚀

So you have successfully been able to insert data into a table using Laravel's Eloquent ORM. But now you want to retrieve the last ID that was inserted, and you're not sure how to go about it. Don't worry, we've got you covered! In this blog post, we will discuss a simple and effective solution to get the last inserted ID using Laravel Eloquent.

The Problem 🔍

Here's a code snippet that demonstrates how data is being inserted into a Company table:

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");

    if ($data->save()) {
        return Response::json(array('success' => true), 200);
    }
}

The above code successfully saves the data, but it doesn't return the last inserted ID.

The Solution 💡

To get the last inserted ID using Laravel Eloquent, you can simply call the id property on the saved model. Here's the modified code with the addition of retrieving the last inserted ID:

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");

    if ($data->save()) {
        $lastInsertedId = $data->id;
        return Response::json(array('success' => true, 'lastInsertedId' => $lastInsertedId), 200);
    }
}

In the modified code, we assign the value of $data->id to a variable called $lastInsertedId, which represents the ID of the last inserted record. The code then returns a JSON response with the lastInsertedId included.

Going the Extra Mile: Error Handling 🏃‍♀️

It's always a good practice to handle any potential errors that may occur during the insertion process. Laravel provides a convenient way to handle these errors using the try-catch block. Let's update our code to include error handling:

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");

    try {
        if ($data->save()) {
            $lastInsertedId = $data->id;
            return Response::json(array('success' => true, 'lastInsertedId' => $lastInsertedId), 200);
        }
    } catch (\Exception $e) {
        return Response::json(array('success' => false, 'error' => $e->getMessage()), 500);
    }
}

With the addition of the try-catch block, any exceptions thrown during the save() method call will be caught, and a JSON response with the error message will be returned.

Wrapping Up 🎉

Congratulations! 🎉 You now know how to retrieve the last inserted ID using Laravel Eloquent. Simply access the id property of the saved model, and you're good to go. Don't forget to handle any potential errors for a robust implementation.

If you found this blog post helpful, consider sharing it with your fellow developers who might be facing similar challenges. And if you have any more questions or tips, feel free to leave a comment below. Happy coding! 💻✨

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my