Read cookies in Laravel Blade created in JS

谁都会走 提交于 2021-01-29 17:52:17

问题


I am beginner webdeveloper. I make my project in Laravel 7 and jQuery.

I create cookies in JavaScript (jQuery) and I need read it in Laravel Blade.

I have this code:

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self,function(){var r=e.Cookies,n=e.Cookies=t();n.noConflict=function(){return e.Cookies=r,n}}())}(this,function(){"use strict";function e(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)e[n]=r[n]}return e}var t={read:function(e){return e.replace(/%3B/g,";")},write:function(e){return e.replace(/;/g,"%3B")}};return function r(n,i){function o(r,o,u){if("undefined"!=typeof document){"number"==typeof(u=e({},i,u)).expires&&(u.expires=new Date(Date.now()+864e5*u.expires)),u.expires&&(u.expires=u.expires.toUTCString()),r=t.write(r).replace(/=/g,"%3D"),o=n.write(String(o),r);var c="";for(var f in u)u[f]&&(c+="; "+f,!0!==u[f]&&(c+="="+u[f].split(";")[0]));return document.cookie=r+"="+o+c}}return Object.create({set:o,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var r=document.cookie?document.cookie.split("; "):[],i={},o=0;o<r.length;o++){var u=r[o].split("="),c=u.slice(1).join("="),f=t.read(u[0]).replace(/%3D/g,"=");if(i[f]=n.read(c,f),e===f)break}return e?i[e]:i}},remove:function(t,r){o(t,"",e({},r,{expires:-1}))},withAttributes:function(t){return r(this.converter,e({},this.attributes,t))},withConverter:function(t){return r(e({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(n)}})}(t,{path:"/"})});

$(document).ready(function () {
    $('.cookies-box-close').click(function (e) {
        $('.cookies-box').removeClass('d-flex');
        $('.cookies-box').addClass('d-none');
        Cookies.set('hiddenCookiesSplash', '1', { expires: 30 })
    });

});

This code create cookies correctly.

Now I try check value in Laravel Blade:

@if (Cookie::get('hiddenCookiesSplash') != '1')
Is okey
@endif

But it's not working - laravel can't read vale from cookie :(

How can I repair it?


回答1:


Also, you should keep in mind that by default Laravel can only read cookies set by Laravel.

The Laravel automatically encrypts all cookies with Bcrypt. You can do one of the following:

  1. Use Laravel backend to create your cookies. (Recommended)
  2. Encrypt your cookie value with Bcrypt in order to Laravel read them.
  3. Disable Laravel cookie encryption, which should allow your Laravel application to read cookies from all sources. (Not recommended)

Sources:

1. Using Laravel to create cookies

2. Reading Laravel Bcrypt within Javascript

3. How to disabled Laravel Encryption



来源:https://stackoverflow.com/questions/63512387/read-cookies-in-laravel-blade-created-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!