How to use mysql_insert_id in Laravel

At this moment the docs are very vague about this, searching “mysql_insert_id” won’t return anything but if you look through the docs you’ll find multiple ways to get that id:

With PDO

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

With insert_get_id() method that works with Fluent or Eloquent objects(will work only if the name of the auto-incrementing column is “id”):

$id = DB::table('users')->insert_get_id(array('name' => 'John Doe'));

With Eloquent’s create() method, which returns the model instance for the newly inserted record, or false if the insert failed.

$user = User::create(array('name' => 'John Doe'));


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s