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

Time:10-31

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.

CodePudding user response:

You can use try and catch block with DB transactions.

use Illuminate\Support\Facades\DB;


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
}

CodePudding user response:

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 Illuminate\Support\Facades\DB;

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();
}
  • Related