Last active
September 16, 2017 07:08
-
-
Save bayareawebpro/94e28e7e498b376b6a1ca09583627c2d to your computer and use it in GitHub Desktop.
Affiliate Tracker Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Http\Middleware; | |
use App\Affiliate; | |
use App\Referral; | |
use Closure; | |
use Cookie; | |
class TrackAffiliates | |
{ | |
/** | |
* Run the request filter. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$response = $next($request); | |
if($request->has('affiliate')) { | |
$response->withCookie(cookie('affiliate', $request->get('affiliate'), 10080)); | |
} | |
if(request()->user() && $request->hasCookie('affiliate')){ | |
$affiliate_tracking_id = request()->cookie('affiliate'); | |
if(Affiliate::where('tracking_id',$affiliate_tracking_id)->exists()){ | |
$affiliate = Affiliate::where('tracking_id',$affiliate_tracking_id)->first(); | |
$referral = $affiliate->referrals()->firstOrCreate(array( | |
'user_id'=>request()->user()->id | |
)); | |
$stats = (object) array(); | |
$stats->url = request()->fullUrl(); | |
$stats->ip = request()->ips(); | |
$stats->user_agent = request()->userAgent(); | |
$referral->request = $stats; | |
$referral->save(); | |
$response->withCookie(Cookie::forget('affiliate')); | |
} | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment