Last active
February 18, 2020 13:22
-
-
Save koekaverna/a20a191bbd1aa311a945ac721a0d038f to your computer and use it in GitHub Desktop.
Laravel middleware that keeps utm marks while redirect
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 | |
// This middleware save utm query from url while redirect | |
// It's require Spatie\Url (https://github.com/spatie/url) | |
namespace App\Http\Middleware; | |
use Closure; | |
use Spatie\Url\Url; | |
class KeepUTMRedirect | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$response = $next($request); | |
// if response is redirect | |
if ($response instanceof \Illuminate\Http\RedirectResponse) { | |
// Collect utm marks | |
$utm = $request->only([ | |
'utm_source', | |
'utm_medium', | |
'utm_campaign', | |
'utm_term', | |
'utm_content' | |
]); | |
// Parse url | |
$url = Url::fromString($response->getTargetUrl()); | |
// Add utm marks to url | |
foreach ($utm as $key => $value) { | |
$url = $url->withQueryParameter($key, $value); | |
} | |
$response->setTargetUrl((string)$url); | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment