检查订阅状态时出现以下错误:
$user = User::where('id', '=', \Auth::user()->id)->first();
if ($user->subscribed('main')) <-- error
错误:
ErrorException in Builder.php line 2405: Call to undefined method
Illuminate\Database\Query\Builder::valid() (View: /var/www/html...
in Builder.php line 2405
at Builder->__call('valid', array())
at Builder->valid()
at call_user_func_array(array(object(Builder), 'valid'), array()) in Builder.php line 1426
at Builder->__call('valid', array())
at Builder->valid()
at call_user_func_array(array(object(Builder), 'valid'), array()) in Relation.php line 343
at Relation->__call('valid', array()) in Billable.php line 172
at HasMany->valid() in Billable.php line 172
at User->subscribed('main') in BillingsController.php line 58
at BillingsController->index()
在同一视图中使用$user->onGenericTrial()
and方法没有任何问题。$user->onTrial()
我使用以下方法创建了一个新订阅:
$user = User::find(1);
$user->newSubscription('main', 'monthly')->create($creditCardToken);
我正在使用 Laravel 5.2 和 Cashier 6.0 。我在这里关注了文档https://laravel.com/docs/5.2/billing#checking-subscription-status。
在我的用户模型中,我使用 Laravel\Cashier\Billable;并使用计费;并且 hasMany 在我的订阅模型上。我的订阅模型具有 belongsTo User 关系
用户模型
<?php namespace App;
use Laravel\Cashier\Billable;
use Carbon\Carbon;
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract {
use Authenticatable, Authorizable, CanResetPassword;
public $incrementing = true;
use SoftDeletes;
use Billable;
protected $dates = ['deleted_at'];
protected $table = 'users';
protected $fillable = [ ... 'stripe_id', 'card_brand', 'card_last_four', 'trial_ends_at'];
public function subscription()
{
return $this->hasMany('App\Subscription');
}
public function getTrialEndsAtAttribute($value)
{
$format = $this->getDateFormat();
return Carbon::createFromFormat($format, $value, 'UTC')->setTimezone(\Helper::getTimezone());
}
这是发生错误的地方:
https://github.com/laravel/cashier/blob/6.0/src/Billable.php
public function subscribed($subscription = 'default', $plan = null)
{
$subscription = $this->subscription($subscription);
if (is_null($subscription)) {
return false;
}
if (is_null($plan)) {
return $subscription->valid();
}
return $subscription->valid() &&
$subscription->stripe_plan === $plan;
}
解决方案:
终于找到问题了!不得在用户模型和订阅模型之间创建关系。我的 User 模型上有 hasMany 关系,Subscription 模型上有 belongsTo 关系。这就是问题所在。