skip to Main Content

Check first all model if it can be saved or not.Then save.

i tried to saved data from query. i have 3 query :

$message_header->save();

$save_receive_info->save_receive_info_id = $message_header->id;
$information_receive->save();

$information_chargeline->save_receive_info_details_id = $information_receive->id;
$maklumat_chargeline->save();

so, based on this query, first it saves $message_header, then if save_receive_info, but if receive_info has an error when saving, what can I do?

I mean, I want to check whether all queries are executable or not then save. I have a problem with this because other queries are stored based on other id

please help. and sorry for my broken english.

2

Answers


  1. You cannot check whether the queries are executable prior to the execution but You can achieve something similar with DB Transactions.

    So, if you can use DB Transactions, it will execute all the queries and if something fails, it will undo all the previous queries that you have done.

    use IlluminateSupportFacadesDB;
    
    try {
        DB::beginTransaction();
    
        $message_header->save();
    
        $save_receive_info->save_receive_info_id = $message_header->id;
        $information_receive->save();
    
        $information_chargeline->save_receive_info_details_id = $information_receive->id;
        $maklumat_chargeline->save();
    
        DB::commit();
        
    } catch (Throwable $th) {
        DB::rollBack();
    }
    
    Login or Signup to reply.
  2. You can use try and catch block with DB transactions.

    use IlluminateSupportFacadesDB;
    
    
    DB::beginTransaction();
    try {
        // your code logic before save
    
        $message_header->save();
    
        $save_receive_info->save_receive_info_id = $message_header->id;
        $information_receive->save();
    
        $information_chargeline->save_receive_info_details_id = $information_receive->id;
        $maklumat_chargeline->save();
    
        DB::commit();
        // all good
    } catch (Exception $e) {
        DB::rollback();
        // something went wrong
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search