Laravel:根据Cookie值有条件地渲染模式

时间:2018-10-22 15:51:07

标签: php laravel

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

主页控制器:

public function inicio()
    {

        $show_modal = Modal::checkIfShowModal();

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

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

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,
        ]);

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

1 个答案:

答案 0 :(得分:0)

您不必在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;

    }