0

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']);

Config/session.php

<?php

use Illuminate\Support\Str;

return [

    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => env('SESSION_LIFETIME', 120),
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => env('SESSION_CONNECTION', null),
    'table' => 'sessions',
    'store' => env('SESSION_STORE', null),
    'lottery' => [2, 100],
    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),
    'path' => '/',
    'domain' => env('SESSION_DOMAIN', null),
    'secure' => env('SESSION_SECURE_COOKIE'),  //also tried adding false to this
    'http_only' => true,
    'same_site' => 'lax',
];

.env file

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file       //tried changing this to database also
SESSION_LIFETIME=120
SESSION_DOMAIN=mydomain.com
SESSION_SECURE_COOKIE=false
  • (Unrelated) fyi: Api routes in Laravel are stateless, they don't use cookies/sessions – brombeer Apr 06 '22 at 06:31
  • @brombeer ok.Can you tell why i can't get the session value or y i can't set the cookie? –  Apr 06 '22 at 06:33
  • Another fyi: the _facade_ for cookie is `Illuminate\Support\Facades\Cookie`. You don't need those if you use `$request->session()` or `$request->cookie()` – brombeer Apr 06 '22 at 06:37
  • @brombeer i know that. But that's not the error here, know? –  Apr 06 '22 at 06:41

2 Answers2

1

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']);

Edit: for session access use this Controller:

<?php

namespace App\Http\Controllers;

class AuthController extends Controller
{
    public function getSession()
    {
        $value = session('access_token');
        return $value;
    }

    public function login()
    {
        session(['access_token' => 'abcde']);
        return redirect('/getSession');
    }

}

with these routes:

Route::get('/signin', [App\Http\Controllers\AuthController::class, 'login']);
Route::get('/getSession', [App\Http\Controllers\AuthController::class, 'getSession']);

Again, head to /signin, a session will be set and you'll be redirected to /getSession, which prints out abcde.

brombeer
  • 8,716
  • 5
  • 21
  • 27
  • no. it's not returning any value still –  Apr 06 '22 at 08:10
  • It does on my end, I tested it before posting (Linux, Laravel Framework 8.83.0). Did you enable cookies in your browser? Does a cookie show up in your browsers DevTools? Any cookie-blocker-addons running in your browser? Any errors/notices in your DevTools console about cookies? How do you serve your project? Apache? `php artisan serve`? – brombeer Apr 06 '22 at 08:20
  • @no errors in console. running server with `php artisan serve`. I can see laravel's default cookies are beings stored in the local storage.If cookies are not enabled, how it happens? And with `session->all()` , am able to get the laarvel default session. –  Apr 06 '22 at 14:04
  • But not getting the session i set –  Apr 06 '22 at 14:16
  • @user17189691 I edited my question and added a working controller using the session along with routes. Serving via `php artisan serve`. If this doesn't work for you you might want to check your Laravel session settings, cookie settings in your browser or try a different browser – brombeer Apr 06 '22 at 18:19
  • Cookies are stored in LocalStorage? That shouldn't be – brombeer Apr 06 '22 at 18:20
  • i tried ur new answer also. it also not working for both cookies & session.It was a typo in my last comment. cookies are not stored in local storage. it's stored under the cookies folder of storage section in application tab. –  Apr 06 '22 at 19:07
  • I've updated the original question body with my session settings. please have a look . –  Apr 06 '22 at 19:14
0

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,
    ],
];
  • i've commented `\App\Http\Middleware\VerifyCsrfToken::class,` - this line in my kernal.Otherwise, it shows `419 page expired error` on form submission. except that, i tried this answer(it's also not working. brings Same situation mentioned in question ) –  Apr 06 '22 at 14:21
  • Maybe this answer can help: https://stackoverflow.com/a/59037903/12503693 – Mirafzal Shavkatov Apr 07 '22 at 04:39