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

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

Nov 30, 2024 am 12:24 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1244
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

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.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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 vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

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.

See all articles