Search code examples
mysqllaraveleloquentpayment-method

Laravel Eloquent select query for payment method used


I have designed 3 tables in mysql Payments, CreditCardPayment, WireTransfer. Payment table has column payment_mode which store the mode of payment used (credit card or paypal). In CreditCardPayment & WireTransfer I am storing the payment id from payment table.

Now how do I fetch all the payments from payment table with the payment mode (details from either credit card or paypal table)?


Solution

  • You must do polymorphic relation the Payment entity and to other entities (CreditCardPayment, WireTransfer).

    Add an migration for Payment to adding these columns:

    • paymentable_type (string)
    • paymentable_id (integer)

    At the Payment.php (entity) you should add this function:

    public function paymentable() {
        return $this->morphTo();
    }
    

    At CreditCardPayment.php you should add this function:

    public function payments(){
        return $this->morphMany(Payment::class, 'paymentable');
    }
    

    At WireTransfer.php you should add this function:

    public function payments(){
        return $this->morphMany(Payment::class, 'paymentable');
    }
    

    Note: The "Payment" at the "payments" method is your Payment entity class.