Home > Backend Development > PHP Tutorial > Understanding Laravel Cashier&#s Core Traits: A Deep Dive

Understanding Laravel Cashier&#s Core Traits: A Deep Dive

DDD
Release: 2024-11-30 00:24:15
Original
530 people have browsed it

Understanding Laravel Cashier

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 = [])
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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

Trial Management

newSubscription($type, $prices = [])
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  • 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
onTrial($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • No parameters: Checks generic trial expiration
  • With $type: Checks specific subscription trial expiration
  • With both: Verifies specific price trial expiration
  • Returns boolean
hasExpiredTrial($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Checks model-level trial status
  • Returns true if trial_ends_at exists and is future
  • No parameters needed
onGenericTrial()
Copy after login
Copy after login
Copy after login
Copy after login
  • Scope to filter customers on generic trial
  • Used in query builder
  • Requires query builder instance
scopeOnGenericTrial($query)
Copy after login
Copy after login
Copy after login
Copy after login
  • Checks if model-level trial has expired
  • Returns true if trial_ends_at exists and is past
  • No parameters needed
hasExpiredGenericTrial()
Copy after login
Copy after login
Copy after login
Copy after login
  • Scope to filter customers with expired generic trials
  • Used in query builder
  • Requires query builder instance
scopeHasExpiredGenericTrial($query)
Copy after login
Copy after login
Copy after login
Copy after login
  • 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

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

ManagesCustomer Trait

Customer Identification

newSubscription($type, $prices = [])
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  • Returns Stripe customer ID or null
  • No parameters needed
  • Returns string|null
onTrial($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Checks if customer has Stripe ID
  • Returns boolean
  • No parameters needed

Customer Creation and Management

hasExpiredTrial($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Creates new Stripe customer
  • Options affect customer metadata, email, name, etc.
  • Throws exception if customer already exists
  • Returns Stripe Customer object
onGenericTrial()
Copy after login
Copy after login
Copy after login
Copy after login
  • Updates existing Stripe customer
  • Options determine what gets updated
  • Returns updated Stripe Customer object
  • Requires existing customer
scopeOnGenericTrial($query)
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets existing customer or creates new one
  • Options affect creation if needed
  • Returns Stripe Customer object
  • More forgiving than createAsStripeCustomer
hasExpiredGenericTrial()
Copy after login
Copy after login
Copy after login
Copy after login
  • Updates existing or creates new customer
  • Options affect both update and creation
  • Returns Stripe Customer object
  • Combines update and create functionality
scopeHasExpiredGenericTrial($query)
Copy after login
Copy after login
Copy after login
Copy after login
  • Syncs local details to Stripe
  • Returns Stripe Customer object
  • Uses model attributes for sync
trialEndsAt($type = 'default')
Copy after login
Copy after login
Copy after login
Copy after login
  • Syncs if exists or creates new customer
  • Options affect creation if needed
  • Returns Stripe Customer object
subscribed($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets Stripe customer object
  • Expand parameter determines related data
  • Returns Stripe Customer object
  • Requires existing customer

Customer Attributes

subscription($type = 'default')
Copy after login
Copy after login
Copy after login
  • Gets name for Stripe sync
  • Returns string|null
  • Default returns $this->name
subscriptions()
Copy after login
Copy after login
Copy after login
  • Gets email for Stripe sync
  • Returns string|null
  • Default returns $this->email
hasIncompletePayment($type = 'default')
Copy after login
Copy after login
Copy after login
  • Gets phone for Stripe sync
  • Returns string|null
  • Default returns $this->phone
subscribedToProduct($products, $type = 'default')
Copy after login
Copy after login
Copy after login
  • Gets address for Stripe sync
  • Returns array|null
  • Empty by default
subscribedToPrice($prices, $type = 'default')
Copy after login
Copy after login
Copy after login
  • Gets preferred locales for Stripe
  • Returns array
  • Empty by default
onProduct($product)
Copy after login
Copy after login
Copy after login
  • Gets metadata for Stripe
  • Returns array
  • Empty by default

Discount Management

onPrice($price)
Copy after login
Copy after login
Copy after login
  • Gets active customer discount
  • Returns Discount object or null
  • No parameters needed
taxRates()
Copy after login
Copy after login
Copy after login
  • Applies coupon to customer
  • Void return
  • Requires coupon ID
priceTaxRates()
Copy after login
Copy after login
  • Applies promotion code to customer
  • Void return
  • Requires promotion code ID
newSubscription($type, $prices = [])
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  • Finds promotion code
  • Returns PromotionCode object or null
  • Options affect search
onTrial($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Finds active promotion code
  • Returns PromotionCode object or null
  • Options affect search

Balance Management

hasExpiredTrial($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets formatted customer balance
  • Returns string
  • No parameters needed
onGenericTrial()
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets raw customer balance
  • Returns integer
  • No parameters needed
scopeOnGenericTrial($query)
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets customer balance transactions
  • Returns Collection
  • Limit affects returned count
hasExpiredGenericTrial()
Copy after login
Copy after login
Copy after login
Copy after login
  • Credits customer balance
  • Returns CustomerBalanceTransaction
  • Amount is required
scopeHasExpiredGenericTrial($query)
Copy after login
Copy after login
Copy after login
Copy after login
  • Debits customer balance
  • Returns CustomerBalanceTransaction
  • Amount is required
trialEndsAt($type = 'default')
Copy after login
Copy after login
Copy after login
Copy after login
  • Applies balance adjustment
  • Returns CustomerBalanceTransaction
  • Amount is required

Tax Management

subscribed($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets customer tax IDs
  • Returns Collection
  • Options affect retrieval
subscription($type = 'default')
Copy after login
Copy after login
Copy after login
  • Creates new tax ID
  • Returns Stripe TaxId
  • Both parameters required
subscriptions()
Copy after login
Copy after login
Copy after login
  • Deletes tax ID
  • Void return
  • Requires tax ID
hasIncompletePayment($type = 'default')
Copy after login
Copy after login
Copy after login
  • Finds specific tax ID
  • Returns Stripe TaxId or null
  • Requires tax ID

Tax Status Checking

subscribedToProduct($products, $type = 'default')
Copy after login
Copy after login
Copy after login
  • Checks if customer is not tax exempt
  • Returns boolean
  • No parameters needed
subscribedToPrice($prices, $type = 'default')
Copy after login
Copy after login
Copy after login
  • Checks if customer is tax exempt
  • Returns boolean
  • No parameters needed
onProduct($product)
Copy after login
Copy after login
Copy after login
  • Checks if reverse charge applies
  • Returns boolean
  • No parameters needed

Billing Portal

onPrice($price)
Copy after login
Copy after login
Copy after login
  • Gets Stripe billing portal URL
  • Returns string
  • ReturnUrl optional
taxRates()
Copy after login
Copy after login
Copy after login
  • Redirects to Stripe billing portal
  • Returns RedirectResponse
  • ReturnUrl optional

ManagesInvoices Trait

Invoice Items

priceTaxRates()
Copy after login
Copy after login
  • Adds invoice item
  • Returns Stripe InvoiceItem
  • Description and amount required
stripeId()
Copy after login
  • Adds price-based item
  • Returns Stripe InvoiceItem
  • Price ID required

Invoice Creation

hasStripeId()
Copy after login
  • Creates immediate invoice
  • Returns Invoice object
  • Description and amount required
createAsStripeCustomer(array $options = [])
Copy after login
  • Creates price-based invoice
  • Returns Invoice object
  • Price ID required
newSubscription($type, $prices = [])
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  • Generates invoice
  • Returns Invoice object
  • Options affect creation
onTrial($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Creates Stripe invoice
  • Returns Invoice object
  • Options affect creation

Invoice Retrieval

hasExpiredTrial($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets upcoming invoice
  • Returns Invoice object or null
  • Options affect preview
onGenericTrial()
Copy after login
Copy after login
Copy after login
Copy after login
  • Finds specific invoice
  • Returns Invoice object or null
  • Requires invoice ID
scopeOnGenericTrial($query)
Copy after login
Copy after login
Copy after login
Copy after login
  • Finds invoice or throws exception
  • Returns Invoice object
  • Requires invoice ID
  • Throws NotFoundHttpException or AccessDeniedHttpException
hasExpiredGenericTrial()
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets invoice PDF
  • Returns Response
  • ID required, filename optional
scopeHasExpiredGenericTrial($query)
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets all invoices
  • Returns Collection
  • Parameters affect filtering
trialEndsAt($type = 'default')
Copy after login
Copy after login
Copy after login
Copy after login
  • Gets all invoices including pending
  • Returns Collection
  • Shorthand for invoices(true)
subscribed($type = 'default', $price = null)
Copy after login
Copy after login
Copy after login
Copy after login
  • 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.

The above is the detailed content of Understanding Laravel Cashier&#s Core Traits: A Deep Dive. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template