Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and destroy cookie in Laravel 5.7?

Tags:

php

laravel-5

I am a novice in Laravel, I have made a simple hello program in Laravel and I want to use a cookie in my program. How do I create and delete a cookie in Laravel? Also, how do I set session in Laravel?

like image 411
Ajay Batham Avatar asked Dec 12 '18 06:12

Ajay Batham


People also ask

How can I set cookie in Laravel?

Creating a CookieCookie can be created by global cookie helper of Laravel. It is an instance of Symfony\Component\HttpFoundation\Cookie. The cookie can be attached to the response using the withCookie() method. Create a response instance of Illuminate\Http\Response class to call the withCookie() method.

How do I delete all cookies in Laravel?

For deleting multiple cookies at once you can simply do the following and of course you can put it in a loop: Cookie::queue(Cookie::forget('key1')); Cookie::queue(Cookie::forget('key2')); return $myResponse; By doing this, there's also no need to return your response with the cookie object anymore.

Where are Laravel cookies stored?

The session driver configuration option defines where session data will be stored for each request. Laravel ships with several great drivers out of the box: file - sessions are stored in storage/framework/sessions . cookie - sessions are stored in secure, encrypted cookies.

Are Laravel cookies secure?

Cookies & Encryption By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client.


1 Answers

Set cookie: Cookie::queue(Cookie::make('cookieName', 'value', $minutes));

Get cookie: $value = $request->cookie('cookieName'); or $value = Cookie::get('cookieName');

Forget/remove cookie: Cookie::queue(Cookie::forget('cookieName'));

Check if cookie exist: Cookie::has('cookiename'); or $request->hasCookie('cookiename') will return true or false

For more detail, you can refer to the documentation:

  • https://laravel.com/docs/5.7/requests#cookies
  • https://laravel.com/api/5.7/Illuminate/Contracts/Cookie/Factory.html
like image 53
Syamsoul Azrien Avatar answered Sep 20 '22 19:09

Syamsoul Azrien