Skip to content

Instantly share code, notes, and snippets.

@koekaverna
Last active February 18, 2020 13:22
Show Gist options
  • Save koekaverna/a20a191bbd1aa311a945ac721a0d038f to your computer and use it in GitHub Desktop.
Save koekaverna/a20a191bbd1aa311a945ac721a0d038f to your computer and use it in GitHub Desktop.
Laravel middleware that keeps utm marks while redirect
<?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