How to get inserted Records ID / Column Data after inserting data in tables in Laravel

In Laravel, when you plan to insert new record into the database table, you can get the ID or any other column’s value of the inserted record using some different methods.Following are some of the approaches:

1. Use create() Method with Eloquent Model

If you use create() method to insert a record,you can easily get the ID or any other column data from the return model instance.

$user = User::create([
    'name' => 'John Doe',
    'email' => 'johndoe@example.com',
    'password' => bcrypt('password123'),
]);

// Retrieve the inserted ID
$insertedId = $user->id;

2. Use save() Method with Eloquent Model

You can use save() method too.This is used to create a new instance of the model,set its data, and then save it.After saving the records, you can access the ID on model instance.

$user = new User;
$user->name = 'John Doe';
$user->email = 'johndoe@example.com';
$user->password = bcrypt('password123');
$user->save();

// Retrieve the inserted ID
$insertedId = $user->id;

3. Use insertGetId() with Query Builder

You can use query builder’s insertGetId() method to insert a record and get the ID.

$insertedId = DB::table('users')->insertGetId([
    'name' => 'John Doe',
    'email' => 'johndoe@example.com',
    'password' => bcrypt('password123'),
]);

// $insertedId now holds the ID of the inserted record

4. Retrieving Other Column Data After Insertion

$user = User::create([
    'name' => 'John Doe',
    'email' => 'johndoe@example.com',
    'password' => bcrypt('password123'),
]);

// Now retrieve any other data you need
$insertedName = $user->name;
$insertedEmail = $user->email;

Leave a Comment