laravel | How to access session array in JavaScript?

18,493

Solution 1

You should keep your PHP and Javascript code seperated. Use data attributes in your HTML and fetch the values in your Javascript code instead.

For example this HTML code (I use json_encode to support line breaks):

<body {{ Session::has('notification') ? 'data-notification' : '' }} data-notification-type='{{ Session::get('alert_type', 'info') }}' data-notification-message='{{ json_encode(Session::get('message')) }}'>
    // ...
</body>

Then in your JS file:

(function(){
    // Don't go any further down the script if [data-notification] is not set.
    if ( ! document.body.dataset.notification)
        return false;

    var type = document.body.dataset.notificationType;
    switch(type){
        case 'info':
            toastr.info(JSON.parse(document.body.dataset.notificationMessage));
            break;

        case 'warning':
            toastr.warning(JSON.parse(document.body.dataset.notificationMessage));
            break;

        case 'success':
            toastr.success(JSON.parse(document.body.dataset.notificationMessage));
            break;

        case 'error':
            toastr.error(JSON.parse(document.body.dataset.notificationMessage));
            break;
    }
})();

You can shorten your JS by doing this:

(function(){
    // Don't go any further down the script if [data-notification] is not set.
    if ( ! document.body.dataset.notification)
        return false;

    var type = document.body.dataset.notificationType;
    var types = ['info', 'warning', 'success', 'error'];

    // Check if `type` is in our `types` array, otherwise default to info.
    toastr[types.indexOf(type) !== -1 ? type : 'info'](JSON.parse(document.body.dataset.notificationMessage));

    // toastr['info']('message') is the same as toastr.info('message')
})();

Read more on: HTMLElement.dataset, Conditional (ternary) Operator

Solution 2

Instead of {{ Session::get('message') }}

try {{ Session::get('notification')->message }} and { Session::get('notification')->alert_type }} respectively.

Your session message returns the array, you will need to use the array keys to get the message not the keys directly.

Share:
18,493
Sapnesh Naik
Author by

Sapnesh Naik

Blog: https://kerneldev.com/

Updated on July 23, 2022

Comments

  • Sapnesh Naik
    Sapnesh Naik almost 2 years

    I am passing an array to a view from my controller.

    Here is the controller function:

    $notification = array(
                'message' => 'Welcome Admin!', 
                'alert_type' => 'success',
            );
    return redirect('/home')->with('notification', $notification);
    

    In my view:

    <script>
      @if(Session::has('notification'))//this line works as expected
    
        var type = "{{ Session::get('alert_type', 'info') }}";
       //but the type var gets assigned with default value(info)
        switch(type){
            case 'info':
                toastr.info("{{ Session::get('message') }}");
                break;
    
            case 'warning':
                toastr.warning("{{ Session::get('message') }}");
                break;
    
            case 'success':
                toastr.success("{{ Session::get('message') }}");
                break;
    
            case 'error':
                toastr.error("{{ Session::get('message') }}");
                break;
        }
      @endif
    </script>
    

    as you can see there's clearly something wrong with the way I am trying to access the array value in var type = "{{ Session::get('alert_type', 'info') }}";

    EDIT- 1 : I tried doing

    var type = "{{ Session::get('notification')->alert_type, 'info' }}";
    switch(type){
        case 'info':
            toastr.info("{{ Session::get('notification')->message }}");
            break;
    
        case 'warning':
            toastr.warning("{{ Session::get('notification')->message }}");
            break;
    
        case 'success':
            toastr.success("{{ Session::get('notification')->message }}");
            break;
    
        case 'error':
            toastr.error("{{ Session::get('notification')->alert_type }}");
            break;
    }
    

    but now I get an error saying

    Trying to get property of non-object (View: C:\xampp\htdocs\financetest1\resources\views\layouts\master.blade.php) (View: C:\xampp\htdocs\financetest1\resources\views\layouts\master.blade.php)

    can anyone please help me with this?

  • Sapnesh Naik
    Sapnesh Naik about 7 years
    okay But I get an error Trying to get property of non-object Here is what I did var type = "{{ Session::get('notification')->alert_type, 'info' }}";
  • Sapnesh Naik
    Sapnesh Naik about 7 years
    Thanks for showing me this way but your answer didn't work for me because I was passing an array into session. so I did {{ Session::get('notification')['message'] }} and It works (see my answer), I will try to do your way with this little correction