Tuesday, February 28, 2017

[SOLVED]How to get last inserted id with insert method in laravel

In my laravel project I am inserting multiple records at time with modelname::insert method. Now I want to get last inserted id of it.I read somewhere when you insert multiple records with single insert method and try to get the last_record_id it will gives you the first id of the last inserted query bunch. But my first question is how to get last record id with following code .If I am able to get first id of the bunch .I ll make other ids for other record by my own using incremental variable.
Code to insert multiple record
if(!empty($req->contract_name) && count($req->contract_name)>0)
            {

                for($i=0; $i<count($req->contract_name); $i++)
                {
                    $contract_arr[$i]['client_id'] = $this->id;
                    $contract_arr[$i]['contract_name'] = $req->contract_name[$i];
                    $contract_arr[$i]['contract_code'] = $req->contract_code[$i];
                    $contract_arr[$i]['contract_type'] = $req->contract_type[$i];
                    $contract_arr[$i]['contract_ext_period'] = $req->contract_ext_period[$i];
                    $contract_arr[$i]['contract_email'] = $req->contract_email[$i];
                    $contract_arr[$i]['created_at'] = \Carbon\Carbon::now();
                    $contract_arr[$i]['updated_at'] = \Carbon\Carbon::now();
                    $contract_arr[$i]['created_by'] = Auth::user()->id;
                    $contract_arr[$i]['updated_by'] = Auth::user()->id;
                    if($req->startdate[$i] != ''){
                        $contract_arr[$i]['startdate'] = date('Y-m-d',strtotime($req->startdate[$i]));
                    }
                    if($req->enddate[$i] != ''){
                        $contract_arr[$i]['enddate'] = date('Y-m-d',strtotime($req->enddate[$i]));
                    }
                }   
                if(!empty($contract_arr)){

                    Contract::insert($contract_arr);

                }
            }




via Alfiza malek

Advertisement