Reputation: 501
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?
Upvotes: 4
Views: 18028
Reputation: 7489
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();
Upvotes: 17
Reputation: 868
You can use the following code:
$data['password']= md5($request->password);
$customer_id= DB::table('customer')
->insertGetId($data);
echo $customer_id;
Upvotes: -1
Reputation: 725
This can be the best answer:
$trans = Transferencia::orderBy('id', 'desc')->take(1)->first();
And use $trans->id
.
Upvotes: -3
Reputation: 131
After save, $data->id should be the last inserted.
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
Upvotes: -1
Reputation: 1390
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.
Upvotes: -2
Reputation: 2425
You can use LAST_INSERT_ID() function. Try this:
SELECT LAST_INSERT_ID() INTO yourTableName;
Upvotes: -1
Reputation: 501
>>> $data = DB::select('SELECT id FROM transferencia ORDER BY id DESC LIMIT 1');
NVM
Upvotes: -1