search
HomeBackend DevelopmentPHP TutorialUnderstanding Laravel Cashier&#s Core Traits: A Deep Dive

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

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

  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
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools