dtutlamjasblef7982 2018-10-22 07:51
浏览 45
已采纳

Laravel:根据cookie值有条件地渲染模态

I'm trying to display (or not) a newsletter modal according to if a cookie is set or not, for some reason $show_modal always returns false.

Main Page Controller:

public function inicio()
    {

        $show_modal = Modal::checkIfShowModal();

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

This is my method for checking if the modal should be shown or not:

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;
        }



    }

Inside my blade template I use conditional to show render modal

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

Modals migration:

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

Any idea why the modal never shows up

</div>

展开全部

  • 写回答

1条回答 默认 最新

  • dongtiao0279 2018-10-22 08:13
    关注

    You don't have to do a strict comparison in Modal.php. Try this:

    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;
    
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部