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

Kryptonit3's avatar

[Stripe][Cashier] Get model records where user is subscribed()

I am unsure on how to do the following. I would like to get records from a model where the related User model is subscribed to a stripe plan. Here is an example of what I am talking about.

User Model

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;

    protected $fillable = [
        'first_name', 'last_name', 'username',
        'email', 'password'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function listings()
    {
        return $this->hasMany(Listing::class);
    }
}

Listing Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Listing extends Model
{
    protected $fillable = [
        'title'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

I would like to be able to get all Listing where the user is subscribed. Now I can easily see if a specific user is subscribed with $user->subscribed() but I want to be able to get all Listings where the user is subscribed.

I tried making a custom query scope on the Listing model to no avail. Here is what I tried

public function scopeSubscribed($query)
{
    $query->whereHas('user', function($q) {
        $q->subscribed();
    });
}

and using it like so

$listings = Listing::subscribed()->all();

Doesn't work. Any ideas?

0 likes
1 reply
Kryptonit3's avatar

Maybe this is a working solution. I tried following the logic @TaylorOtwell uses in the Cashier package to check if the subscription is active. I have added this as the query scope on the Listing model.

public function scopeSubscribed($query)
{
    return $query->whereHas('user', function ($r) {
                $r->whereHas('subscriptions', function ($s) {
                    $s->whereNested(function ($t) {
                        $t->where('name', 'main') // name of subscription
                            ->whereNull('ends_at')
                            ->orWhere('ends_at', '>', Carbon::now())
                            ->orWhereNotNull('trial_ends_at')
                            ->where('trial_ends_at', '>', Carbon::today());
                    });
                });
            });
}

It appears to work. Sucks It has to be done like this.

3 likes

Please or to participate in this conversation.