Bilal Haidar
Posted on November 28, 2024
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 = [])
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)
- 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)
- No parameters: Checks generic trial expiration
- With
$type
: Checks specific subscription trial expiration - With both: Verifies specific price trial expiration
- Returns boolean
onGenericTrial()
- Checks model-level trial status
- Returns true if trial_ends_at exists and is future
- No parameters needed
scopeOnGenericTrial($query)
- Scope to filter customers on generic trial
- Used in query builder
- Requires query builder instance
hasExpiredGenericTrial()
- Checks if model-level trial has expired
- Returns true if trial_ends_at exists and is past
- No parameters needed
scopeHasExpiredGenericTrial($query)
- Scope to filter customers with expired generic trials
- Used in query builder
- Requires query builder instance
trialEndsAt($type = 'default')
- 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)
- Just
$type
: Checks valid subscription existence - With
$price
: Checks specific price subscription - Returns boolean
subscription($type = 'default')
- Gets subscription by type
- Returns Subscription model or null
subscriptions()
- Gets all subscriptions
- Returns HasMany relationship
- No parameters needed
hasIncompletePayment($type = 'default')
- Checks for incomplete payment on subscription
- Returns boolean
subscribedToProduct($products, $type = 'default')
-
$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')
-
$prices
: Single price ID or array -
$type
: Subscription type to check - Returns boolean
- Checks if subscribed to ANY of given prices
onProduct($product)
- Checks for valid subscription with specific product
- Returns boolean
- More specific than subscribedToProduct
onPrice($price)
- Checks for valid subscription with specific price
- Returns boolean
- More specific than subscribedToPrice
taxRates()
- Gets tax rates for subscription
- Returns array
- Empty by default, meant to be overridden
priceTaxRates()
- Gets tax rates for individual subscription items
- Returns array
- Empty by default, meant to be overridden
ManagesCustomer Trait
Customer Identification
stripeId()
- Returns Stripe customer ID or null
- No parameters needed
- Returns string|null
hasStripeId()
- Checks if customer has Stripe ID
- Returns boolean
- No parameters needed
Customer Creation and Management
createAsStripeCustomer(array $options = [])
- Creates new Stripe customer
- Options affect customer metadata, email, name, etc.
- Throws exception if customer already exists
- Returns Stripe Customer object
updateStripeCustomer(array $options = [])
- Updates existing Stripe customer
- Options determine what gets updated
- Returns updated Stripe Customer object
- Requires existing customer
createOrGetStripeCustomer(array $options = [])
- Gets existing customer or creates new one
- Options affect creation if needed
- Returns Stripe Customer object
- More forgiving than createAsStripeCustomer
updateOrCreateStripeCustomer(array $options = [])
- Updates existing or creates new customer
- Options affect both update and creation
- Returns Stripe Customer object
- Combines update and create functionality
syncStripeCustomerDetails()
- Syncs local details to Stripe
- Returns Stripe Customer object
- Uses model attributes for sync
syncOrCreateStripeCustomer(array $options = [])
- Syncs if exists or creates new customer
- Options affect creation if needed
- Returns Stripe Customer object
asStripeCustomer(array $expand = [])
- Gets Stripe customer object
- Expand parameter determines related data
- Returns Stripe Customer object
- Requires existing customer
Customer Attributes
stripeName()
- Gets name for Stripe sync
- Returns string|null
- Default returns $this->name
stripeEmail()
- Gets email for Stripe sync
- Returns string|null
- Default returns $this->email
stripePhone()
- Gets phone for Stripe sync
- Returns string|null
- Default returns $this->phone
stripeAddress()
- Gets address for Stripe sync
- Returns array|null
- Empty by default
stripePreferredLocales()
- Gets preferred locales for Stripe
- Returns array
- Empty by default
stripeMetadata()
- Gets metadata for Stripe
- Returns array
- Empty by default
Discount Management
discount()
- Gets active customer discount
- Returns Discount object or null
- No parameters needed
applyCoupon($coupon)
- Applies coupon to customer
- Void return
- Requires coupon ID
applyPromotionCode($promotionCodeId)
- Applies promotion code to customer
- Void return
- Requires promotion code ID
findPromotionCode($code, array $options = [])
- Finds promotion code
- Returns PromotionCode object or null
- Options affect search
findActivePromotionCode($code, array $options = [])
- Finds active promotion code
- Returns PromotionCode object or null
- Options affect search
Balance Management
balance()
- Gets formatted customer balance
- Returns string
- No parameters needed
rawBalance()
- Gets raw customer balance
- Returns integer
- No parameters needed
balanceTransactions($limit = 10, array $options = [])
- Gets customer balance transactions
- Returns Collection
- Limit affects returned count
creditBalance($amount, $description = null, array $options = [])
- Credits customer balance
- Returns CustomerBalanceTransaction
- Amount is required
debitBalance($amount, $description = null, array $options = [])
- Debits customer balance
- Returns CustomerBalanceTransaction
- Amount is required
applyBalance($amount, $description = null, array $options = [])
- Applies balance adjustment
- Returns CustomerBalanceTransaction
- Amount is required
Tax Management
taxIds(array $options = [])
- Gets customer tax IDs
- Returns Collection
- Options affect retrieval
createTaxId($type, $value)
- Creates new tax ID
- Returns Stripe TaxId
- Both parameters required
deleteTaxId($id)
- Deletes tax ID
- Void return
- Requires tax ID
findTaxId($id)
- Finds specific tax ID
- Returns Stripe TaxId or null
- Requires tax ID
Tax Status Checking
isNotTaxExempt()
- Checks if customer is not tax exempt
- Returns boolean
- No parameters needed
isTaxExempt()
- Checks if customer is tax exempt
- Returns boolean
- No parameters needed
reverseChargeApplies()
- Checks if reverse charge applies
- Returns boolean
- No parameters needed
Billing Portal
billingPortalUrl($returnUrl = null, array $options = [])
- Gets Stripe billing portal URL
- Returns string
- ReturnUrl optional
redirectToBillingPortal($returnUrl = null, array $options = [])
- Redirects to Stripe billing portal
- Returns RedirectResponse
- ReturnUrl optional
ManagesInvoices Trait
Invoice Items
tab($description, $amount, array $options = [])
- Adds invoice item
- Returns Stripe InvoiceItem
- Description and amount required
tabPrice($price, $quantity = 1, array $options = [])
- Adds price-based item
- Returns Stripe InvoiceItem
- Price ID required
Invoice Creation
invoiceFor($description, $amount, array $tabOptions = [], array $invoiceOptions = [])
- Creates immediate invoice
- Returns Invoice object
- Description and amount required
invoicePrice($price, $quantity = 1, array $tabOptions = [], array $invoiceOptions = [])
- Creates price-based invoice
- Returns Invoice object
- Price ID required
invoice(array $options = [])
- Generates invoice
- Returns Invoice object
- Options affect creation
createInvoice(array $options = [])
- Creates Stripe invoice
- Returns Invoice object
- Options affect creation
Invoice Retrieval
upcomingInvoice(array $options = [])
- Gets upcoming invoice
- Returns Invoice object or null
- Options affect preview
findInvoice($id)
- Finds specific invoice
- Returns Invoice object or null
- Requires invoice ID
findInvoiceOrFail($id)
- Finds invoice or throws exception
- Returns Invoice object
- Requires invoice ID
- Throws NotFoundHttpException or AccessDeniedHttpException
downloadInvoice($id, array $data = [], $filename = null)
- Gets invoice PDF
- Returns Response
- ID required, filename optional
invoices($includePending = false, array $parameters = [])
- Gets all invoices
- Returns Collection
- Parameters affect filtering
invoicesIncludingPending(array $parameters = [])
- Gets all invoices including pending
- Returns Collection
- Shorthand for invoices(true)
cursorPaginateInvoices($perPage = 24, array $parameters = [], $cursorName = 'cursor', $cursor = null)
- Gets paginated invoices
- Returns CursorPaginator
- Multiple parameters affect pagination
Key Observations
- Parameter Sensitivity: Methods often have different behaviors based on parameter presence.
- Return Types: Methods consistently return specific types (boolean, objects, collections).
- Default Values: Many parameters have reasonable defaults but can be overridden.
- Trait Interdependence: Methods often rely on other trait methods.
- Stripe Integration: Most methods interact with Stripe's API either directly or indirectly.
Best Practices
- Always check parameter requirements for desired behavior.
- Handle potential exceptions, especially for *OrFail methods.
- Use proper type hinting when extending these traits.
- Test different parameter combinations thoroughly.
- 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.
Posted on November 28, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.