phplaraveleloquentlaravel-8laravel-cashier

Laravel & Cashier : HasMany magic getter returns an empty string


Using laravel/framework 8.0 and laravel/cashier 13.16

I use cashier to manage stripe subscriptions. As explained in the doc, because I don't use App\Models\User as the Billable Model, I declared my own Billable class in AppServiceProvider :

// app/Providers/AppServiceProvider.php


public function boot()
{
    Cashier::useCustomerModel(CustomClass::class);
    Cashier::useSubscriptionModel(Subscription::class);

    ...
}

In my CustomClass, I use the Billable Trait :

class CustomClass extends Model
{
    use HasFactory, Notifiable, Billable;
}

This should give me access to an HasMany relation defined in the Billable trait :


// ManagesSubscriptions.php (in the Billable Trait)

public function subscriptions(): HasMany
{
    return $this->hasMany(Cashier::$subscriptionModel, $this->getForeignKey())->orderBy('created_at', 'desc');
}

My migrations are well played, in fact when I does

dump($myClassInstance->subscriptions());
dump($myClassInstance->subscriptions()->count());

I get a Illuminate\Database\Eloquent\Relations\HasMany object and count returns 1.

But the magic getter $myClassInstance->subscriptions returns an empty string. I'm new to laravel but it is supposed to return an object right ?

Moreover, this is used in Cashier webhook, WebhookController in the method handleCustomerSubscriptionCreated :

if (! $user->subscriptions->contains('stripe_id', $data['id'])) {

But right here, I'm getting this error :

Error: Call to a member function contains() on string

Maybe I am missing something ?


Solution

  • I found my problem, my Model was overriding the getAttribute method that is used by the magic method __get so some stuff happenned inside that prevented my relations to be returned.

    So be careful when extending this method (I would even recommand not to do it ;))