camille
camille

Reputation: 328

Get attributes from relationship parent model

I'm loading some data for the user like this.

Method 1
$user->load(['subscription.payementTypes']);


Method 2
$user->load(['charity.payementTypes']);

Is there anyway I can figure out in the PaymentType model that it is called via subscription or charity?

I want to call an Accessor in PaymentType based on Subscription or Charity

// For Subscriptions
public function getPaymentDescriptionAttribute()
{
    // if Subscription

    // if Charity
}

The relationships are as follows.

//Class User
public function subscription()
{
    return $this->hasOne(Subscription::class);
}

public function charity()
{
    return $this->hasOne(Charity::class);
}

//Class Subscription
public function paymentTypes()
{
    return $this->belongsToMany(PaymentType::class);
}

Upvotes: 0

Views: 332

Answers (2)

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

if it is not working you can do somthing like this

in User.php

//Class User
public function subscriptionWithPaymentType()
{
    return $this->hasOne(Subscription::class)->with('paymentTypes');
}

then you can do this

$user->load(['subscriptionWithPaymentType']);

Upvotes: 1

I feel like in class Subscription, you should name it paymentTypes. I'd say it's a hasMany though?

public function paymentTypes()
{
    return $this->hasMany(PaymentType::class);
}

and in the PaymentType you can do

public function subscription
{
return $this->belongsTo(Subscription::class);
}

Upvotes: 1

Related Questions