3

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?

peterh
  • 1
  • 15
  • 76
  • 99
Christian
  • 465
  • 6
  • 21
  • 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

7 Answers7

13

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);
Mahdi Younesi
  • 5,930
  • 1
  • 19
  • 47
0
>>> $data = DB::select('SELECT id FROM transferencia ORDER BY id DESC LIMIT 1');

NVM

Christian
  • 465
  • 6
  • 21
0

You can use LAST_INSERT_ID() function. Try this:

SELECT LAST_INSERT_ID() INTO yourTableName;
Rashed
  • 2,231
  • 9
  • 24
0

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

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

You can use the following code:

$data['password']= md5($request->password);
    
   $customer_id= DB::table('customer')
            ->insertGetId($data);
    echo $customer_id;
Nazmul Haque
  • 457
  • 5
  • 11
-1

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,284
  • 7
  • 12
-1

This can be the best answer:

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

And use $trans->id.

horse
  • 679
  • 4
  • 10
  • 30