首页 > 解决方案 > Laravel:根据 cookie 值有条件地渲染模式

问题描述

我试图根据是否设置了 cookie 来显示(或不显示)时事通讯模式,由于某种原因,$show_modal 总是返回 false。

主页控制器:

public function inicio()
    {

        $show_modal = Modal::checkIfShowModal();

        //dd($show_modal);
        
        return view('inicio.index', compact( 'show_modal'));
    }

这是我检查模态是否应该显示的方法:

模态的.php

public static function checkIfShowModal(){


        $modal = Modal::first();
        
        if($modal->isActive && Cookie::get('cookie_modal_1') !== false)
        {
            //cookie is set, don't show modal
            return false;
        }
        else if($modal->isActive && Cookie::get('cookie_modal_1') == true){
            //cookie isn't set, show modal then
            Cookie::queue( Cookie::make('cookie_modal_1', true, 60*24*7));
            return true;
        }



    }

在我的刀片模板中,我使用条件来显示渲染模式

@if($show_modal == true)
    @include('partials/modals/modal_fir')
@endif

模态迁移:

Schema::create('modals', function (Blueprint $table) {
            $table->increments('id');
            $table->longText('body');
            $table->boolean('isActive')->default(false);
            $table->timestamps();
        });
        //FILL MODALS TABLE WITH ONE MODAL
        DB::table('modals')->insert([
            'body' => 'Subscribete a nuestro boletín noticiario, recibe ofertas, noticias, eventos y articulos de nosotros',
            'isActive' => true,
        ]);

知道为什么模态永远不会出现

标签: phplaravel

解决方案


您不必在Modal.php. 尝试这个:

public static function checkIfShowModal(){

        $modal = Modal::first();
        //use != instead of !==
        if($modal->isActive && Cookie::get('cookie_modal_1') != false)
        {
            //cookie is set, don't show modal
            return false;
        }
        else if($modal->isActive && Cookie::get('cookie_modal_1') == true){
            //cookie isn't set, show modal then
            Cookie::queue( Cookie::make('cookie_modal_1', true, 60*24*7));
            return true;
        }
       //return default response, true or false (according to preference)
       return true;

    }

推荐阅读