dimanche 9 juillet 2017

Laravel polymorphic relations and many ifs

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.

Aucun commentaire:

Enregistrer un commentaire