Laravel 5.8 + Vue2JS Session and Old values in component - laravel

I have question about normal laravel multi form with post action as method based on laravel session. I added in this form component of vue, which is simple city autocomplete. I want load to inputs into fields of this component from session (session()), or old (old()) values, if session exist i want to load from session city and province, but if session doesnt exist, but old laravel values exist I want to load them in this component form, if they doesnt exist, leave fields empty. What's the easiest way to do that?

Get the session and pass a default which would be the old value.
$data = session('session_data_key', $old_value); // however you get the old value is up to you.
Pass it down to your view. If no session is set on the server, it will use the default (if default is null it will not set the auto-complete).
UPDATE
If you are using axios to make calls to a laravel app, before loading the form component (in mounted() {}) do a call to axios to get the value of (session or old value). This is what you'll load into the form.
axios.get('/api/load_dafault').then(resp => {
this.defaultValueToBePassedToField = resp.data.value;
});
The endpoint '/api/load_dafault' or whatever yours is named, will have it's controller like so:
public function loadDefaults()
{
$old_value = ... // however you get it is up to you.
$data = session('session_data_key', $old_value);
}
Do not forget to ensure you set the routes.

Related

Good practices to manage user session data with vue and laravel API

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?
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.

View Share doesn't return updated data, how then to share live data?

I currently have a model which access data like so:
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
return view('layouts.cart')->with('cartDetails', $displayCart);
This model correctly retrieves the data in a current session.
To access this same data in a header file I'm using View::Share in the AppServiceProvider like so:
public funciton boot()
{
$currentSessionID = session()->getId();
$inCartDetails = Cart::where('session_id', $currentSessionID)->get();
View::share('inCartDetails', $inCartDetails);
}
In my blade the $inCartDetails returns empty. I get [].
My suspicion is that this function ONLY gets called at boot. Hence the name :) and that it's empty cause at the time of starting the session it's empty since user hasn't selected anything. If this is correct how would I then pass live data to multiple views?
The session is not available in the boot method of the service providers. You should create a middleware for this. Check out this answer here: How to retrieve session data in service providers in laravel?

How do I set initial vuex state in Laravel?

I have the data I am looking for in a controller and need to set some state in vuex. Do I need to make a second database request, or is there some way for me to pass the value from my controller to vuex?
I am trying to pass the value down as props and change a null state, but when I change the state, the value is still being passed down.
Is there a way to pass the value from the controller to vuex, or do I have to double my requests and make 2 calls just to load the same data?
You can do a second query to fetch the initial state OR get these values through window.App (or whatever).
window.App = {
initialState: {{ !empty($myInitialState) ? json_encode($myInitialState) : '' }}
};
In Vue.js, update the initial vuex state using window.App.initialState;
created () {
this.$store && this.$store.dispatch('SET_INITIAL_STATE', window.App.initialState || {})
}

Sharing root data with router-view component vue js

Best to give more context to this first.
I am creating an Single Page Application with vuejs, vue-router. When the user logs in the user object is returned from the backend. I am using Laravel 5.4 for the backend. The user object is then sorted on the vue $root instance so it can be accessed anywhere by using this.$root.user.
My only problem is that when I want to edit the user data, I have an edit form in which the user data should be automatically populated with the existing data. This would be fine if I just wanted to do something like this: v-model="this.$root.user.first_name" but I have a form object which helps with validation and making everything more modular.
So in the data return I have this on the router-view component:
data: function() {
return {
form: new Form({
first_name: this.$root.user.first_name,
last_name: this.$root.user.last_name,
country: this.$root.user.country,
preffered_currency: this.$root.user.preffered_currency,
email: this.$root.user.email,
})
}
}
The only problem is that everything is undefined. I'm not sure how to get around the problem so any help which be appreciated. Thanks.
I figured a way to do it.
What I forgot to add is that on refresh of the page obviously vue forgets about all of the current stored data so because of that I have to make a request to the backend to get the current user.
So when the ajax request is made to get the current user I created a new Vue object in which all objects can see and assigned it to Window.Event and created a new Vue instance against that. Window.Event = new Vue({});
Now once the ajax request has returned I did Window.Event.$emit('user', this.user) and on the component which needed the user data I just created an $on event with create().
created() {
Window.Event.$on('user', function(user){
this.form.first_name = user.first_name
this.form.last_name = user.last_name
this.form.country = user.country
this.form.preffered_currency = user.preffered_currency
this.form.email = user.email
}.bind(this));
}

Codeigniter paypal_lib->ammount from form?

I need to get the quantity of items from a form and pass that to CI's paypal_lib auto_form:
This is my controller:
function auto_form()
{
$this->paypal_lib->add_field('business', 'admin_1261513315_biz#pixelcraftwebdesign.com');
$this->paypal_lib->add_field('return', site_url('home/success'));
$this->paypal_lib->add_field('cancel_return', site_url('home/cancel'));
$this->paypal_lib->add_field('notify_url', site_url('home/ipn')); // <-- IPN url
$this->paypal_lib->add_field('custom', '1234567890'); // <-- Verify return
$this->paypal_lib->add_field('item_name', 'Paypal Test Transaction');
$this->paypal_lib->add_field('item_number', '001');
$this->paypal_lib->add_field('quantity', $quant);
$this->paypal_lib->add_field('amount', '1');
$this->paypal_lib->paypal_auto_form();
}
I have a library of my own that validates the input and redirects to auto_form on validation. I just need to pass the var $quant to the controller.
How can I achieve this?!
If you're redirecting directly to the auto_form controller method you can setup an argument there to pass your data in:
auto_form($quant)
Then, depending assuming you have no routes, rewriting, or querystrings 'on' (basically a stock CI setup) to interfere, and you are using the URL helper to redirect, you would do your redirect something like this:
redirect('/index.php/your_controller/auto_form/'. $quantity_from_form);
More on passing URI segments to your functions here.
Or if you're already using CI sessions in your application you can add the quantity value to a session variable for later retrieval inside of the auto_form controller method:
// Set After Your Form Passed Validation
$this->session->set_userdata('quant', $quantity_from_form);
// Retrieve Later in Controller Method After Redirect
$this->paypal_lib->add_field('quantity', $this->session->userdata('item'));
More on CI sessions here.

Resources