DEV Community

Bilal Haidar
Bilal Haidar

Posted on

Understanding Laravel Cashier's Core Traits: A Deep Dive

Laravel Cashier provides several powerful traits that handle Stripe integrations. Today, we'll explore three core traits and their public methods: ManagesSubscriptions, ManagesCustomer, and ManagesInvoices. Understanding these traits is crucial for implementing subscription-based billing in your Laravel applications.

ManagesSubscriptions Trait

Subscription Creation and Management

newSubscription($type, $prices = [])
Enter fullscreen mode Exit fullscreen mode

Creates new subscription builder instance. Type defines the subscription name (e.g., 'default'), and prices can be single ID or array.

Trial Management

onTrial($type = 'default', $price = null)
Enter fullscreen mode Exit fullscreen mode
  • No parameters: Checks ONLY generic (model-level) trial
  • With $type: Checks subscription-specific trial
  • With both: Checks if specific price is on trial
  • Returns boolean
hasExpiredTrial($type = 'default', $price = null)
Enter fullscreen mode Exit fullscreen mode
  • No parameters: Checks generic trial expiration
  • With $type: Checks specific subscription trial expiration
  • With both: Verifies specific price trial expiration
  • Returns boolean
onGenericTrial()
Enter fullscreen mode Exit fullscreen mode
  • Checks model-level trial status
  • Returns true if trial_ends_at exists and is future
  • No parameters needed
scopeOnGenericTrial($query)
Enter fullscreen mode Exit fullscreen mode
  • Scope to filter customers on generic trial
  • Used in query builder
  • Requires query builder instance
hasExpiredGenericTrial()
Enter fullscreen mode Exit fullscreen mode
  • Checks if model-level trial has expired
  • Returns true if trial_ends_at exists and is past
  • No parameters needed
scopeHasExpiredGenericTrial($query)
Enter fullscreen mode Exit fullscreen mode
  • Scope to filter customers with expired generic trials
  • Used in query builder
  • Requires query builder instance
trialEndsAt($type = 'default')
Enter fullscreen mode Exit fullscreen mode
  • No parameters: Returns generic trial end date if on generic trial
  • With $type: Returns subscription-specific trial end date
  • Returns Carbon instance or null

Subscription Status Checking

subscribed($type = 'default', $price = null)
Enter fullscreen mode Exit fullscreen mode
  • Just $type: Checks valid subscription existence
  • With $price: Checks specific price subscription
  • Returns boolean
subscription($type = 'default')
Enter fullscreen mode Exit fullscreen mode
  • Gets subscription by type
  • Returns Subscription model or null
subscriptions()
Enter fullscreen mode Exit fullscreen mode
  • Gets all subscriptions
  • Returns HasMany relationship
  • No parameters needed
hasIncompletePayment($type = 'default')
Enter fullscreen mode Exit fullscreen mode
  • Checks for incomplete payment on subscription
  • Returns boolean
subscribedToProduct($products, $type = 'default')
Enter fullscreen mode Exit fullscreen mode
  • $products: Single product ID or array
  • $type: Subscription type to check
  • Returns boolean
  • Checks if subscribed to ANY of given products
subscribedToPrice($prices, $type = 'default')
Enter fullscreen mode Exit fullscreen mode
  • $prices: Single price ID or array
  • $type: Subscription type to check
  • Returns boolean
  • Checks if subscribed to ANY of given prices
onProduct($product)
Enter fullscreen mode Exit fullscreen mode
  • Checks for valid subscription with specific product
  • Returns boolean
  • More specific than subscribedToProduct
onPrice($price)
Enter fullscreen mode Exit fullscreen mode
  • Checks for valid subscription with specific price
  • Returns boolean
  • More specific than subscribedToPrice
taxRates()
Enter fullscreen mode Exit fullscreen mode
  • Gets tax rates for subscription
  • Returns array
  • Empty by default, meant to be overridden
priceTaxRates()
Enter fullscreen mode Exit fullscreen mode
  • Gets tax rates for individual subscription items
  • Returns array
  • Empty by default, meant to be overridden

ManagesCustomer Trait

Customer Identification

stripeId()
Enter fullscreen mode Exit fullscreen mode
  • Returns Stripe customer ID or null
  • No parameters needed
  • Returns string|null
