Passing data from laravel blade to vue.js Is it possible to pass some data from laravel blade to vue.js root instance?
It tried it with props but it doesn't work.
UPDATE: (What I tried)
myblade.blade.php
<div :searchresult="{{$variable->id}}"></div>
main.js
new Vue({
el: 'body',
props: ['searchresult']
});
When I check my VueConsole, it always says that searchresult is undefined.
Hi,
In order to pass Laravel variables to your views, you can use the JavaScript package: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
And then, you can do this in your controller:
JavaScript::put([
'user' => User::first()
]);
And use it in your vue instance:
// You now have a javascript user var:
console.log(user);
new Vue({
el: '#app',
data: {
user: user
}
});
Hope it helps!
Thanks for the nice trick. That worked ! :)
Yes you can do also this :
var vm = new Vue({
el: '#app',
data: {
searchresults: {!! json_encode($searchresults->toArray()) !!},
}
});
And in your view :
<div id="app">
<div v-for="result in searchresults">
@{{ result.name }}
</div>
</div>
And in your controller :
public function searchTopics()
{
// Let's suppose your research is about topics :
$searchresults = \App\topic::all();
return view('research', compact('searchresults'));
}
Here is what worked for me to pass an array ...
View:
<data :mydatas=mydatas ></data>
<script>
const app = new Vue({
el: '#app',
data: {
mydatas: {!! json_encode(&mydatas) !!},
}
});
</script>
Vue:
<template>
<select>
<option v-for="(item, index) in mydatas" :value=index>
{{item}}
</option>
</select>
</template>
<script>
export default {
props: ['mydatas']
}
</script>
Similar to the post of WUAmin:
If you don't want to add a additional script-tag, then you can use a vue-package I've created.
https://www.npmjs.com/package/vue-laravel-data
Maybe there could be bugs but first tests are working well.
@El_Matella your solution works like a charm. Thank you very much :D
I have to agree with @guillaume.caggia 's approach. Here's a refactored version using the new @json ($foo) Laravel directive. Subjectively, it just feels cleaner and works great given how Vue.js treats form input bindings using the v-model directive.
v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth.
<template>
<form>
<input id="email" type="email" v-model="userEmail" required>
</form>
</template>
<script>
const app = new Vue({
el: '#app',
data: {
userEmail: @json($user->email),
},
});
</script>
I use this method to transfer data in vue file. It's working perfect but issue is, All data display in view source.
How can I hide display data in view source?
If you don't want it all displayed in the source, you can pull such data using axios.
Please sign in or create an account to participate in this conversation.