简体   繁体   中英

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?

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();
dd($data->id);

You can use LAST_INSERT_ID() function. Try this:

SELECT LAST_INSERT_ID() INTO yourTableName;

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

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
>>> $data = DB::select('SELECT id FROM transferencia ORDER BY id DESC LIMIT 1');

NVM

You can use the following code:

$data['password']= md5($request->password);
    
   $customer_id= DB::table('customer')
            ->insertGetId($data);
    echo $customer_id;

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.

This can be the best answer:

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

And use $trans->id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM