Home > Software design >  Laravel create/update
Laravel create/update

Time:12-11

        function ()
                 if ($request->ajax())
                {
                    $data = $request->input()
              $organisationGroup = new OrgrpOrganisationGroup;
           $organisationGroup->ORGRPID = $data['Group_Id'];
           $organisationGroup->ORGRPCode = $data['Group_Code'];
           $organisationGroup->ORGRPName = $data['Group_Name'];
           $organisationGroup->MSCONID = $data['Country'];
           $organisationGroup->MSCSTID =$data['State'];
           $organisationGroup->MSCCYID = $data['City'];
           $organisationGroup->MSCURID =$data['Currency'];
                $organisationGroup->save();

this is my controller i am getting form data from blade php through ajax .if i click the button data pass into ajax and then i will come to controller .for update same button if i make update it will come to same controller function from here its self can i make update ?

CodePudding user response:

I think this code work for create and for update you must say which data you want update for update data use this

function (OrgrpOrganisationGroup organisationGroup) ... ... ... $organisationGroup->save();

CodePudding user response:

If u want to do bolt create/update with only one function, then you have to change it.
Solutions 1: Base on your request have an id or not.
Into your controller:

public function sendData($id = null, Request $request){  
  if($request->ajax()){  
    if(!$id){  
     OrgrpOrganisationGroup::create($request->all());  
    }  
    else{  
     $orgroOrganisation = OrgrpOrganisationGroup::findOrFail($id);  
     OrgrpOrganisationGroup::update($orgroOrganisation, $request->all());  
    }  
  }  
 }  

And your route:

Route::post('sendData/{id?}',[\App\Http\Controllers\YourController::class,'sendData']);  

Solutions 2:
Your request must be contain id, then your back-end will check id.

public function sendData($id, Request $request){  
   if($request->ajax()){  
    $orgroOrganisation = OrgrpOrganisationGroup::findOrFail($id);  
     if(!$orgroOrganisation){  
       OrgrpOrganisationGroup::create($request->all());  
     }  
    else{  
      OrgrpOrganisationGroup::update($orgroOrganisation, $request->all());  
     }  
   }  
}  

And your route:

Route::post('sendData/{id}',[\App\Http\Controllers\YourController::class,'sendData']);
  • Related