Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last inserted id through save() method in laravel

Tags:

php

laravel

I know to get the last id I can use insertGetId() but I want to know how can I get the last inserted id through save() method.

order = new Store_order;
    $order->invoice_id = $signed['invoice_id'];
    $invoice = $order->save()['so_id'];

I used this but it returns null value

like image 315
Alen Avatar asked Jan 29 '26 02:01

Alen


2 Answers

After $order->save(), $order->so_id should be the last id inserted. Your code should be as below.

$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$order->save();
$invoice = $order->so_id;
like image 82
TIGER Avatar answered Jan 31 '26 17:01

TIGER


You can get it by like below :

$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$invoice = $order->save();
echo $invoice->so_id;

in this case you no need to store in one variable and then access it, You can get the inserted records by calling the model object itself :

    $order = new Store_order;
    $order->invoice_id = $signed['invoice_id'];
    $order->save();
    // echo $order; => will return entire stored last record.
    echo $order->so_id;

Make sure so_id is autoincrement.

like image 23
Muthu17 Avatar answered Jan 31 '26 17:01

Muthu17



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!