dtutlamjasblef7982
2018-10-22 15: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 16: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;
    
        }
    
    点赞 打赏 评论

相关推荐 更多相似问题