spatie/laravel-referer
Store a visitor’s original referrer in the Laravel session. Detects from utm_source first, then the external domain from the Referer header, otherwise empty. Configurable session key and referrer sources via published config.
Installation:
composer require spatie/laravel-referer
Publish the config file (optional):
php artisan vendor:publish --provider="Spatie\Referer\RefererServiceProvider"
First Use Case:
Automatically capture the referer on every request. The package stores the referer in the session under the key referer. Access it anywhere in your app:
$referer = session('referer');
Where to Look First:
Automatic Referer Capture:
The package listens to the Illuminate\Http\Request events (starting, finished) and populates the session with the referer. No manual intervention is needed for standard use.
Conditional Logic: Use the referer to drive user experience or analytics:
if ($referer = session('referer')) {
if (str_contains($referer, 'google.com')) {
// Show Google-specific CTA
}
}
Integration with Middleware: Create middleware to act on the referer:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class TrackReferer
{
public function handle(Request $request, Closure $next)
{
$referer = session('referer');
// Log or process referer data
return $next($request);
}
}
Register in app/Http/Kernel.php:
protected $middleware = [
\App\Http\Middleware\TrackReferer::class,
];
Custom Session Key:
Override the default session key (referer) in config/referer.php:
'session_key' => 'custom_referer_key',
Ignoring Specific Domains: Exclude internal or unwanted domains from being captured:
'ignored_domains' => [
'example.com',
'localhost',
],
Manual Override: Manually set the referer in edge cases:
session(['referer' => 'custom_referer_url']);
Event-Based Processing:
Listen to the referer.captured event to react dynamically:
use Spatie\Referer\Events\RefererCaptured;
RefererCaptured::listen(function (RefererCaptured $event) {
// Custom logic when referer is captured
});
Referer in API Responses: Include the referer in API responses for client-side tracking:
return response()->json([
'data' => $data,
'referer' => session('referer'),
]);
Combining with UTM Parameters:
Leverage the package’s priority logic (e.g., utm_source over Referer header) for marketing campaigns:
if (session('referer') === 'newsletter.example.com') {
// Target newsletter subscribers
}
Testing: Mock the referer in tests:
$this->withSession(['referer' => 'test_referer']);
Session Dependency:
SESSION_DRIVER in .env is configured (e.g., file, database, redis) to avoid silent failures.Header Sanitization:
Referer header is sanitized to remove fragments (#) and query strings (?). If you need the raw header, access it directly:
$rawReferer = $request->header('Referer');
HTTPS/HTTP Mismatches:
http://, https://) are consistent. If you need the original scheme, store it separately.Ignored Domains:
ignored_domains are case-sensitive. Use lowercase for consistency:
'ignored_domains' => ['EXAMPLE.COM'], // Won't match 'example.com'
Caching:
Cache::remember), ensure the referer is recaptured if needed:
$referer = session('referer', fn() => $this->captureReferer());
CSRF and Forms:
if ($request->referer !== session('referer')) {
abort(403, 'Invalid referer');
}
Check Session Data: Dump the session to verify the referer is stored:
dd(session()->all());
Log Referer Capture: Add debug logs in the service provider:
// In RefererServiceProvider.php
Referer::capture(function ($referer) {
\Log::debug('Captured referer:', ['referer' => $referer]);
});
Test Edge Cases:
$request->headers->remove('Referer');
$this->assertEmpty(session('referer'));
http:///example.com gracefully (it does, but test locally).Clear Session Issues: If the referer isn’t persisting, check for:
StartSession order in Kernel.php).array driver).Custom Referer Logic:
Override the Spatie\Referer\Referer class to modify how referers are captured:
namespace App\Services;
use Spatie\Referer\Referer as BaseReferer;
class CustomReferer extends BaseReferer
{
protected function determineReferer(): ?string
{
// Custom logic here
return parent::determineReferer();
}
}
Bind it in AppServiceProvider:
$this->app->bind(\Spatie\Referer\Referer::class, App\Services\CustomReferer::class);
Add Referer to Models: Use accessors to attach referer data to Eloquent models:
public function getRefererAttribute()
{
return session('referer');
}
Referer in Views: Share the referer with Blade views:
View::share('referer', session('referer'));
Access in Blade:
@if($referer)
<p>You came from: {{ $referer }}</p>
@endif
Analytics Integration: Pipe referer data to tools like Google Analytics or Mixpanel:
$referer = session('referer');
\Analytics::track('referer_visit', ['referer' => $referer]);
How can I help you explore Laravel packages today?