Get latest inserted Id in Laravel

After inserting data to table, we need to retrieve that row’s id for upcoming tasks like sending a JSON response or inserting more data to other tables which is related to the inserted row.

Here are several ways to get the ID depends on which method you use to insert data:

$data = new Invoice;
$data->document = 'Invoice/2020/07';
$id = $data->id;
$id = DB::table('invoices')->insertGetId([
    'document' => 'Invoice/2020/07'
$order = Order::create(['document' => 'Invoice/2020/07']);
$id = $order->value('id');

Leave a Comment

Your email address will not be published.