I'm still learning Laravel, and I still have one thing I'm stuck on. In my transactions
table in my database, I have two fields for a polymorphic relation:
paymentable_id
paymentable_type
So I can add a Payment Plan
or a Savings Plan
or any other model, to a transaction.
The way I am doing this is, by having a couple of radio buttons in my view, to select which model has to be added. After making a selection, a dropdown appears to select which one has to be added, and this will submit a Payment Plan ID
for example.
In my controller, I am then checking which has been submitted, and then attaching that one to my transaction:
if ($request['plan_id'])
{
$plan = Plan::find($request['plan_id']);
$plan->transactions()->save($transaction);
}
if ($request['saving_id'])
{
$saving = Saving::find($request['saving_id']);
$saving->transactions()->save($transaction);
}
// And a couple more, for Fixed Payments, Subscriptions, Budgets, and so on.
And this is where I am stuck, I do not know the proper way to accomplish this, or even if polymorphic is the way to go for this (I'm pretty sure that it is though). Having like 5+ if's
in my controller, or anywhere else for that matter, seems wrong to me.
A simple solution, though might not be practicable, is to change your form to pass two values: 'plan_type'
, 'plan_id'
. Then in your controller, you check which plan type is requested and defer to its model'
$planType = "App\\" . $request['plan_type'];
$plan = $planType::find($request['plan_id']);
$plan->transactions()->save($transaction);
Of course, you need to validate the data, and check that the type submitted exists.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.