spatie/laravel-blade-javascript
Adds a simple @javascript Blade directive to export PHP values to JavaScript by writing them to window in a script tag. Use @javascript('key','value') and access it in the browser as key/value for quick server-to-client data sharing.
Install via Composer: composer require spatie/laravel-blade-javascript. No manual service provider registration needed—the package auto-registers. Begin by exporting a simple variable in a Blade template: @javascript('appUrl', url('/')). When the page renders, this outputs <script>window['appUrl'] = 'https://your-app.com';</script>, making appUrl globally accessible in client-side JS. Check the config at config/blade-javascript.php (publish with php artisan vendor:publish --provider="Spatie\BladeJavaScript\BladeJavaScriptServiceProvider" --tag="config") to set a JS namespace (e.g., 'namespace' => 'app' scopes variables under window.app.key).
Use @javascript in any Blade file—typically inside a layout (e.g., resources/views/layouts/app.blade.php) near the top of the <head> or just before </body>. Pass a single associative array to export multiple vars at once: @javascript(['csrfToken' => csrf_token(), 'currentUser' => auth()->user()->only(['id', 'name'])]). For security-sensitive data (e.g., user details), always filter data with only() or transform() to avoid leaking unnecessary fields. Leverage the namespace config to prevent global pollution and name collisions across modules. If using CSP, publish and edit the default view (resources/views/vendor/bladeJavaScript/index.blade.php) to inject a nonce: <script nonce="{{ csp_nonce() }}">...</script>.
@javascript before any inline scripts that depend on these variables; otherwise, the variables won’t be defined yet.<script> blocks. If variables are missing, verify the directive is included outside of @push/@stack blocks, as rendering order may be altered.'["a","b"]'). Always wrap non-primitives in json_encode() or use @javascript(['user' => (object)$user]) to ensure proper parsing.defer, async, or type attributes (e.g., type="module" for modern bundlers), though this may require adjusting how JS consumes the globals.How can I help you explore Laravel packages today?