Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last id inserted on a database in Laravel?

I am trying to get the last id of my table, I want this to know what is the next number of my counter and to show it to the user, I've tried with the last() method but I got this:

>>> $trans = Transferencia::last()
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::last()'

Is there other way to know this?

like image 624
Christian Avatar asked Sep 12 '25 01:09

Christian


1 Answers

4 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();

Using create() method:

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

Using save() method:

$data = new User;
$data->name = 'Test';
$data->save();
like image 159
Mahdi Younesi Avatar answered Sep 14 '25 16:09

Mahdi Younesi