Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with cookies in Laravel 5.2

I'm setting cookie on some click event. Then after storing value in cookie, I want to

  1. Check for existence of cookie
  2. Get cookie values

I have developed a function by referring Laravel official docs. Console shows that cookies have been set. But after that, I can not solve two point (mentioned in above list) for view(Blade Template). It always shows (Cookie::get('cookie.clients')) 'null'. But browser console displays that cookie . If anyone knows answer, it will be appreciated.

Here is my code.

Controller

use App\Client;
use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Repositories\ClientRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;

class ClientController extends Controller
{
    public function cookieadd(Request $request, Client $client)
    {
        $clients = [];
        if (Cookie::get('cookie.clients') != null)
        {
            $clients = Cookie::get('cookie.clients');
        }
        array_push($clients, $client);

        Cookie::forever('cookie.clients', $clients);

        return redirect('/client');
    }
}

View

@if (Cookie::get('cookie.clients') != null)
<p>cookie is set</p>
@else
<p>cookie isn't set</p>
@endif
like image 418
Akshay Vaghasiya Avatar asked Mar 22 '16 09:03

Akshay Vaghasiya


People also ask

How do I enable cookies in laravel?

Creating a CookieCookie can be created by global cookie helper of Laravel. It is an instance of Symfony\Component\HttpFoundation\Cookie. The cookie can be attached to the response using the withCookie() method. Create a response instance of Illuminate\Http\Response class to call the withCookie() method.

How do you check if cookies are set or not in laravel?

If you check out the Cookie class now you can use Cookie::has('cookieName'); class Cookie extends Facade { /** * Determine if a cookie exists on the request. * * @param string $key * @return bool */ public static function has($key) { return ! is_null(static::$app['request']->cookie($key, null)); } // ...

Where are laravel cookies stored?

The session driver configuration option defines where session data will be stored for each request. Laravel ships with several great drivers out of the box: file - sessions are stored in storage/framework/sessions . cookie - sessions are stored in secure, encrypted cookies.

What is Response() in Laravel?

Basic Response Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response.


2 Answers

You're creating a cookie object but you're not sending it with the response.

You can either, add it directly to your response in a controller

$cookie = Cookie::forever('cookie.clients', $clients);

return redirect('/client')->withCookie($cookie);

Or you can queue a cookie and use the AddQueuedCookiesToResponse Middleware to automatically add it to the Response.

Cookie::queue(Cookie::forever('cookie.clients', $clients));

return redirect('/client');
like image 138
Ben Swinburne Avatar answered Sep 28 '22 01:09

Ben Swinburne


Here's another perspective.

If I understood correctly you've used Javascript to set the cookie on the client side, and you want to pick it up on the server side.

Laravel encrypts its cookies and when you use $request->cookies() you get the decrypted values, and retrieving the cookies from client side doesn't pass the decryption process and we get nulls. I guess, I haven't been able to dig out the appropriate source code :)

You can still use the raw PHP $_COOKIE['cookie_clients'] to retrieve the cookie set by client. Notice, . is converted to _ by PHP (as seen on php.net).

Alternatively, you could add the name of the cookie of interest into $except in Http/Middleware/EncryptCookies.php, which will allow you to pick it up with the more Laravel approach of $request->cookie().

I'm sure there are many other ways of going around Laravel here, hopefully this gives you an idea of where to look if you don't like either approach. Good luck.

like image 41
D0mski Avatar answered Sep 28 '22 02:09

D0mski