Laravel is a strong php based framework today. Its very important to main transactions when you are working with database in your application. If you don't maintain transaction level then you have high probability to loose your data sometimes. So its nothing more to do to handle this situation. Below is a small example how to do this:
DB::transaction(function() use($p1, $p2) {
$data = array(
"value_1" => "Value 1",
"value_2" => "Value 2"
);
$insert_id = DB::table('table_name')->insertGetId($data);
if($insert_id) {
throw new Exception("Error");
}
$data = array(
"value_1" => "Value 1",
"value_2" => "Value 2"
);
$insert_id = DB::table('table_name_2')->insertGetId($data);
if($insert_id) {
throw new Exception("Error");
}
});
So, if any error occurs or exception thrown by us manually all transaction will be roll back automatically. So all 2 entries will be persist on database together or nothing will be on database.
DB::transaction(function() use($p1, $p2) {
$data = array(
"value_1" => "Value 1",
"value_2" => "Value 2"
);
$insert_id = DB::table('table_name')->insertGetId($data);
if($insert_id) {
throw new Exception("Error");
}
$data = array(
"value_1" => "Value 1",
"value_2" => "Value 2"
);
$insert_id = DB::table('table_name_2')->insertGetId($data);
if($insert_id) {
throw new Exception("Error");
}
});
So, if any error occurs or exception thrown by us manually all transaction will be roll back automatically. So all 2 entries will be persist on database together or nothing will be on database.
No comments:
Post a Comment