Spread the love

In this article we will learn to delete cookies in laravel. In our last article we learnt to set and get cookies and how cookies are used to store the data in client computer, Cookie can hold tiny information in computer and can retrieve when required for same website. In laravel we can delete cookies using laravel inbuilt methods like forget and response()->cookie($cookie).

Cookies are not removed until we queue it or send it with response so we also need to call response methods or return proper response to close the connection.

we can use below method to set the cookie in laravel

//Method 1

//Method 2

$cookie = \Cookie::forget('key')
return response(view('viewa_path'))->withCookie($cookie); 

Let’s understand it with example

Method 1 : Set and get cookies

In this method we will delete cookies using the queue and cookie class to get the values so first create a route as follow

use Illuminate\Support\Facades\Route;

   Cookie::queue("name", "readerstacks.com", 600);
  return "cookie set successfully";
  return "cookie deleted successfully";

Method 2 : Set and get cookies using forget and response

In this method we will get and set cookies using the request and response method

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;

    $cookie = \Cookie::forget('name');
    return response(view('welcome'))->withCookie($cookie);

Route::get('/set-cookie',function(Request $request){
   $cookie = cookie('name', 'readerstacks', 600);
   return response(view("welcome"))->cookie($cookie);

Also Read : How to set and get cookies in angular using package ?

Leave a Reply