How to get Last Inserted ID in Laravel
Today, we will learn How to get the Last Inserted ID in Laravel. In this tutorial, we learn how to get the last inserted ID in Laravel for example. we get the last inserted ID using insertGetId in the Laravel application. so, we have some example ways to get the last inserted ID in Laravel. We use lastInsertId, insertGetId, create, save method used to get the last ID of the inserted record in the Laravel application.
Using lastInsertId() method
We can get the last inserted ID using Laravel default method lastInsertId() with example.
use DB;
$request->validate([
'firstname' => 'required',
'lastname' => 'required',
'age' => 'required',
]);
Student::create($request->all());
$id = DB::getPdo()->lastInsertId();
echo $id;
Using insertGetId() method
We can get the last inserted ID using Laravel default method insertGetId().
$id = Student::insertGetId([
'firstname' => $request->firstname,
'lastname' => $request->lastname,
'age' => $request->age,
]);
echo $id;
Using create() method
We can get the last ID using of Laravel default create() method with Laravel Model. create() method also returns the last insert record’s object and we can get using this object to last inserted ID.
$students = Student::create([
'firstname' => $request->firstname,
'lastname' => $request->lastname,
'age' => $request->age,
]);
echo $students->id;
Using save() method
We can get the last inserted ID using the Laravel default save() method. we use the save() method for inserting data then it can get the last inserted id.
$students = new Student;
$students->firstname = $request->firstname;
$students->lastname = $request->lastname;
$students->age = $request->age;
$students->save();
echo $students->id;
I hope this tutorial is very helpful. if have any other known way to get the last inserted ID in Laravel, please leave a comment. Thanks 🙂