Thursday, 27 September 2018

Laravel Eloquent ORM get last insert id

In Laravel, when using the Eloquent ORM to insert a new record into the database, the inserted model instance will be updated with the auto-incrementing ID from the database. You can directly get the ID from the model instance without additional queries or commands.

How to Get the Last Insert ID with Laravel Eloquent

When you create a new record using Eloquent, Laravel automatically populates the model's ID property with the value of the newly inserted record's primary key. Here's a straightforward example:

$user = new User;
$user->name = "Tom";
$user->phone = "+154483480";
$user->save();

After the save method, use something like
$last_Insert_Id = $user->id;

In this snippet, $user->save() stores the new record in the database. Eloquent then automatically updates the $user object's id property with the ID of the newly inserted record.
 

Why is this feature important?

Obtaining the last inserted ID is crucial in many scenarios, such as redirecting users to a newly created resource, creating relationships between new and existing records, or logging activities. Laravel's Eloquent ORM makes this process seamless and efficient, enhancing the developer's productivity.

Using Custom Query Builder

We can get the last insert ID with the help of the query builder as well.
Here is a below snippet example.

$last_id = DB::table('products')->insertGetId(['id' => 22]);
 

Conclusion

Laravel's Eloquent ORM is a powerful tool that simplifies database interactions in PHP applications. Its ability to effortlessly provide the last inserted ID epitomizes the framework's goal: to simplify complex tasks and code more elegantly. Whether you're a seasoned Laravel developer or new to the framework, mastering Eloquent will significantly enhance your web development skills.
 

No comments:

Post a Comment

Laravel csrf token mismatch for ajax post request

Error "CSRF Token Mismatch" commonly occurs if tokens do not match in both sessions and sent , and received requests.CSRF token he...