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

后端 未结 6 1717
醉酒成梦
醉酒成梦 2021-01-22 03:37

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 =          


        
相关标签:
6条回答
  • 2021-01-22 03:56

    Try this once it worked for me where $mode->save(); was only returning true.

    $mylastid = DB::getPdo()->lastInsertId();
    
    0 讨论(0)
  • 2021-01-22 04:02
    $ObjTable->nane = $name;
    $ObjTable->save();
    echo $ObjTable->id;
    

    this will be display last inserted id.

    0 讨论(0)
  • 2021-01-22 04:07

    In case of you did overwride the name of primary key in the model as in next case:

    protected $primaryKey = 'your_table_id_name';
    

    use:

    $id = $your_variable_save->your_table_id_name
    

    if not:

    $id = $your_variable_save->id
    
    0 讨论(0)
  • 2021-01-22 04:10

    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.

    0 讨论(0)
  • 2021-01-22 04:12

    You can get the last inserted id by the following codes.

    Using Laravel Eloquent

    $order = new Store_order();
    $order->invoice_id = $signed['invoice_id'];
    $order->save();
    
    $lastInsertedId = $order->so_id;     //now getting Last inserted id
    echo $lastInsertedId; 
    

    Provided that $order->so_id means last inserted id of the given object where so_id is the primary key of the table.

    0 讨论(0)
  • 2021-01-22 04:16

    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;
    
    0 讨论(0)
提交回复
热议问题