Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RonB1985's avatar

How would you solve this? Polymorphic or something else?

I've been at this for a few days now. I have a transactions table which holds information about incomes and expenses. Next to this I have a few other tables:

  • Payments (monthly automatic payments)
  • Savings (savings goals)
  • Plans (payment plans)

For each of these I can add a transaction. And I want to link these together. For example, when I create a new payment to automatically add an expense of 100 dollars on a monthly basis, my scheduler will create this transaction every month. Right now I am linking them together using a polymorphic relation. So the tranactions table has a paymentable_type and paymentable_id field.

This all works. However, I have to use a lot of conditionals. First, when submitting the new transaction, I need to check if a payment was selected in the form, or a saving, or a plan. That's already 3 conditionals in my controller. Some code from controller:

if ($request['plan_id'])
        {
            $plan = Plan::find($request['plan_id']);

            $plan->transactions()->save($transaction);
        }

Also on my transactions.edit form there are some conditionals. The code just looks very messy.

Example in my view:

@if($transaction->paymentable_type == 'App\Models\Plan')
    {{ Form::select('plan_id', ['' => ''] + $plans, $transaction->paymentable_id, ['class' => 'select-plan']) }}
@else
    {{ Form::select('plan_id', ['' => ''] + $plans, null, ['class' => 'select-plan']) }}
@endif

I was thinking about creating a form for each of them, but then I would end up having basically 4 identical transaction forms, with only one difference in each. I just haven't been able to think of the "best" solution, or most clean solution, yet.

How would you solve this?

0 likes
0 replies

Please or to participate in this conversation.