How to recover the ID of the last record inserted in the bank?

Asked

Viewed 8,261 times

-1

How do I recover the id of the last record made in a table in the database?

I’m using Laravel. Before using a framework I used LASTINSERT.

  • 1

    Depends on the BD used. What framework / language?

  • Try to improve your question to facilitate the perception of your need. Framework? Which one? Which language?

  • Please specify the framework and language you are using, so we can assist you, remembering most of the frameworks persistence that I know of, at least, already has this function implemanting by default, for example the Hibernate, by persisting an object the framework already arrow the ID generated by the database in the object.

  • Inform, language and Database, if Mysql is LAST_INSERT_ID and in each database is a form and in PDO and Mysqli has already implemented it

  • Laravel by default works with sqlite, mysql, postgresql and sqlserver, and the same is already implemented as is the last id inserted and with reply would be Antonio Carlos Ribeiro, Could we improve and disseminate such information since here is growing and very the questions about php ? user7834 improve your question so it stays and does not close it!

3 answers

6

If you use Eloquent, this is done automatically regardless of the database system:

class Post extends Eloquent {

}

$post = Post::create(['title' => 'Laravel']);

echo $post->id;

2

  • thanks Lucas Henrique, helped me a lot.

  • @user7834 If the answer helped solve the problem, give a help and mark as the answer "accept".

2

If you are using PDO in Laravel the correct form is:

$id = DB::connection('mysql')->pdo->lastInsertId();

If the database is not Mysql change this in the above code.

  • So Leo, I’m using the framework Laravel and not the PDO, I’ve used enough PDO and in these cases it was very easy to get lastinsert, will the Laravel have some native way to get the last id of a record?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.