Transferring anonymous session data and restricting it to an authenticated user

Currently, session data for anonymous (not authenticated) users of my web application is not moved / assigned to the user after they log in or register.

For example: an anonymous user interacts with the application, creates some session data (for example, products in a shopping cart), then registers / registers and then logs out, session data is still available and does not move / become inaccessible to an unauthorized user.

I am using a file session driver (without a database), maybe someone can provide an example of what needs to be changed (I suppose in the session configuration) to make any session data created by an anonymous user assigned and only available to this user after their authentication by logging in or registering and only during user authentication.

The requirement for this is that application users create unique objects (tied to their user_id), which are saved only after payment, when order processing is performed. I store them in the session until the user logs in / logs in and completes the final order phase, and only after that they will be saved. Thus, I absolutely cannot have user objects stored in unidentified sessions after the user logs out. I could disconnect the session when I logged out, but ideally I want to save them when the user logs in again.

+4
source share
1 answer

. , Laravel , , , . , .

:

  • - , , - , , cookie , .

  • , Laravel , , . , . , , , . , :

1. , SyncShoppingCart, Illuminate\Auth\Events\Login ( \\ ):

php artisan make:listener SyncShoppingCart --event=Illuminate\\Auth\\Events\\Login

2. app/Listeners SyncShoppingCart.php. handle . , cart_item, , , CartItem, . , , :

public function handle(Login $event)
{
    // Iterate over the session cart items and 
    foreach (session()->get('cart') as $item) {
        $cartItem = new App\CartItem();

        // Set the user ID for the cart item so you know
        // which user added this item to the cart
        $cartItem->user_id = Auth::id();

        // Set the product ID and any other properties
        // you want stored for the cart item
        $cartItem = $item->product_id;
        // ...

        // Save the cart item to the database
        $cartItem->save();
    }

    session()->forget('cart');
}

3. app/Providers/EventServiceProvider.php $listen:

protected $listen = [
    ...
    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\SyncShoppingCart',
    ],
];

, , App\Listeners\SyncShoppingCart::handle . , , , . , , .


, Events Laravel.

+1

All Articles