How to check if a cookie is set in Laravel?


When you visit a web page it, usually generates text files that contain small pieces of data such as username and password, and stores them on the user’s browser. These are knowns cookies they used to identify user system and can be accessed by the web server or the client computer (on which they are stored).

  • The information stored in the cookies is specific to a web server.

  • Once you connect to a server a cookie is created labeled with a unique ID and stored in your computer.

  • Once a cookie is exchanged/stored in a client, and if you connect to the server again, it will identify your system based on the cookie stored.

  • This helps the server to to deliver a page personalized to a particular user.

Example 1

Following example creates a cookie and verifies if it is set.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Cookie; class UserController extends Controller { public function index(Request $request) { Cookie::queue('msg', 'cookie testing', 10); echo $value = $request->cookie('msg'); } }

Output

The output of the above code is −

Example 2

Another way to test if the cookie is set or not can be seen in the example below −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Cookie; class UserController extends Controller { public function index(Request $request) { Cookie::queue('msg', 'cookie testing', 10); return view('test'); } }

test.blade.php

<!DOCTYPE html> <html> <head> <style> body { font-family: 'Nunito', sans-serif; } </style> <head> <body class="antialiased"> <div> {{ Cookie::get('msg') }} </div> </body> </html>

Output

The output of the above code is −

Example 3

Using the hasCookie() method to test if the given cookie is set or not.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Cookie; class UserController extends Controller{ public function index(Request $request) { if($request->hasCookie('msg')) { echo "Cookie present"; } else { echo "Cookie msg is not set"; } } }

Output

Cookie present

Example 4

Another example to test cookie setting.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Cookie; class UserController extends Controller{ public function index(Request $request) { return view('test'); } }

Test.blade.php

<!DOCTYPE html> <html> <head> <style> body { font-family: 'Nunito', sans-serif; } </style> </head> <body class="antialiased"> <div> @if (Cookie::get('msg') !== false) <p>cookie is present.</p> @else <p>cookie is not set.</p> @endif </div> </body> </html>

Output

The output of the above code is −

cookie is present.

Updated on: 30-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements