Peter
Peter

Reputation: 2702

cookies in laravel 5.2 - how to read

Before the Laravel 5.2 I had a small snippet to get a value stored in a cookie:

In my view:

    @if(!Cookie::has('colorTheme'))
        <?php $colortheme = 1; ?>
    @else
        <?php $colortheme = Cookie::get('colorTheme'); ?>
    @endif

Now these methods don't work. When I use this snippet in L5.2

$cookie_colorTheme = request()->cookie('colorTheme','1');
    @if(!isset($cookie_colorTheme)) 
        <?php $cookie_colorTheme = '1'; ?>
    @endif
    <link rel="stylesheet" class='a' id='colortheme' href="{{asset('css/colortheme_'.$cookie_colorTheme.'.css')}}">

It also doesn't work, as the cookie is not in request - it is already stored on the user's computer.

My questions:

Thank you!

Upvotes: 2

Views: 404

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Your code looks ok, so maybe cookies are just empty. Try dd($_COOKIE) or something similar to understand what's going on.

To set default value, you can do this:

{{ $value = $request->cookie('name') ? $request->cookie('name') : 'default value' }}

or you can try to do this in a Blade template:

{{ $request->cookie('name') or 'default value' }}

Upvotes: 1

Related Questions