Search code examples
phplaravellaravel-8laravel-cashier

Change cashier model from User to Hotel


I want to use another model for cashier, not the default. I have 2 tables User and Hotel relation one-to-many (a user can have multiple hotels). I want to add possibility that a user can add different payment methods for his hotels. I removed cashier columns from user and I added to hotel table.

I put in services.php :

'stripe' => [
    'model' => \App\Models\Hotel::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

In my controller :

public function get(Request $request)
{
    $creditorId = config('id');
    $user = $request->user();
    $stripeUser = $user->createOrGetStripeCustomer();
    .............

 }

I added in Hotel.php Billable and I removed Billable from User.

Now I have the error :

Call to undefined method App\Models\User::createOrGetStripeCustomer()

In the past was working for User.php. How can I fix this error?

User.php :

class User extends Authenticatable implements CanResetPassword {

 use Notifiable, HasSanctumTokens, HasFactory;

 protected $fillable = [
  'email',
  'password',
  'lang',
 ];
 .......

Hotel.php :

class Hotel extends Model
{
  use Billable, HasFactory;

  public $incrementing = false;
  protected $fillable = [
    'id',
    'name',
    'user_id',
  ];
   .............

Solution

  • This error appears because you remove the Billable trait from your User model and moved it to the Hotel model

    so what do you need to do from the model relation in this case (one -> many)

    User Model

    class User extends Authenticatable implements CanResetPassword {
    
     use Notifiable, HasSanctumTokens, HasFactory;
    
     protected $fillable = [
      'email',
      'password',
      'lang',
     ];
    
     public function hotels()
     {
        return $this->hasMany(Hotel::class);
     }
    

    after that from the controller you need to pass the hotel as a parameter instead of user

    Controller

    public function get(Request $request, Hotel $hotel)
    {
        $stripeUser = $hotel->createOrGetStripeCustomer();
        .............
    }