Skip to content

Instantly share code, notes, and snippets.

@gentildpinto
Created January 30, 2021 21:20
Show Gist options
  • Save gentildpinto/4b03c03e4d676423c0b67164af418b37 to your computer and use it in GitHub Desktop.
Save gentildpinto/4b03c03e4d676423c0b67164af418b37 to your computer and use it in GitHub Desktop.
A simple code to get the next auto increment id from a table in laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
/**
* @return mixed
*/
private function getNextUserId()
{
$statement = DB::select("SHOW TABLE STATUS LIKE 'users'");
$nextUserId = $statement[0]->Auto_increment;
return $nextUserId;
}
}
@gentildpinto
Copy link
Author

Thank you for your reply @gentildpinto

$nextId  = DB::table('shipments')->max('id') + 1;

This will not be accurate when the latest id gets deleted and this snippet generate the nextId which was already used. (By deleted record).

Yeah, you're right
I forgot that detail

@JasonJensenDev
Copy link

In MySQL 8 and above, the auto_increment value is cached which is why you're seeing the wrong value when executing your query.

To get the up to date auto_increment value, run SET information_schema_stats_expiry = 0; before the query.

@gentildpinto
Copy link
Author

In MySQL 8 and above, the auto_increment value is cached which is why you're seeing the wrong value when executing your query.

To get the up to date auto_increment value, run SET information_schema_stats_expiry = 0; before the query.

Thank's for your hep! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment