L
L
Li2020-09-15 19:59:02
Laravel
Li, 2020-09-15 19:59:02

How to correctly add cookies to middleware?

Hello.

Add cookies to middleware

public function handle($request, Closure $next)
    {
        if (!$request->hasCookie('city')) {
            return $next($request)->cookie('city', 'testCity');
        }

        return $next($request);
    }


The cookie is added in the browser. Now in the template I'm trying to display

request()->city выдает null
$_COOKIE['city'] выдает testCity


What am I doing wrong, and how do I add cookies to request cookie ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kuznetsov, 2020-09-15
@cubaPro

Try this: and add to your method (in brackets) $request Request or like this:
$request->cookie('city');

use Illuminate\Support\Facades\Cookie;

$value = Cookie::get('name');

In general, there is docs: https://laravel.com/docs/8.x/requests#cookies

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question