Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tolgayigit's avatar

Laravel Referer Tracking

Hello,

I want to make a user referer system in Laravel 5.4. I must use cookie because I must keep referer data minimum 30 days.

I'm giving a referer URL to all users. If some person came to site from one of these URL's, I want to save this referer's id to users table's referer_id's column.

Example referer URL: http://www.example.com?ref_id=10

I looked about cookies in Laravel but I couldn't understand because all of examples were prepared with response() method.

Thanks in advance.

0 likes
1 reply
viktorivanov's avatar

Hello @tolgayigit , I'll suggest to use Middleware where you could check for ?ref_id=10 and make a cookie using the queue method, that way Laravel will set it for you with the next response.

Here are the steps to reproduce:

  1. go in terminal and type php artisan make:middleware Referrer and Laravel will generate a class Referrer in app/Http/Middleware
  2. in handle method of that class type in the following:
    public function handle($request, Closure $next)
    {
        if($request->has('ref_id')) {
            Cookie::queue('ref_id', $request->get('ref_id'), 43200); // 43200 in minutes are 30 days
        }
        return $next($request);
    }
  1. register your middleware in app/Http/Kernel as route middleware, e.g. append 'referrer' => App\Http\Middleware\Referrer::class into protected $routeMiddleware

  2. assign 'referrer' to your "home" route in routes/web.php, for example Route::get('/home', 'HomeController@index')->name('home')->middleware('referrer');

And whenever there is ref_id query parameter in your home route (http://www.example.com?ref_id=10) a cookie will be set on the client's browser.

Cheers

Please or to participate in this conversation.