2

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?

Mahdi Younesi
  • 6,889
  • 2
  • 20
  • 51
Christian
  • 481
  • 1
  • 7
  • 24
  • If `ID` is AUTO_INCREMENT, there is no reliable way to know what will be the next one. – Paul Spiegel Mar 10 '18 at 18:20
  • Maybe running `select max(id) from table` get the result. – ako Mar 10 '18 at 18:36
  • Possible duplicate of [Get current AUTO\_INCREMENT value for any table](https://stackoverflow.com/questions/15821532/get-current-auto-increment-value-for-any-table) – sorak Mar 11 '18 at 07:33
  • AUTO_INCREMENT **is not a counter** and there is **no way** to know the next value before insert. You just **shouldn't** show to the user anything like this. – Your Common Sense Sep 15 '22 at 08:08

7 Answers7

15

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();
Mahdi Younesi
  • 6,889
  • 2
  • 20
  • 51
-1
>>> $data = DB::select('SELECT id FROM transferencia ORDER BY id DESC LIMIT 1');

NVM

Christian
  • 481
  • 1
  • 7
  • 24
-1

You can use LAST_INSERT_ID() function. Try this:

SELECT LAST_INSERT_ID() INTO yourTableName;
Rashed
  • 2,349
  • 11
  • 26
-1

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

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
Kashif Saleem
  • 132
  • 2
  • 12
-1

You can use the following code:

$data['password']= md5($request->password);
    
   $customer_id= DB::table('customer')
            ->insertGetId($data);
    echo $customer_id;
Nazmul Haque
  • 720
  • 8
  • 13
-2

As I get you right, you want to know which id will be on next insert. If there is AUTO_INCREMENT primary key in table, you can get next value of that key using query:

SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = "TABLE_NAME"

But it's not recommended to show user his ID before inserting, because it can be changed from other user's session.

Taron Saribekyan
  • 1,360
  • 7
  • 13
-2

This can be the best answer:

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

And use $trans->id.

horse
  • 707
  • 4
  • 11
  • 30