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.
So what part isn't working? Is it not saving test value in test cookie?
What does not work?
Maybe you could try the Cookie::make() method instead?
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;
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 :-)
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.
@scalerboy 's answer is completely correct as stated in the document: https://laravel.com/docs/5.2/responses#attaching-cookies-to-responses
<?php
namespace App\Http\Controllers;
use Cookie;
use App\Http\Controllers\Controller;
class DashboardController extends Controller
{
/**
* Show the application dashboard.
*
* @return Response
*/
public function index()
{
Cookie::queue('saw_dashboard', true, 15);
return view('dashboard');
}
}
use this code
public function index(CookieJar $cookieJar, Request $request)
{
if($request->referrer){
$cookieJar->queue(cookie('referrer', $request->referrer, 45000));
}
return view('welcome');
}
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));;
}
@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!
It is also possible to use the response helper method:
public function index()
{
return response()->view('welcome')
->withCookie(cookie('referrer', request()->referrer, 45000));
}
Please sign in or create an account to participate in this conversation.