24

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?

Community
  • 1
  • 1
Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
  • 1
    Possible duplicate of [Laravel, get last insert id using Eloquent](http://stackoverflow.com/questions/21084833/laravel-get-last-insert-id-using-eloquent) – Luís Cruz Oct 27 '15 at 14:22
  • If `If the table has an auto-incrementing id` Try this : https://stackoverflow.com/a/46482971/2815635 – Niklesh Raut Sep 29 '17 at 06:37

11 Answers11

50

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);
Terrymight
  • 69
  • 7
Edgar Orozco
  • 2,722
  • 29
  • 33
  • 3
    It's worth noting that the doc is misleading because the first method shown is `->save();` and it doesnt, IMO, do enough to explain that `save()` returns a boolean while *only* Insert, update, and delete return the instance. Especially since in says "After **saving** or creating" – Wesley Smith Dec 09 '16 at 11:06
22

**** For Laravel ****

$user = new User();

$user->name = 'John';

$user->save();

//Getting Last inserted id

$insertedId = $user->id;
Majbah Habib
  • 8,058
  • 3
  • 36
  • 38
6

You could wrap your data in the insertGetId() method like this

$id = DB::table('table')->insertGetId( $data );

In this case the array $data would look something like this

$data = [ 'field' => 'data' , 'field' => 'data' ];

and if you’re using the DB façade you could just append the lastInsertID() method to your query.

$lastInsertedID = DB::table('table')->insert( $data )->lastInsertId();
Pankaj katiyar
  • 464
  • 10
  • 26
3
$lastId = User::create($loginuserdata)->id;
user2339271
  • 96
  • 1
  • 2
2

As others said bfore me you may retrieve id by using

$model->id;

but only if you are using standard naming convention for eloquent. If you want to use other name for primaryKey column, eg:

class Users extends Model{
    $primaryKey = 'userid';
}

you may retrieve last inserted id by calling

$model->userid;

It is described in: https://laravel.com/docs/master/eloquent#eloquent-model-conventions where one can find:

Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention.

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.

Krzysiek Grzembski
  • 960
  • 10
  • 20
  • Dear @Krzysiek Grzembski I need it in my controller.I changed it in the model as you written it in the model.But now $model->userid; is where accessible.I need it in my controller.Please guide... – Raham Mar 10 '16 at 11:59
  • @Raham Please see my updated answear. It is hard to tell what is your problem without any piece of code. – Krzysiek Grzembski Mar 21 '16 at 08:40
  • actually I solved my problem.My problem was that how can I retrieve the last inserted one from table.Now I looked up for your answer that how you return the last inserted one.where you defined $model... – Raham Mar 22 '16 at 11:38
  • The problem is the trigger generated keys – SaidbakR Apr 08 '17 at 13:50
2

You may do it as,

public function store(Request $request,ModelName $obj)
{
        $lastInsertedId = $obj->create($request->all())->id;

}

Hope this will help you.

Raham
  • 4,781
  • 3
  • 24
  • 27
2

This is an eloquent model:

$user = new Reports();        
$user->email= 'david@example.com';  
$user->save();
$lastInsertId = $user->id;

A solution using Query Builder:

 $lastInsertId = DB::table('reports')->insertGetId(['email' => 'david@example.com']);
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
2

This is my try:

$model_ins = Model::orderBy('id', 'desc')->take(1)->first();

And use $model_ins->id.

horse
  • 707
  • 4
  • 11
  • 30
1
$user = (new user)->create($request->all()) ;

        \Session::flash('message', 'Thanks , Your record No (' .$user->id . ') has been Successfully added');

This is my solution. I return the inserted object and get its ID or any other property.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
mercury
  • 2,390
  • 3
  • 30
  • 39
1

This code works with Laravel 5.3:

$upstatus = User::create($status);
return response()->json($upstatus);

User pages/site I was call data.id

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
MD Ashik
  • 9,117
  • 10
  • 52
  • 59
1

This is an easier way that works on all of the ways that you inserted:

DB::getPdo()->lastInsertId()
Mohsen
  • 4,049
  • 1
  • 31
  • 31