Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last insert id in Eloquent ORM laravel

Tags:

I am performing a database operation with "Eloquent ORM in Laravel". I just want to take the last insert id (not the maximum id) in the database.

I searched to get last insert id in laravel Eloquent ORM, I got following link (Laravel, get last insert id using Eloquent) that is refer to get last insert id from following function "$data->save()".

But I need to get

"Model::create($data)";

My Query:

GeneralSettingModel::create($GeneralData);  User::create($loginuserdata); 

How can I retrieve the last inserted id?

like image 225
Deenadhayalan Manoharan Avatar asked Jan 10 '15 07:01

Deenadhayalan Manoharan


People also ask

How do I get the last inserted ID in Laravel ORM?

you can use it and get last ID of inserted record in laravel application. DB::table('users')->insert([ 'name' => 'TestName' ]); $id = DB::getPdo()->lastInsertId();; dd($id); 3) Using create() method. $data = User::create(['name'=>'first']); dd($data->id);

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

What are the difference between Insert () and InsertGetId () in Laravel?

Insert(): This function is simply used to insert a record into the database. It not necessary that ID should be autoincremented. InsertGetId(): This function also inserts a record into the table, but it is used when the ID field is auto-increment.


1 Answers

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); 
like image 183
Edgar Orozco Avatar answered Sep 20 '22 13:09

Edgar Orozco