I try to set a Cookie in Laravel 4 in a specific route.
Unfortunately, setting the Cookie does only work in the global App::after() filter.
First thing I tried was returning a response with a Cookiefrom my Controller.
This doesn't work:
return Response::make($view)->withCookie(Cookie::make('foo','bar'));
However, this does:
return Response::make()->withCookie(Cookie::make('foo','bar'));
But does not solve my problem.
Next I tried it with an after filter as follows.
Route::filter('cookie', function($route, $request, $response)
{
$response->withCookie(Cookie::make('foo', 'bar'));
});
This does not work either.
Next, I tried it using Cookie::queue(), which I've found in another answer - with no luck.
The only place the Cookie is set properly is in App::after().
App::after(function($request, $response)
{
$response->withCookie(Cookie::make('foo', 'bar'));
});
Besides I'm pretty sure that one of the other approaches should work, this solution doesn't give me the control I'm looking for.
I'm running Laravel v4.0.9.
Try this tested, working code.
Specify expiration time (in minutes from now). Dont you use some cookie extension in your browser, which may protect/blacklist specified cookies from being modified...
Route::get('cookieset', function(){
$cookie = Cookie::make('foo', 'bar', 60);
return Redirect::to('cookieget')->withCookie($cookie);
});
Route::get('cookieget', function(){
dd(Cookie::get('foo'));
});
Related
I'm currently building a REST API with Laravel Lumen 8. I want to set a cookie if the user logged in successfully. I saw that in the Lumen 5.1 docs there was a section that showed how to send a cookie with the response (https://lumen.laravel.com/docs/5.1/responses#attaching-cookies-to-responses). But in the documentation for version 8 this section is missing. I also looked into the Laravel 8 docs (https://laravel.com/docs/8.x/responses#attaching-cookies-to-responses) and tried the following things in my routes/web.php file:
Attempt 1
$router->get('/test', function () {
return response('Hello World')->cookie(
'name', 'value', 60
);
});
But then I get the following error:
Argument 1 passed to
Symfony\Component\HttpFoundation\ResponseHeaderBag::setCookie() must
be an instance of Symfony\Component\HttpFoundation\Cookie, string
given
Attempt 2
use Illuminate\Support\Facades\Cookie;
$router->get('/test', function () {
Cookie::queue('name', 'value', 60);
return response('Hello World');
});
Error message: Target class [cookie] does not exist.
Attempt 3
$router->get('/test', function () {
$cookie = cookie('name', 'value', 60);
return response('Hello World')->cookie($cookie);
});
Error message: Call to undefined function cookie()
Attempt 4
use Symfony\Component\HttpFoundation\Cookie;
$router->get('/test', function () {
return response(null)->withCookie(new Cookie('name', 'value'));
});
This solution works, but if i set the third parameter like this new Cookie('name', 'value', 60), I don't get an error message but the cookie doesn't get set anymore.
And I'm also a bit sceptical because I never saw this in any official docs but only in this stack overflow question: Set cookie on response in lumen 5.6.
These weren't the only things I tried but nothing worked so far. Setting a cookie should be such an easy thing but I just can't achieve it. I'm pretty new to Laravel/Lumen, has it something to do with the new Version 8? Or what else am I doing wrong?
I've had the same issue, this is not pretty but it fixed it for me.
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
...
$response = new Response();
$response->headers->setCookie(Cookie::create('foo', 'bar'));
$response->send(); // <- this guy
In case you are using the jwt-auth library by Sean Tymon for JSON Web Token Authentication, this Thread may help you: https://github.com/tymondesigns/jwt-auth/issues/1594#issuecomment-395575980
Cited from the thread:
The root of the culprit I guess is that Lumen by design no longer does
cookies which I find a bit of a flaw in the light of all the blogs and
OWASP suggestions of not storing a JWT in localstorage but rather in a
httponly cookie to prevent XSS and deal with CSRF accordingly. So, the
jwt-auth doesn't include the cookie parser with the
LumenServiceProvider which is what you register in app.php as a
service provider:
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
So when you add
use Tymon\JWTAuth\Http\Parser\Cookies;
to the top of jwt-auth\src\Providers\LumenServiceProvider.php
and add
new Cookies($this->config('decrypt_cookies'))
into the array at the very end of the file
$this->app['tymon.jwt.parser']->setChain([<br>
new AuthHeaders,
new QueryString,
new InputSource,
new LumenRouteParams,
new Cookies($this->config('decrypt_cookies')),
]);
then you should be able use the cookie authentication in Lumen as
well.
I've been using Laravel from command prompt in Windows 10, but the difficulty of switching between projects has made me switch to using Homestead. However, in a new project I have started there, I can't for the life of me get cookies to persist.
Here is my current code (for debugging this problem only):
use Illuminate\Support\Facades\Cookie;
// ......
public function __construct(Request $request) {
$customer_id = Cookie::get('customer_id');
if(!$customer_id) {
Cookie::queue('customer_id', time(), 3600);
}
dd($customer_id);
}
Expected output: On consecutive page loads, the visitor will see the same unix timestamp they initially opened the page at (I understand this is not a good way of handling it, again, this is just for reproducing the error.)
Reality: Every pageload will produce a different timestamp.
I've looked up as many discussions as I could find. Solutions that I tried:
Using the Route method of declaring cookies
Using good-old PHP setcookie
Using Cookie:make, and Cookie:forever
Adding 'customer_id' in the exceptions among EncryptCookies
Placing the route in the web middleware
Erasing php artisan cache, restarting vagrant
Making the session folder editable through chmod
Yet still, after applying all the above, the cookie is still gone after every page load.
Since I had no prior problem like this through Xampp's PHP, I have to assume there is a (hopefully) trivial and obvious problem with Vagrant that I don't yet know. Any advice is appreciated!
Queued cookies are only sent with responses, so be sure that your controller function does return one.
use Illuminate\Support\Facades\Cookie;
// ......
public function __construct(Request $request) {
$customer_id = Cookie::get('customer_id');
if(!$customer_id) {
Cookie::queue('customer_id', time(), 3600);
}
}
public function foo() {
...
return response('some text');
}
Also, if using some kind of api you have to add a middleware to include the cookies on the response. See Laravel 5.4 - Cookie Queue
I am trying to queue various cookies in response in Lumen.
I've added \Illuminate\Cookie\ into my Composer.
I added Following code in app.php
$app->singleton('cookie', function () use ($app) {
return $app->loadComponent('session', 'Illuminate\Cookie\CookieServiceProvider', 'cookie');
});
$app->bind('Illuminate\Contracts\Cookie\QueueingFactory', 'cookie');
In My Controller, I am trying the following code
Cookie::queue(Cookie::make('test', 'tada', 10, '/'));
//Few more business logic here: before returning the response
$response = new \Illuminate\Http\Response('exit');
return $response->withHeaders($headers);
I can see my queued cookies using Cookie::getQueuedCookies()
but still, after a response, my cookie is nowhere to be found.
I tried various answers from StackOverflow questions but still couldn't resolve it
I can't use response()->withCookie() solution because I am creating cookies at various points of my code, and can't pull them together at the time of response
Queued cookies in Laravel are handled by the \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse class.
It begs the question why you'd use Lumen if you wanted cookies support but you should be able to add this middleware to your HTTP stack in Lumen.
I used Swagger to generate a Slim framework for a server. Without editing anything, I am testing the basic functions. I have one located at /user/login. Here is the script I have for it:
$app = new Slim\App();
$app->POST('/user/login', function($request, $response, $args) {
$queryParams = $request->getQueryParams();
$username = $queryParams['username'];
$password = $queryParams['password'];
$response->write("Will not work");
return $response;
});
$app->GET('/user/{user_id}', function($request, $response, $args) {
$response->write('Works');
return $response;
});
However, when I try to POST to the url using Postman (chrome app), it results in a 500 error. If I try any of the GET methods, it works. It only seems to be happening with the POST methods.
I have it running on an Ubuntu machine, with Apache2 installed with PHP. I have updated everything to the latest available versions. ModRewrite is enabled, and the override is set to all. Please help! I am at such as loss at this point.
I found the error.
Notice that I have two urls, one at /user/login and /user/{user_id}, because of the two starting /user urls, it confuses and doesn't know which to use, resulting in a 500 error.
Switching the /user/login to /login corrected the issue.
I feel stupid for not knowing that would happen.
I am having an issue trying to make a GET request to a route and process the parameters passed in via the URL. Here are two routes I created in routes.php:
$router->get('/', function() {
$test = \Input::get('id');
dd($test);
});
$router->get('test', function() {
$test = \Input::get('id');
dd($test);
});
When I go to the first URL/route ('/') and pass in some data, 123 prints to the screen:
http://domain.com/dev/?id=123
When I go to the second ('test') NULL prints to the screen (I've tried '/test' in the routes.php file as well).
http://domain.com/dev/test?id=123
A few things to note here:
This installation of Laravel is in a subfolder.
We are using Laravel 5.
Any idea why one would work and the other would not?
First thing - Laravel 5 is still under active development so you cannot rely on it too much at this moment.
Second thing is caching and routes. Are you sure you are running code from this routes?
Change this code into:
$router->get('/', function() {
$test = \Input::get('id');
var_dump($test);
echo "/ route";
});
$router->get('test', function() {
$test = \Input::get('id');
var_dump($test);
echo "test route";
});
to make sure messages also appear. This is because if you have annotations with the same verbs and urls they will be used and not the routes you showed here and you may dump something else. I've checked it in fresh Laravel 5 install and for me it works fine. In both cases I have id value displayed
You can use
Request::path()
to retrieve the Request URI or you can use
Request::url()
to get the current Request URL.You can check the details from Laravel 5 Documentation in here : http://laravel.com/docs/5.0/requests#other-request-information and when you did these process you can get the GET parameters and use with this function :
function getRequestGET($url){
$parts = parse_url($url);
parse_str($parts['query'], $query);
return $query;
}
For this function thanks to #ruel with this answer : https://stackoverflow.com/a/11480852/2246294
Try this:
Route::get('/{urlParameter}', function($urlParameter)
{
echo $urlParameter;
});
Go to the URL/route ('/ArtisanBay'):
Hope this is helpful.