Rainier laan
Rainier laan

Reputation: 1130

Laravel - Distinguish session by user_ID

I have a project where a logged in user can fill in some data. This data will then be stored in a session called "Main_settings". The way I do that is by doing this in my controller:

private $predefinedArray = ['user_id', 'city', 'postal_code', 'street_name',
                            'house_number', 'store_name', 'store_tel',
                            'store_hoo', 'vat_number'];

public function store(Request $request)
{
    foreach($this->predefinedArray as $value) {
        $request->session()->put('main_settings.' . $value, $request->input($value));
    }

   return redirect('themes');
}

I call the session variables by doing this in my view:

{{ session('main_settings.store_name') }}

If the user returns, His information will still be there, That's not the issue. The problem is, if John Doe logs in and starts filling in the form and then logs out. And Jane Doe logs in, The information that John Doe filled in will be displayed, While Jane Doe didn't even fill anything in yet.

Somehow I need to distinguish a session by a user ID so I can call the session of the logged in User in the view. How can I accomplish this?

The user_id is being sent WITH the form.

Thanks in advance.

Upvotes: 0

Views: 84

Answers (1)

Saiyan Prince
Saiyan Prince

Reputation: 4020

The problem is, if John Doe logs in and starts filling in the form and then logs out. And Jane Doe logs in, The information that John Doe filled in will be displayed, While Jane Doe didn't even fill anything in yet.

This is happening because you are not forgetting those values when John Doe logs out. If you would like to remove the inserted values when John Doe logs out, have a look at this.

Controller.php

private $predefinedArray = [
    'user_id', 'city', 'postal_code',
    'street_name', 'house_number', 'store_name',
    'store_tel', 'store_hoo', 'vat_number'
];

public function logout()
{
    session()->forget('main_settings');

    auth()->logout();

    return redirect('/');
}

This should help you achieve the result.


If, for any reason, you want to retain the values in the session, you can do the following:

public function store(Request $request)
{
    foreach($this->predefinedArray as $value) {
        session()->put(auth()->id().'.main_settings.' . $value, $request->$value);
    }

   return redirect('themes');
}

By adding auth()->id(), you have persisted in the session, the user's id and the settings that he inserted while filling the form. This in turn will help the logged in user, because they then don't have to fill all the details again.

Hope this helps you out. Happy Coding. Cheers.

Upvotes: 1

Related Questions