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
\Cookie::queue(\Cookie::forget('key'));

//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

<?php
use Illuminate\Support\Facades\Route;

Route::get('/set-cookie',function(){
   Cookie::queue("name", "readerstacks.com", 600);
  return "cookie set successfully";
});
Route::get('/delete-cookie',function(){
   \Cookie::queue(\Cookie::forget('name'));
  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

<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;


Route::get('/delete-cookie',function(){
    $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