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

Posted 3 years ago by Kryptonit3

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?

Please sign in or create an account to participate in this conversation.