How to use blade variables in JavaScript in Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents for Laravel articles
This article discusses how to use variables from Laravel's Blade in JavaScript.
Conclusion
I think it's a good idea to define variables in Blade and then write the additional JavaScript-related code in a separate JavaScript file.
test.blade.php
<script>
// Define the variable $posts used in Laravel's Blade as a variable in JavaScript
const posts = @json($posts);
</script>
// The subsequent processing is in a separate file
<script src="{{ mix('js/test.js') }}"></script>
Summary
That's all.
There are various ways to do this, but I think this approach can handle any pattern.
As long as you can define the variables, I think the rest is in the realm of JavaScript, so it would be good to search for JavaScript-related information.
For feedback or complaints, please contact me on Twitter DM.
That's it!
Related articles