Understanding Laravel Cashiers 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 = [])
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 = [])
- 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)
- 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)
- Checks model-level trial status
- Returns true if trial_ends_at exists and is future
- No parameters needed
onGenericTrial()
- Scope to filter customers on generic trial
- Used in query builder
- Requires query builder instance
scopeOnGenericTrial($query)
- Checks if model-level trial has expired
- Returns true if trial_ends_at exists and is past
- No parameters needed
hasExpiredGenericTrial()
- Scope to filter customers with expired generic trials
- Used in query builder
- Requires query builder instance
scopeHasExpiredGenericTrial($query)
- 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')
- Just $type: Checks valid subscription existence
- With $price: Checks specific price subscription
- Returns boolean
subscribed($type = 'default', $price = null)
- Gets subscription by type
- Returns Subscription model or null
subscription($type = 'default')
- Gets all subscriptions
- Returns HasMany relationship
- No parameters needed
subscriptions()
- Checks for incomplete payment on subscription
- Returns boolean
hasIncompletePayment($type = 'default')
- $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')
- $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')
- Checks for valid subscription with specific product
- Returns boolean
- More specific than subscribedToProduct
onProduct($product)
- Checks for valid subscription with specific price
- Returns boolean
- More specific than subscribedToPrice
onPrice($price)
- Gets tax rates for subscription
- Returns array
- Empty by default, meant to be overridden
taxRates()
- Gets tax rates for individual subscription items
- Returns array
- Empty by default, meant to be overridden
ManagesCustomer Trait
Customer Identification
newSubscription($type, $prices = [])
- Returns Stripe customer ID or null
- No parameters needed
- Returns string|null
onTrial($type = 'default', $price = null)
- Checks if customer has Stripe ID
- Returns boolean
- No parameters needed
Customer Creation and Management
hasExpiredTrial($type = 'default', $price = null)
- Creates new Stripe customer
- Options affect customer metadata, email, name, etc.
- Throws exception if customer already exists
- Returns Stripe Customer object
onGenericTrial()
- Updates existing Stripe customer
- Options determine what gets updated
- Returns updated Stripe Customer object
- Requires existing customer
scopeOnGenericTrial($query)
- Gets existing customer or creates new one
- Options affect creation if needed
- Returns Stripe Customer object
- More forgiving than createAsStripeCustomer
hasExpiredGenericTrial()
- Updates existing or creates new customer
- Options affect both update and creation
- Returns Stripe Customer object
- Combines update and create functionality
scopeHasExpiredGenericTrial($query)
- Syncs local details to Stripe
- Returns Stripe Customer object
- Uses model attributes for sync
trialEndsAt($type = 'default')
- Syncs if exists or creates new customer
- Options affect creation if needed
- Returns Stripe Customer object
subscribed($type = 'default', $price = null)
- Gets Stripe customer object
- Expand parameter determines related data
- Returns Stripe Customer object
- Requires existing customer
Customer Attributes
subscription($type = 'default')
- Gets name for Stripe sync
- Returns string|null
- Default returns $this->name
subscriptions()
- Gets email for Stripe sync
- Returns string|null
- Default returns $this->email
hasIncompletePayment($type = 'default')
- Gets phone for Stripe sync
- Returns string|null
- Default returns $this->phone
subscribedToProduct($products, $type = 'default')
- Gets address for Stripe sync
- Returns array|null
- Empty by default
subscribedToPrice($prices, $type = 'default')
- Gets preferred locales for Stripe
- Returns array
- Empty by default
onProduct($product)
- Gets metadata for Stripe
- Returns array
- Empty by default
Discount Management
onPrice($price)
- Gets active customer discount
- Returns Discount object or null
- No parameters needed
taxRates()
- Applies coupon to customer
- Void return
- Requires coupon ID
priceTaxRates()
- Applies promotion code to customer
- Void return
- Requires promotion code ID
newSubscription($type, $prices = [])
- Finds promotion code
- Returns PromotionCode object or null
- Options affect search
onTrial($type = 'default', $price = null)
- Finds active promotion code
- Returns PromotionCode object or null
- Options affect search
Balance Management
hasExpiredTrial($type = 'default', $price = null)
- Gets formatted customer balance
- Returns string
- No parameters needed
onGenericTrial()
- Gets raw customer balance
- Returns integer
- No parameters needed
scopeOnGenericTrial($query)
- Gets customer balance transactions
- Returns Collection
- Limit affects returned count
hasExpiredGenericTrial()
- Credits customer balance
- Returns CustomerBalanceTransaction
- Amount is required
scopeHasExpiredGenericTrial($query)
- Debits customer balance
- Returns CustomerBalanceTransaction
- Amount is required
trialEndsAt($type = 'default')
- Applies balance adjustment
- Returns CustomerBalanceTransaction
- Amount is required
Tax Management
subscribed($type = 'default', $price = null)
- Gets customer tax IDs
- Returns Collection
- Options affect retrieval
subscription($type = 'default')
- Creates new tax ID
- Returns Stripe TaxId
- Both parameters required
subscriptions()
- Deletes tax ID
- Void return
- Requires tax ID
hasIncompletePayment($type = 'default')
- Finds specific tax ID
- Returns Stripe TaxId or null
- Requires tax ID
Tax Status Checking
subscribedToProduct($products, $type = 'default')
- Checks if customer is not tax exempt
- Returns boolean
- No parameters needed
subscribedToPrice($prices, $type = 'default')
- Checks if customer is tax exempt
- Returns boolean
- No parameters needed
onProduct($product)
- Checks if reverse charge applies
- Returns boolean
- No parameters needed
Billing Portal
onPrice($price)
- Gets Stripe billing portal URL
- Returns string
- ReturnUrl optional
taxRates()
- Redirects to Stripe billing portal
- Returns RedirectResponse
- ReturnUrl optional
ManagesInvoices Trait
Invoice Items
priceTaxRates()
- Adds invoice item
- Returns Stripe InvoiceItem
- Description and amount required
stripeId()
- Adds price-based item
- Returns Stripe InvoiceItem
- Price ID required
Invoice Creation
hasStripeId()
- Creates immediate invoice
- Returns Invoice object
- Description and amount required
createAsStripeCustomer(array $options = [])
- Creates price-based invoice
- Returns Invoice object
- Price ID required
newSubscription($type, $prices = [])
- Generates invoice
- Returns Invoice object
- Options affect creation
onTrial($type = 'default', $price = null)
- Creates Stripe invoice
- Returns Invoice object
- Options affect creation
Invoice Retrieval
hasExpiredTrial($type = 'default', $price = null)
- Gets upcoming invoice
- Returns Invoice object or null
- Options affect preview
onGenericTrial()
- Finds specific invoice
- Returns Invoice object or null
- Requires invoice ID
scopeOnGenericTrial($query)
- Finds invoice or throws exception
- Returns Invoice object
- Requires invoice ID
- Throws NotFoundHttpException or AccessDeniedHttpException
hasExpiredGenericTrial()
- Gets invoice PDF
- Returns Response
- ID required, filename optional
scopeHasExpiredGenericTrial($query)
- Gets all invoices
- Returns Collection
- Parameters affect filtering
trialEndsAt($type = 'default')
- Gets all invoices including pending
- Returns Collection
- Shorthand for invoices(true)
subscribed($type = 'default', $price = 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.
The above is the detailed content of Understanding Laravel Cashiers Core Traits: A Deep Dive. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.
