user860511
user860511

Reputation:

Toastr to use Laravel session variables as alert messages

I am wanting to swap from Bootstrap alerts to Toastr alerts. My current working set up is:

@if (Session::has('flash_notification.message'))

     <div class="alert alert-{{ Session::get('flash_notification.level') }}">
         <button type="button" class="close" data-dismiss="alert" 
             aria-hidden="true">&times;</button>
         {{ Session::get('flash_notification.message') }}
     </div>

 @endif

But I'm now struggling on accessing Laravel's session variables within JS.

The actual JS working example is:

$(document).ready(function() {

    toastr.info('Page Loaded!');

    });

});

But, I want to use Laravel's session variables to include different messages and warning boxes:

@if (Session::has('flash_notification.message'))

    <script>
        $(document).ready(function() {

            toastr.options.timeOut = 4000;
            toastr.{{ Session::get('flash_notification.level') }}('{{ Session::get('flash_notification.message) }}');

        });
    </script>

@endif

I'm getting various errors such as unexpected ;. Any help would be hugely appreciated. Many thanks.

Upvotes: 4

Views: 6444

Answers (1)

Michael Pittino
Michael Pittino

Reputation: 2178

Since you are working in a blade-template you can output the content of a variable/function with {{ var/function() }}. If you want unescaped output you can use {!! var/function() !!}.

So the solution for your problem is, that you need to surround your php code with the {{ }} tags:

@if (Session::has('flash_notification.message'))

    <script>
        $(document).ready(function() {

        toastr.{{ Session::get('flash_notification.level') }}
        ('{{ Session::get('flash_notification.message') }}');

        });
    </script>

@endif

Upvotes: 3

Related Questions