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

troelsjohnsen's avatar

How to set a Cookie with Laravel 5?

I am trying to figure how to set a cookie in Laravel 5. This doesn't work:

return view('welcome')->withCookie(cookie('test', 'test', 45000));

Can anyone help me? I have tried looking through the source code but can't figure it out.

0 likes
11 replies
bashy's avatar

So what part isn't working? Is it not saving test value in test cookie?

bart's avatar

What does not work? Maybe you could try the Cookie::make() method instead?

troelsjohnsen's avatar

This doesn't set a cookie

return view('welcome')->withCookie(cookie('test', 'test', 45000));

This does

$response = new \Illuminate\Http\Response('Test');
$response->withCookie(cookie('test', 'test', 45000));
return $response;
troelsjohnsen's avatar
troelsjohnsen
OP
Best Answer
Level 1

I ended up doing this

 use Illuminate\Cookie\CookieJar;
 public function index(CookieJar $cookieJar, Request $request)
 {
     if($request->referrer){
        $cookieJar->queue(cookie('referrer', $request->referrer, 45000));
     }

     return view('welcome');
 }

This also worked

$response = new \Illuminate\Http\Response(view('welcome'));
$response->withCookie(cookie('referrer', $request->referrer, 45000));
return $response;

But the other solution looks cleaner. Thanks for your help :-)

7 likes
scalerboy's avatar

I believe you can just queue it.

Cookie::queue(Cookie::make('name', 'value', 'minutes'));

And on the next response the cookie will be added automagically.

9 likes
usamarauf93's avatar

use this code

public function index(CookieJar $cookieJar, Request $request) { if($request->referrer){ $cookieJar->queue(cookie('referrer', $request->referrer, 45000)); }

 return view('welcome');

}

Azik's avatar

namespace

use Illuminate\Support\Facades\Input;

use Illuminate\Http\Request; 

and function

public function regionCookie(Request $request)
{
        $region = Input::get('region');
        return redirect()->back()->withCookie(cookie('region', $region,10));;
}

1 like
eugenefvdm's avatar

@TROELSJOHNSEN - I loved your solution and used it as a foundation for an single page form where I wanted to upload CVs before the user was already registered. Using a cookie seemed the way to go and your queuing put me on the right track. Nice one!

1 like
jlndk's avatar

It is also possible to use the response helper method:

public function index()
{
    return response()->view('welcome')
                     ->withCookie(cookie('referrer', request()->referrer, 45000));
}

Please or to participate in this conversation.