How to get last inserted id from table in Laravel
In this tutorial, we will explain to you about how to get last inserted id from the table in laravel. Sometimes when we need first table reference ID to insert to another table at that time we have to need last inserted ID of the first table.
If you want to get last inserted ID from the table. laravel provides the Eloquent library method such as save(), create(), insertGetId() and getPdo().
So you can see below steps for laravel get last insert id.
Using The save() Method
1 2 3 4 5 6 7 8 9 10 11 | public function store(Request $request) { $student = new Student([ 'first_name' => $request->get('txtFirstName'), 'last_name'=> $request->get('txtLastName'), 'address'=> $request->get('txtAddress') ]); $student->save(); print_r($student->id); } |
Using The create() Method
1 2 3 4 5 6 7 8 9 10 11 | public function store(Request $request) { $data = array(); $data['first_name'] = $request->get('txtFirstName'); $data['last_name'] = $request->get('txtLastName'); $data['address'] = $request->get('txtAddress'); $student = Student::create($data); print_r($student->id); } |
Using The insertGetId() Method
1 2 3 4 5 6 7 8 9 10 | public function store(Request $request) { $data = array(); $data['first_name'] = $request->get('txtFirstName'); $data['last_name'] = $request->get('txtLastName'); $data['address'] = $request->get('txtAddress'); $id = DB::table('students')->insertGetId($data); print_r($id); } |
Using The getPdo() Method
1 2 3 4 5 6 7 8 9 10 11 | public function store(Request $request) { $data = array(); $data['first_name'] = $request->get('txtFirstName'); $data['last_name'] = $request->get('txtLastName'); $data['address'] = $request->get('txtAddress'); DB::table('students')->insert($data); $id = DB::getPDO()->lastInsertId(); print_r($id); } |
Please follow and like us: