Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Pyae's avatar
Level 1

Accessing php constant by javascript?

Can we access php constant value from external javascript file?

0 likes
4 replies
toby's avatar

No, not directly. PHP = server side; JS = client side.

However, you can echo/json_encode the value of your PHP variable inside a script block of your html/blade template and assign it to a JS variable

1 like
toby's avatar
toby
Best Answer
Level 31

First, you pass your PHP variable ($varToJs in the example) to a blade template (stored in resources/views/site/index.blade.php) like this:

// SiteController.php

namespace App\Http\Controllers;

class SiteController extends Controller
{
    public function index()
    {
        $varToJs = ['some', 'data', 'here', 123];

        return view('site.index', compact('varToJs'));
    }
}

Then you can get the content of $varToJs inside the template:

<!-- views/site/index.blade.php -->

<script>
    // like this...
    window.varFromPhpA = {!! json_encode($varToJs) !!};
    // or like this...
    window.varFromPhpB = @json($varToJs);
</script>

this will be rendered as:

<script>
    window.varFromPhpA = ["some","data","here",123];
    window.varFromPhpB = ["some","data","here",123];
</script>

You don't (and maybe shouldn't) assign the variable to the global window object though... it depends ;)

If you need this often, maybe take a look at Jeffrey's PHP-Vars-To-Js-Transformer package

Pyae's avatar
Level 1

Thank a lot. Now, i will test with that in my code. Have a nice day!

Please or to participate in this conversation.