Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel localstorage item fetch in Controller

In Laravel,Is there any way to get localstorage items in controller.I want to return this items in view blade. My localstorage item looks like .

enter image description here

like image 616
Rana Avatar asked Jan 09 '18 12:01

Rana


People also ask

How can I get localStorage data in laravel controller?

I will suggest you to get the value from the localStorage with javascript using localStorage. getItem('myItem') and then store it as a cookie using document. cookie = "name=value" . You will now be able to access it from your laravel controller using $_COOKIE['cookieName'] .

How do I access localStorage in PHP?

You can access localstorage via PHP. You need to write some javascript that store localstorage value in COOKIE and you can use it using PHP. <script> var email = localStorage. getItem("email"); var d = new Date(); d.


3 Answers

I will suggest you to get the value from the localStorage with javascript using localStorage.getItem('myItem') and then store it as a cookie using document.cookie = "name=value". You will now be able to access it from your laravel controller using $_COOKIE['cookieName'].

Example:

Javascript

//define a function to set cookies
function setCookie(name,value,days) {
   var expires = "";
   if (days) {
       var date = new Date();
       date.setTime(date.getTime() + (days*24*60*60*1000));
       expires = "; expires=" + date.toUTCString();
   }
   document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

//get your item from the localStorage
var myItem = localStorage.getItem('myItem');
setCookie('cookieName', myItem, 7);

PHP

$myItem = '';

if(isset($_COOKIE['cookieName'])) {
    $myItem = $_COOKIE['cookieName'];
}
like image 76
Kamga Simo Junior Avatar answered Oct 16 '22 17:10

Kamga Simo Junior


You can pass them from javascript with some event. You cannot just retrieve them in controller, because its server side.

like image 21
Epsilon47 Avatar answered Oct 16 '22 17:10

Epsilon47


I will extend @kamgas answer

You could set it in a cookie instead of local storage, which will allow Laravel to read the cookie

To fetch the cookie with Laravel you should use:

Cookie::get('mycookie')

Since Laravel by default only allow Laravel to read Laravel encrypted cookies you will need to set an exception in the App\Http\Middleware\EncryptCookies middleware class

protected $except = [
    'mycookie',
];
like image 32
ii iml0sto1 Avatar answered Oct 16 '22 17:10

ii iml0sto1