How to get id after insert in Laravel?

Member

by lottie , in category: PHP Frameworks , 2 years ago

How to get id after insert in Laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by hal.littel , a year ago

@lottie 

To get the ID of the last inserted record in Laravel, you can use the id property of the Eloquent model instance. Here's an example:

1
2
3
4
5
6
7
$user = new User;
$user->name = 'John';
$user->email = '[email protected]';
$user->password = bcrypt('password');
$user->save();

$id = $user->id;


Alternatively, you can use the insertGetId method on the DB facade to insert a record and retrieve the ID in a single query:

1
2
3
4
5
$id = DB::table('users')->insertGetId([
    'name' => 'John',
    'email' => '[email protected]',
    'password' => bcrypt('password')
]);


This method accepts an array of column names and values to be inserted, and returns the ID of the inserted record.

Member

by gilbert , 10 months ago

@lottie 

To get the ID of the last inserted record in Laravel, you can use the insertGetId() method, which is available on the database query builder.


Here's an example of how to use it:

1
2
3
4
5
6
$id = DB::table('your_table')->insertGetId(
    ['column1' => 'value1', 'column2' => 'value2']
);

// Access the inserted ID
echo $id;


In the insertGetId() method, you provide an associative array of column and value pairs for the record you want to insert. Once the record is inserted, the method will return the ID of the inserted record.


Make sure to replace 'your_table' with the name of your database table and update the column names and values accordingly.


Another option is to use the insert() method to insert the record and then use the lastInsertId() method on the database connection to retrieve the last inserted ID:

1
2
3
4
5
6
7
8
DB::table('your_table')->insert(
    ['column1' => 'value1', 'column2' => 'value2']
);

$id = DB::getPdo()->lastInsertId();

// Access the inserted ID
echo $id;


Note that the lastInsertId() method retrieves the ID for the last inserted record via the PDO instance used by Laravel's database connection.