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
webgroup, not on API routes.
How to use it
- Add
referral_code(unique) tousersandreferred_by(nullable foreign key). - Append
CaptureReferral::classto the web middleware group inbootstrap/app.php. - Optionally set
config('referrals.last_touch')to true for last-touch attribution. - At registration:
$user->referred_by = ReferralAttribution::resolve($user->referral_code);. - Test by visiting
/?ref=ABC12345and checking therefcookie 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.