Reputation: 2202
I am building a single-page application
with Vue
and laravel
API as backend.
I've tried some packages
like Vue Session and it worked well, however in almost every API
call I always need to send 2 or 3 parameters that will always be the same (stored in vue-session
), like user_id
and company_id
. I used to manage this with common PHP sessions
(Zend_Session
with Zend Framework
) in my other applications, this way I always have that information stored in my backend
session
and don't need to send it every time by the frontend
Here's an example of how I used to do it with PHP session
$model->insert(array(
'user_id' => $this->session->user_id, //stored in session
'company_id' => $this->session->company_id, //stored in session
'field1' => $this->getParam('field1'), //frontend param (ajax)
'field2' => $this->getParam('field2') //frontend param (ajax)
));
And here's how I'm doing it with Vue
and Laravel
const data = {
user_id: this.$session.get('user_id'), //this is what i'm trying to get rid of
company_id: this.$session.get('company_id'), //this is what i'm trying to get rid of²
field1: this.field1,
field2: this.field2
}
axios
.post('/api/some/endpoint', this.data)
.then(resp => {
//...//
})
Basically, in this example I want to not need to always send user_id
and company_id
as a post
param
.
Is there any way to get better code "reuse" in cases like this?
Upvotes: 4
Views: 2797
Reputation: 8726
1, You can save your session data in the cookie. The browser will automatically send your cookie to the server. Don't forget to delete the cookie when the user logout.
2, If you still want to use Vue session or other storages, you can easily create a method that wraps your post method and add user's information to the payload
function postRequest(url, payload) {
payload.user_id = this.$session.get('user_id')
payload.company_id = this.$session.get('company_id')
return axios.post(url, payload)
}
Use this method whenever you want to make a post.
Upvotes: 1