1

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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Pass session data from Laravel to Vue

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:

  1. Declare the session variable
  2. Once the vue component has been mounted, call the loadSession() function
  3. Use axios to get the data being returned from route/web.php/'session' and store the response in the session variable

This may not be the best solution, but it works. There might be a better solution out there though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.