In this article, I am gonna show you 5 different ways to get last inserted record ID in MySQL database with Laravel.
Using insertGetId() method
You can use insertGetId method to get last inserted id when you are using DB class to insert data into the database.
You can use method chaining here. For example
$id = DB::table('users')->insertGetId( [ 'name' => 'first' ] ); dd($id);
Laravel provides DB class to play with the database if you are not familiar with eloquent then you can use formal SQL queries that will work.
Using lastInsertId() method
You can use lastInsertId(). But be careful if you are run this on directly after DB::insert() it will not work.
You need PDO object to run this method. For example
DB::table('users')->insert([ 'name' => 'TestName' ]); $id = DB::getPdo()->lastInsertId();; dd($id);
Core SQL Query
Very simple and easiest very to use SQL Query. Like this:
$data = DB::select('SELECT id FROM five_point_zero ORDER BY id DESC LIMIT 1'); dd$data);
It will give you an array of Id column which was last inserted id.
Using create() method.
Laravel provides a model class or eloquent class feature which is very powerful. Default when you use the eloquent model to insert your data it will give you collection or object of your last inserted record.
From that object, you can fetch id key. For example
$data = User::create(['name'=>'first']); dd$data->id);
Using save() method.
If you are using save method then also it's very easy to get the last ID. Ideally, it's similar to create() method.
The method save() will store your last record into your model class instance. You can get id key from that instance.
$data = new User; $data->name = 'Test'; $data->save(); dd($data->id);