Fan Fan - 24 days ago 7
MySQL Question

How to get last increment in laravel orm?

As the title said ,
If I had a

vendor
model , how to get the last increment in laravel orm ?


I already find the answer, but can`t trans it to laravel orm way.
Any idea?

case 1:

SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'table_name'
AND table_schema = DATABASE( ) ;


case 2:

SHOW TABLE STATUS LIKE 'table_name'

Answer

It is unclear whether you want to retrieve the last inserted id right after the insert or at any given time so I will answer the latter as it is the least straight-forward.

As you write yourself, the last inserted id is not stored with the table itself but rather the table information_schema.tables which is why you cannot use the model to retrieve this information. You can however use the query builder in Laravel to do this.

$last_insert_id = DB::table('information_schema.tables')
          ->where('table_name', $table_name)
          ->whereRaw('table_schema = DATABASE()')
          ->select('AUTO_INCREMENT')->first();