Is there anyway I can pass session data from my laravel controller to a .vue file?
Please help.
PS: I am using laravel 5.4 and vuejs 2
You can pass strings and colllections to vue from blade templates like so:
<my-component :collection="{!! $collection->toJson() !!}" string=" {{ $string }}"></my-component>
Just remember to add the corresponding props to your MyComponent.vue file.
props: ['collection', 'string']
So more specifically if you intend to use a the values from Laravel session('key', 'default') then you have to be sure that you know whether you need to json encode an object or array or if you are passing just a string value.
first of all you need to construct a method from your controller and ajax request it and catch him from vue method.
Example: from your controller :
function mysession(){
return session()->all()}
from your vue will like this like call this method when mounted() or ready
var self = this
$.get('mysession',function(response) {
self.sessionsData = response; }
after this execution sessionsData will now hold your sessions objects came from your controller.
I had the same problem; unfortunately, I couldn't pass the session data from a controller, but managed to pass session data in another way.
NOTE: I used Laravel 9 and Vue 3
Add the following to your router/web.php file; in this case, I'm returning an array that contains a user id and username taken from the current session.
Route::get('session', function () {
return [
'user_id' => session()->get('account_id'),
'username' => session()->get('username')
];});
Afterwards, put the following in your Example.vue's script tag and use the 'session' variable however you like.
data: function() {
return {session: []}
},
mounted(){
this.loadSession
},
methods:{
loadSession: function (){
axios.get('session')
.then( (response) => {
this.session = response.data;
})
.catch(function (error){
console.log(error);
});
},
}
Quick explanation of the code:
This may not be the best solution, but it works. There might be a better solution out there though.