问题描述:

I've got a problem with the cashier package from Taylor (https://github.com/laravel/cashier). When I try to get the Invoices for a User the Object that is returned is Empty.

For information i've set up my cashier database columns into a membership table! And then set up the proper relationships.

I can charge the User if I do something like this:

$user->membership->subscription('1month')->create($token);

But if I want to get the invoices like so

$invoices = $user->membership->invoices();

it returns an empty Object.

What am I doing wrong??

Thanks

Update:

Here`s the code from the Models:

User.php

public function membership() {

return $this->hasOne('Membership');

}

and

Membership.php

class Membership extends \Eloquent implements BillableInterface {

use BillableTrait;

/**

* @var array

*/

protected $dates = ['trial_ends_at', 'subscription_ends_at'];

public function user_membership() {

return $this->belongsTo('User');

}

}

网友答案:

For anyone also struggling with this, I found that just returning $invoices will show a blank json array, but if you pass $invoices to a view, and use a foreach loop it will work.

Ex: This returns a blank array

$invoices = $user->invoices();

return $invoices

The following will return a value even though it appears blank in the original json return.

$invoices = $user->invoices();

foreach ($invoices as $invoice)

{

$test = $invoice->dateString();

}

return $test;
网友答案:

I'm using Laravel 5.1, if you checkout \laravel\cashier\src\Laravel\Cashier\Invoice.php you can see all the methods available on the Invoice object.

You have to loop through the $this->user->invoices() object to use the methods, but if you're looking for a verbose dump of the invoice data you can call getStripeInvoice().

This dumps all the data related to an invoice..

    $invoices_object = $this->user->invoices();
    $invoices = [];

    foreach($invoices_object as $invoice) {
        array_push($invoices, $invoice->getStripeInvoice() );
    }
    return $invoices;

网友答案:

Try adding in subscription() before calling invoices()

$user->membership()->subscription()->invoices();

网友答案:

If you are pulling it as a JSON or similar, this can be a useful snippet to return from your controller:

    public function index()
    {
        $user = auth()->user();

        if($user->hasStripeId()) {
            $invoices = $user->invoices()->map(function($invoice) {
                return [
                    'date' => $invoice->date()->toFormattedDateString(),
                    'total' => $invoice->total,
                    'download' => '/user/download/invoice/' . $invoice->id,
                ];
            });
        } else {
            $invoices = [];
        }

        return [ 'invoices' => $invoices ];
    }

Tested in Cashier v7.x

相关阅读:
Top