In this tutorial we will show you how to use cookie in Laravel, and you will learn to Set Get and Forget the cookie in Laravel. We can do that by checking if the cookie is exist or not.
Before we will show you how to get, set and delete all cookies in laravel, You should know what is cookie? can we eat that? nahh...
Cookies (HTTP cookies, web cookies, internet cookies, browser cookies) are tiny text files that web server generates and sends to a web browser and placed on user's web browser. In addition, cookies are used to track/identify return users in web application.
Today content you will learn in list below
Using Cookies::make()
to create or set cookies in Laravel, commonly three parameters required first is the key or name, the second value to store and expiry interval.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
public function index(Request $request)
{
$minutes = 5;
Cookie::queue(Cookie::make('key', 'any value', $minutes));
}
Anyway if you don't want cookie to be expired you can use Cookie::forever
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
public function index(Request $request)
{
Cookie::queue(Cookie::forever('key', 'value'));
}
Other ways you can attach cookie to response instance
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
public function index(Request $request)
{
$minutes = 5;
$cookie = Cookie::make('key', 'any value', $minutes);
return response()
->json(['success' => true])
->withCookie($cookie);
}
To check all cookie
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
public function index(Request $request)
{
$cookies = request()->cookie();
dd($cookies);
// Or use below
$cookies = Cookie::get();
dd($cookies);
}
To get specific cookie should pass the key or name.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
public function index(Request $request)
{
$value = Cookie::get('key');
echo $value;
// Or use below
$value = request()->cookie('key');
echo $value;
}
To destroy or deleted cookie, we use Cookie::forget('key');
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
public function index(Request $request)
{
Cookie::queue(Cookie::forget('key'));
}
Use Cookie::has()
is used to check cookie exists or not, which will return boolean value.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
public function index(Request $request)
{
if(Cookie::has('key'))
{
echo "Cookie exist!";
}
// Or use below check
if($request->hasCookie('key'))
{
echo "Cookie exist!";
}
}
Hope this short blog help you, please have a nice day!!
You might also like...
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him