How to Get the Latest Inserted Id in Laravel
An inserted id is an automatically-generated number that is assigned to a newly-added row in a database table. This number can be used to reference the row in subsequent queries. In Laravel, after you insert a new record into the database, you may need to get the id of the newly inserted record. For example, if you insert a new user into the user’s table, you may want to get the id of the new user in order to add that user to another table, such as a roles table.
// $data = new Invoice; $data->document = 'Invoice/2020/07'; $data->save(); $id = $data->id; // $saleId = DB::table('sales')->insertGetId([ 'document' => 'Invoice/2020/07' ]); // $order = Order::create(['document' => 'Invoice/2020/07']); $id = $order->value('id');