Get the Last Inserted Id Using Laravel Eloquent

Get the Last Inserted Id Using Laravel Eloquent

After save, $data->id should be the last id inserted.

$data->save();
$data->id;

Can be used like this.

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);

For updated laravel version try this

return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);

How to get last inserted id in Laravel?

Use insertGetId()

$id = DB::table('users')-> insertGetId(array(
'email_id' => $email_id,
'name' => $name,
));

How to get last id inserted on a database with eloquent?

5 Ways to Get Last Inserted Id in Laravel :

Using insertGetId() method:

$id = DB::table('users')->insertGetId(
[ 'name' => 'first' ]
);

Using lastInsertId() method:

DB::table('users')->insert([
'name' => 'TestName'
]);
$id = DB::getPdo()->lastInsertId();

Core SQL Query:

$id = DB::select('SELECT id FROM five_point_zero ORDER BY id DESC LIMIT 1');

Using create() method:

$data = User::create(['name'=>'first']);
$data->id; // Get data id

Using save() method:

$data = new User;
$data->name = 'Test';
$data->save();
dd($data->id);

How to get last insert id in Eloquent ORM laravel

Like the docs say: Insert, update, delete

"You may also use the create method to save a new model in a single
line. The inserted model instance will be returned to you from the
method
. However, before doing so, you will need to specify either a
fillable or guarded attribute on the model, as all Eloquent models
protect against mass-assignment.

After saving or creating a new model that uses auto-incrementing IDs,
you may retrieve the ID by accessing the object's id attribute:
"

$insertedId = $user->id;

So in your sample:

$user = User::create($loginuserdata);
$insertedId = $user->id;

then on table2 it is going to be

$input['table2_id'] = $insertedId;
table2::create($input);

Get the last inserted id using laravel

Instead of using

\DB::table('categories')->insert($insert);

Use

\DB::table('categories')->insertGetId($insert);

The method insertGetId will insert the datas and then return the incremented ID of the inserted line.

laravel 8 : insert method get last insert id in eloquent (İnsert Method)

$insert = Product::create($alldata);
$insert->id

Holds the id of the inserted item.

Basically you have the whole collection in your $insert variable, of the item that you inserted.

Laravel: get last Insert id from query builder

Try it once :-

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

how can i get last inserted id in laravel 8 using elequent model

For Laravel

$user = new User();

$user->name = 'Rakesh';

$user->save();

//Getting Last inserted id

$insertedId = $user->id;


Related Topics



Leave a reply



Submit