Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amjadkhan896's avatar

Cookie setting in the middleware not working

Hi All,

I have a simple middleware where i want to set the country inside the cookie. The cookie is setting and i can view. But its not working for the first time. when the page loads. When i refresh the page at the second time. then it works. But first time not works. What is the issue. Any Help will be appreciated.. My code is

<?php

namespace App\Http\Middleware;

use Closure;
use Modules\Location\Entities\Country;

class CheckCountry
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->hasCookie('country'))
        {
            return $next($request);
        }

            // dd('ddd');
            $country = Country::where('service_supported', 1)->where('status', 1)->get();
            if($country->count()==1){
                $response = $next($request);
                return $response->withCookie(cookie()->forever('country', $country));
            }



    }
}

And My middleware group is

  /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [

            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
           // \App\Http\Middleware\SetLocale::class,
            \App\Http\Middleware\CheckCountry::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
0 likes
5 replies
Snapey's avatar
Snapey
Best Answer
Level 122

Cookies are only returned to the browser at the end of the request, so you can never set and read the cookie in the same request cycle.

I suggest if you find the cookie set then you read it and add it to the session. If not then you set the cookie, and also add it to the session. Then, wherever you would have used the cookie, you use the session instead.

amjadkhan896's avatar

@Snapey but if i use the session i have to change a lot of code in all controllers . Any other solutions. I don't want to do changes in all the controllers.

Snapey's avatar

I don't see a solution there - only the issue.

You could possibly set the cookie and then exit with a redirect back to the same page?

The problem with this will be that if the user has cookies disabled then they will just be stuck in a never ending loop - as opposed to always getting the same default language

i have to change a lot of code in all controllers

Does not sound very DRY

amjadkhan896's avatar

Thanks @Snapey it works only with the sessions. But now the problem is I will change all the controllers code :) And that was the main reason I was searching a method that i should not replace my code, But could not succeeded. Thanks once Again

Please or to participate in this conversation.