So I'm making navbar with vue and i need to get my app name as my navbar brand, how can I do that?
3 Answers
You can set your variables in your blade template to use them in JS.
<script type="text/javascript">
window.your_scope = window.your_scope || {};
your_scope.data= '{{env('VALUE')}}';
console.log(window.your_scope.data);
</script>
Check this package https://github.com/laracasts/PHP-Vars-To-Js-Transformer
4 Comments
killstreet
This package was made to set JS variables inside your controller, not your blade file.
Mtxz
This package will, from your controller, put variables in your DOM, using a blade template you can specify.
killstreet
The OP is using vueJS, next to that, you are re-defining your variables since the package is handling this already. In the controller you will define the variable name that you use in your JS. As per your example you are re-defining the same values to other variables. Seems like a dodgy way of using it.
Mtxz
Yes, of course, you should no use both. The package uses the same principle, that I wanted to explain. As it's a quite simple method, it can be done without the said package easily. VueJS or not, principle is the same and can be adapted. It's to me the only way to pass variable from PHP to JS without using asyncrone request of any sort: the DOM.
Pass the env to javascript variable like this
<script>
var APP = {
"name": "{{env('APP_NAME')}}",
"url": "{{env('APP_URL')}}"
}
</script>
You can access as object APP.name or APP.url
1 Comment
Ardy Febriansyah
Where you place this script?
You can access env variables form vue files like this:
data() {
return {
appName: import.meta.env.VITE_APP_NAME,
}
},
as seen in app.js by default:
const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
1 Comment
mafortis
Yes nowadays that Laravel uses vite this code works but in time of question (2018) we were supposed to add new variable like
MIX_APP_NAME.