i have code for saving user and code for sending mail, but i want to rollback if there is an error with saving or sending mail, this is my code looks like :
\DB::beginTransaction();
try{
$user->save();
//role
$user->attachRole($role);
//send email
\DB::commit();
Mail::to($user->email)->send(new ActivationCode($user));
return response()->json([
'status' => 'success',
'message' => 'Berhasil mendaftar, cek email anda untuk mendapatkan kode aktivasi'
], 201);
}catch(\Exception $e){
\DB::rollback();
return response()->json([
'status' => 'fail',
'message' => 'Terjadi kesalahan, harap periksa kembali form pendaftaran'
], 400);
}
the mail code was intentionally made an error.
the problem: the catch is reached but the data still inserted into the database
You must be firstly send mail, then commit changes.
\DB::beginTransaction();
try{
$user->save();
//role
$user->attachRole($role);
//send email
Mail::to($user->email)->send(new ActivationCode($user));
\DB::commit();
return response()->json([
'status' => 'success',
'message' => 'Berhasil mendaftar, cek email anda untuk mendapatkan kode aktivasi'
], 201);
}catch(\Exception $e){
\DB::rollback();
return response()->json([
'status' => 'fail',
'message' => 'Terjadi kesalahan, harap periksa kembali form pendaftaran'
], 400);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments