Laravel Cookie returns null

Viewed 101

I am new to Laravel (version 8) and i am trying to figure out why my cookie is returning a null. I am setting up the cookie like this'

public function setCookies($value){
    $minutes = 60;
    $response = new Response('Hello World');
    $response->withCookie(cookie('name', $value, $minutes));
    return $response;

}

where $value is the string value of the cookie

and i am trying to get the cookie with this method

public function getCookies(Request $request) {
    $value = $request->cookie('name');

    return $value;
}

but the return value is always null. please let me know where i am going wrong

here are my routes

Route::get('/cookie/set','App\Http\Controllers\Cont@setCookies');
Route::get('/cookie/get','App\Http\Controllers\cont@getCookies');
2 Answers

you have to change code to this :

public function setCookie(Request $request){
  $minutes = 60;
  $response = new Response('Set Cookie');
  $response->withCookie(cookie('name', 'MyValue', $minutes));
  return $response;
}

You need to change the route to accept dynamic value. If you're sending values from url, then set the route to

Route::get('/cookie/set/{value}','App\Http\Controllers\Cont@setCookies');
Related