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';
$data->save();
$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. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close