Home > Net >  I am stuck at Unable to set cookie or session Laravel
I am stuck at Unable to set cookie or session Laravel

Time:04-06

None of the below methods is setting cookie. i tried defining the route in Routes/api.php also.And in case of session,dd(session()->get('access_token')); inside the session_login() method immaediately after setting session gives data.But in index() method, it gives null data. I am able to use the Symfony\Component\HttpFoundation\Cookie facade only, when using the direct facade use cookie; it shows error undefined type.So, i couldn't try the cookie::queue()similarly for session also, not able to try with use session facade. that's why i've commented it in the below code.How can i fix this? i've already gone through many links in internet. Any help is much appreciated.

controller

use Symfony\Component\HttpFoundation\Cookie;
//use Cookie;
use Illuminate\Support\Facades\Session;
//use Session;

class AuthController extends Controller
{
    public function getCookie(Request $request){
        $value = $request->cookie('access_token');
        return $value;
     }
      public function login(Request $request)
    {
       $response = new Response();
       $response->withCookie(cookie('access_token','abcd',60));

       //Cookie::queue('access_token','abcd',60);

      //Cookie::queue(Cookie::make('access_token','abcd',60));  --shows error Call to undefined method Symfony\Component\HttpFoundation\Cookie::queue() 

       return redirect('/getCookie');
    }
   public function session_login(Request $request)
     {
       session(['access_token'=>$token]);
       return redirect('/');
     }
     public function index()
     {
       return session()->get('access_token');
     }
}

Routes/web.php

Route::post('/signin', [AuthController::class,'login']);
Route::get('/getCookie',[AuthController::class,'getCookie']);
Route::get('/',[AuthController::class,'index']);

CodePudding user response:

Use the Cookie facade and Cookie::queue() to set and Cookie::get() to get cookie values.

Stripped down (working) version of your controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cookie;

class AuthController extends Controller
{
    public function getCookie()
    {
        $value = Cookie::get('access_token');
        return $value;
    }

    public function login()
    {
        Cookie::queue('access_token', 'abcd', 600);
        return redirect('/getCookie');
    }

}

Head to /signin, a cookie access_token will be set with the value abcd. You'll be redirected to /getCookie, which will output abcd.

Routes used (routes/web.php):

Route::get('/signin', [AuthController::class,'login']);
Route::get('/getCookie',[AuthController::class,'getCookie']);

CodePudding user response:

In App\Http\Kernel:

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,
    ],

    'api' => [
        // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

In App\Providers\RouteServiceProvider:

 $this->routes(function () {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));
    });

In RouteServiceProvider web.php uses web middlewareGroup and api.php uses api middlewareGroup. So, web middlewareGroup includes session and cookie middlewares, which are respond to work with them.

So, if you want to you use sessions and cookies in api.php, you need to add session and cookie middlewares to api middlewareGroup:

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,
    ],

    'api' => [
        // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,

        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
    ],
];
  • Related