hasStripeId()
Enter fullscreen mode Exit fullscreen mode
  • Checks if customer has Stripe ID
  • Returns boolean
  • No parameters needed

Customer Creation and Management

createAsStripeCustomer(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Creates new Stripe customer
  • Options affect customer metadata, email, name, etc.
  • Throws exception if customer already exists
  • Returns Stripe Customer object
updateStripeCustomer(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Updates existing Stripe customer
  • Options determine what gets updated
  • Returns updated Stripe Customer object
  • Requires existing customer
createOrGetStripeCustomer(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Gets existing customer or creates new one
  • Options affect creation if needed
  • Returns Stripe Customer object
  • More forgiving than createAsStripeCustomer
updateOrCreateStripeCustomer(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Updates existing or creates new customer
  • Options affect both update and creation
  • Returns Stripe Customer object
  • Combines update and create functionality
syncStripeCustomerDetails()
Enter fullscreen mode Exit fullscreen mode
  • Syncs local details to Stripe
  • Returns Stripe Customer object
  • Uses model attributes for sync
syncOrCreateStripeCustomer(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Syncs if exists or creates new customer
  • Options affect creation if needed
  • Returns Stripe Customer object
asStripeCustomer(array $expand = [])
Enter fullscreen mode Exit fullscreen mode
  • Gets Stripe customer object
  • Expand parameter determines related data
  • Returns Stripe Customer object
  • Requires existing customer

Customer Attributes

stripeName()
Enter fullscreen mode Exit fullscreen mode
  • Gets name for Stripe sync
  • Returns string|null
  • Default returns $this->name
stripeEmail()
Enter fullscreen mode Exit fullscreen mode
  • Gets email for Stripe sync
  • Returns string|null
  • Default returns $this->email
stripePhone()
Enter fullscreen mode Exit fullscreen mode
  • Gets phone for Stripe sync
  • Returns string|null
  • Default returns $this->phone
stripeAddress()
Enter fullscreen mode Exit fullscreen mode
  • Gets address for Stripe sync
  • Returns array|null
  • Empty by default
stripePreferredLocales()
Enter fullscreen mode Exit fullscreen mode
  • Gets preferred locales for Stripe
  • Returns array
  • Empty by default
stripeMetadata()
Enter fullscreen mode Exit fullscreen mode
  • Gets metadata for Stripe
  • Returns array
  • Empty by default

Discount Management

discount()
Enter fullscreen mode Exit fullscreen mode
  • Gets active customer discount
  • Returns Discount object or null
  • No parameters needed
applyCoupon($coupon)
Enter fullscreen mode Exit fullscreen mode
  • Applies coupon to customer
  • Void return
  • Requires coupon ID
applyPromotionCode($promotionCodeId)
Enter fullscreen mode Exit fullscreen mode
  • Applies promotion code to customer
  • Void return
  • Requires promotion code ID
findPromotionCode($code, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Finds promotion code
  • Returns PromotionCode object or null
  • Options affect search
findActivePromotionCode($code, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Finds active promotion code
  • Returns PromotionCode object or null
  • Options affect search

Balance Management

balance()
Enter fullscreen mode Exit fullscreen mode
  • Gets formatted customer balance
  • Returns string
  • No parameters needed
rawBalance()
Enter fullscreen mode Exit fullscreen mode
  • Gets raw customer balance
  • Returns integer
  • No parameters needed
balanceTransactions($limit = 10, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Gets customer balance transactions
  • Returns Collection
  • Limit affects returned count
creditBalance($amount, $description = null, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Credits customer balance
  • Returns CustomerBalanceTransaction
  • Amount is required
debitBalance($amount, $description = null, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Debits customer balance
  • Returns CustomerBalanceTransaction
  • Amount is required
applyBalance($amount, $description = null, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Applies balance adjustment
  • Returns CustomerBalanceTransaction
  • Amount is required

Tax Management

taxIds(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Gets customer tax IDs
  • Returns Collection
  • Options affect retrieval
createTaxId($type, $value)
Enter fullscreen mode Exit fullscreen mode
  • Creates new tax ID
  • Returns Stripe TaxId
  • Both parameters required
deleteTaxId($id)
Enter fullscreen mode Exit fullscreen mode
  • Deletes tax ID
  • Void return
  • Requires tax ID
findTaxId($id)
Enter fullscreen mode Exit fullscreen mode
  • Finds specific tax ID
  • Returns Stripe TaxId or null
  • Requires tax ID

Tax Status Checking

isNotTaxExempt()
Enter fullscreen mode Exit fullscreen mode
  • Checks if customer is not tax exempt
  • Returns boolean
  • No parameters needed
isTaxExempt()
Enter fullscreen mode Exit fullscreen mode
  • Checks if customer is tax exempt
  • Returns boolean
  • No parameters needed
reverseChargeApplies()
Enter fullscreen mode Exit fullscreen mode
  • Checks if reverse charge applies
  • Returns boolean
  • No parameters needed

Billing Portal

billingPortalUrl($returnUrl = null, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Gets Stripe billing portal URL
  • Returns string
  • ReturnUrl optional
redirectToBillingPortal($returnUrl = null, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Redirects to Stripe billing portal
  • Returns RedirectResponse
  • ReturnUrl optional

ManagesInvoices Trait

Invoice Items

tab($description, $amount, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Adds invoice item
  • Returns Stripe InvoiceItem
  • Description and amount required
tabPrice($price, $quantity = 1, array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Adds price-based item
  • Returns Stripe InvoiceItem
  • Price ID required

Invoice Creation

invoiceFor($description, $amount, array $tabOptions = [], array $invoiceOptions = [])
Enter fullscreen mode Exit fullscreen mode
  • Creates immediate invoice
  • Returns Invoice object
  • Description and amount required
invoicePrice($price, $quantity = 1, array $tabOptions = [], array $invoiceOptions = [])
Enter fullscreen mode Exit fullscreen mode
  • Creates price-based invoice
  • Returns Invoice object
  • Price ID required
invoice(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Generates invoice
  • Returns Invoice object
  • Options affect creation
createInvoice(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Creates Stripe invoice
  • Returns Invoice object
  • Options affect creation

Invoice Retrieval

upcomingInvoice(array $options = [])
Enter fullscreen mode Exit fullscreen mode
  • Gets upcoming invoice
  • Returns Invoice object or null
  • Options affect preview
findInvoice($id)
Enter fullscreen mode Exit fullscreen mode
  • Finds specific invoice
  • Returns Invoice object or null
  • Requires invoice ID
findInvoiceOrFail($id)
Enter fullscreen mode Exit fullscreen mode
  • Finds invoice or throws exception
  • Returns Invoice object
  • Requires invoice ID
  • Throws NotFoundHttpException or AccessDeniedHttpException
downloadInvoice($id, array $data = [], $filename = null)
Enter fullscreen mode Exit fullscreen mode
  • Gets invoice PDF
  • Returns Response
  • ID required, filename optional
invoices($includePending = false, array $parameters = [])
Enter fullscreen mode Exit fullscreen mode
  • Gets all invoices
  • Returns Collection
  • Parameters affect filtering
invoicesIncludingPending(array $parameters = [])
Enter fullscreen mode Exit fullscreen mode
  • Gets all invoices including pending
  • Returns Collection
  • Shorthand for invoices(true)
cursorPaginateInvoices($perPage = 24, array $parameters = [], $cursorName = 'cursor', $cursor = null)
Enter fullscreen mode Exit fullscreen mode
  • Gets paginated invoices
  • Returns CursorPaginator
  • Multiple parameters affect pagination

Key Observations

  1. Parameter Sensitivity: Methods often have different behaviors based on parameter presence.
  2. Return Types: Methods consistently return specific types (boolean, objects, collections).
  3. Default Values: Many parameters have reasonable defaults but can be overridden.
  4. Trait Interdependence: Methods often rely on other trait methods.
  5. Stripe Integration: Most methods interact with Stripe's API either directly or indirectly.

Best Practices

  1. Always check parameter requirements for desired behavior.
  2. Handle potential exceptions, especially for *OrFail methods.
  3. Use proper type hinting when extending these traits.
  4. Test different parameter combinations thoroughly.
  5. Consider caching frequent calls to reduce API requests.

Conclusion

These traits form the backbone of Laravel Cashier's functionality. Understanding the full scope of available methods and their parameter behaviors is crucial for proper implementation. Always consult the official documentation alongside this reference for the most up-to-date information.

Top comments (0)