javascriptphplaravelhelper

How can I access Laravel Helper from Javascript?


I have a Laravel web app and want to access my Laravel Helper from any .js file.

In normally I accessed helper from script in blade.php file like this:-

<script>
function getSiteSettings() {
    return JSON.parse('<?php echo json_encode(Helper::getSettings()) ?>');
}
</script>

But I want to access this from my script.js file. Is it possible? I have tried with localStorage and get it very easily but problem is, in site settings have some secured data.

And if possible to hide localStorage data then my problem will be solved.


Solution

  • I found the answer. Basically, there is no direct way to write PHP code in the .js file. Here is 3 short way to get PHP/Laravel variable or Laravel Helper.

    Solution 1. Call an ajax and get the return the value from js and use it as needed.

    $(function() {
         // ajax call
    });
    

    Solution 2. Any Laravel Helper/Var can be accessible from a blade file, like this:

    <script>
        let name = "{{ \Helper::get_name() }}";
    </script>
    

    and use this name anywhere in js.

    Solution 3. The last and best way which I have been using is: Add the external script in the blade and add a getter and setter method into the script so that you can set the value from the blade file inside the js.

    // in external/script.js script
    var GetLaravelHelper = function () {
        let options = {
            name_from_laravel : ''
        }
    
        return {
            init: function(){
                // code for on load
            },
            set_options: function(data){
                Object.assign( options, data );
            },
            get_options: function(){
                return options;
            }
        }
    }();
    
    window.GetLaravelHelper = GetLaravelHelper; // You can get acces this GetLaravelHelper into balde file where you imort this js
    
    document.onload(function(){
        GetLaravelHelper.init();
    })
    

    Then in blade, you can set any value into the Object like this:

    <script src="external/script.js"></script>
    <script>
       GetLaravelHelper.set_options({
            name_from_laravel: "{{ config('app.name') }}", // or anything from laravel/php
       })
    </script>
    

    BTW for Solution 3, remember that you are assigning value in global window.

    Hope it will help you a lot. Happy Coding <3