In my Laravel application, I have two models that I'm saving, first, an Application
and then a modelable class model, however, if one of them fails to save for whatever reason then I want to prevent saving both as they both rely on one another.
I've tried wrapping everything in a try/catch
, the Application
model saves, but when my modelable
fails it's not prevent the Application
from saving.
What am I missing?
My code is:
try {
// generate metadata about application
$threadUUID = (string) Str::uuid();
$submittedAt = Carbon::now();
// create application instance
$application = Application::create([
'user_id' => $affiliate->user_id,
'company_id' => $affiliate->company_id,
'country_id' => $affiliate->affiliate_product->country->id,
'product_id' => $affiliate->affiliate_product->product->id,
'serve_method_id' => $affiliate->affiliate_product->serve_method->id,
'application_form_id' => $affiliate->affiliate_product->application_form->id,
'pingtree_group_id' => $affiliate->affiliate_product->pingtree_group->id,
'affiliate_id' => $affiliate->id,
'thread_uuid' => $threadUUID,
'status' => 'pending',
'submitted_at' => $submittedAt
]);
// init a new provider class instance
$provider = new $providerClass($request, $application, $affiliate);
// create modelable data
$modelable = $modelableClass::create(array_merge($provider->getMappedApplication(), [
'user_id' => $application->user_id,
'company_id' => $affiliate->company_id,
'country_id' => $application->country_id,
'product_id' => $application->product_id,
'serve_method_id' => $application->serve_method_id,
'application_form_id' => $application->application_form_id,
'pingtree_group_id' => $application->pingtree_group_id,
'affiliate_id' => $application->affiliate_id,
]));
} catch (\Exception $e) {
return new ApiErrorResponse($e, [
'legacy_response' => [
'Result' => 'Invalid',
'Message' => 'Error saving application',
]
]);
}