DEV3 Technologies home

Referral attribution cookie

Capture a ref code from the URL into a first-party cookie with a validated value and a 30 day window, then read it when the visitor signs up.

LaravelMiddlewarereferralcookieattributionaffiliate

Code

How it works

What it solves

A referral link is only useful if the code survives until the visitor signs up, often days later and on a different page. Reading ?ref= at registration time loses almost everyone. A first-party cookie bridges the gap, and a small helper makes the attribution rules explicit.

How it works

CaptureReferral runs on web requests. If the query string carries ref, it checks the shape with a strict pattern and confirms the code exists in the database, so junk values are never stored. Attribution policy is first touch by default: an existing valid cookie is kept, and a new code only replaces it when last_touch is switched on in config. The response gets a queued cookie that lasts 30 days, is HttpOnly, and uses SameSite=Lax.

Laravel encrypts cookies by default, which also stops visitors editing the code by hand.

ReferralAttribution::resolve is the read side. It returns the referrer's id from the cookie and refuses self-referral, which is the first abuse case you will meet. Call it in your registration action and store the result on the new user.

Adapting it

Rename the parameter, change the lifetime, or record a touch row for analytics before setting the cookie. For cross-domain programmes pass the code through the signup URL as well.

Pitfalls

  • Respect consent rules; a referral cookie may still need disclosure.
  • Register the middleware in the web group, not on API routes.

How to use it

  1. Add referral_code (unique) to users and referred_by (nullable foreign key).
  2. Append CaptureReferral::class to the web middleware group in bootstrap/app.php.
  3. Optionally set config('referrals.last_touch') to true for last-touch attribution.
  4. At registration: $user->referred_by = ReferralAttribution::resolve($user->referral_code);.
  5. Test by visiting /?ref=ABC12345 and checking the ref cookie is set.

Licence: DEV3 Snippet Licence. Free to use, change and ship in personal and commercial projects. Attribution is appreciated, not required. Please do not redistribute snippets as a collection.

Related snippets