Search code examples
laravellaravel-nova

MorphTo with conditions


I am working with field MorphTo and I try to make conditions for the resources.

For example I have 4 resources:

Accounts

PaymentMethodCreditCard

PaymentMethodBankAccount

Transactions

Every Account can add as many Payment Methods as he wants. And in the transaction I work with MorphTo to select the Payment Method that the account selected.

My problem starts when I try to create a transaction from Nova and get a list of all the Payment Methods in the db without any relation to the account.

My ideal idea was like that:

        MorphTo::make('Transactions')
        ->withoutTrashed()
        ->dependsOn('Account', function (MorphTo $field, NovaRequest $request, FormData $formData) {
            if(isset($formData->Account)){
                $field->types([
                    PaymentMethodCreditCard::class => fn($q)=>$q->where('account_id', $formData->Account),
                    PaymentMethodBankAccount::class => fn($q)=>$q->where('account_id', $formData->Account),
                ]);
            }
        }),

But of course it will not work, Someone has any idea how I can add conditions to the resource?


Solution

  • I'll give you two answers. Since the question does not exactly clarify whether the Account value is changable during the edit process or it's predefined.

    Account value does not change.

    If the account value does not change after the resource is loaded, then the solution you are looking for is Relatable Filtering

    public static function relatablePaymentMethods(NovaRequest $request, $query)
    {
        $resource = $request->findResourceOrFail();
        return $query->where('account_id', $resource->Account);
    }
    

    Account value can change

    If the account value can change, then you'll need to create your own "Morph To" behavior using Select and Hidden fields.

    With Select field, you can utilize the dependsOn and options functions, to change the query results when the Account changes.