laravelshoppingcart icon indicating copy to clipboard operation
laravelshoppingcart copied to clipboard

[ question & discussion ] guest cart to user cart

Open rebornishard opened this issue 7 years ago • 15 comments
trafficstars

If i use session user to identify cart, i'm unable to make cart for non user ( guest ) how to make cart worked for guest and user at same time ? if guest register , continue his cart are they possible ?

rebornishard avatar Jun 21 '18 12:06 rebornishard

@rebornishard hello, for non-users (guest), you can set cookies for this guest as their cart identifier and retrieve that cookie on server and bind it just like when you bind a cart to a user ID etc.

darryldecode avatar Jun 22 '18 03:06 darryldecode

@darryldecode any sample code that can make a clue, i clueless here since only see example using session thanks before

rebornishard avatar Jun 27 '18 05:06 rebornishard

Also interested in that question. Especially, how to work with it through API.
I have project where backend and frontend are separated. I used Cart::getCondition() for guests and Cart::session($user->id)->getCondition() for auth users, but in that case I must always check if user exist.
There is no doubt that this is a wrong practice... Can you advise something?

makzef avatar Oct 19 '18 12:10 makzef

The only way I found is to make custom AuthenticateUsers trait with custom login function so every time a user login we can transfer the items from the guest cart to the user's cart. The problem is that Laravel regenerate the session when user is logged in and the cart identifier changes.

<?php

namespace App\Traits;

use App\Models\DatabaseStorageModel;
use App\Models\Product;
use Illuminate\Http\Request;

trait AuthenticateUsersCustom
{
    use \Illuminate\Foundation\Auth\AuthenticatesUsers;

    public function login(Request $request)
    {
        $old_session_id = $request->session()->getId();
        $old_cart_data = DatabaseStorageModel::find($old_session_id.'_cart_items');

        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            if ($old_cart_data) {
                if ($old_cart_data->cart_data->count()) {
                    \Cart::session(auth()->id());
                    $old_cart_data->cart_data->each(function ($item) {
                        $item = $item->toArray();
                        \Cart::add($item);
                    });
                }
            }

            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
}

and then you can use the new trait to login users

vlados avatar May 04 '20 06:05 vlados

I have the same problem! Have any solution?

Shaykhnazar avatar Oct 13 '20 06:10 Shaykhnazar

@Shaykhnazar see my previous post

vlados avatar Oct 13 '20 11:10 vlados

@Shaykhnazar see my previous post

where is your post?

Shaykhnazar avatar Oct 13 '20 13:10 Shaykhnazar

@Shaykhnazar https://github.com/darryldecode/laravelshoppingcart/issues/137#issuecomment-623283546

vlados avatar Oct 13 '20 14:10 vlados

It is not working for me! But I can't find any error in the code. The code is perfect but not working after login.

вт, 13 окт. 2020 г. в 19:50, Vladislav Stoitsov [email protected]:

@Shaykhnazar https://github.com/Shaykhnazar #137 (comment) https://github.com/darryldecode/laravelshoppingcart/issues/137#issuecomment-623283546

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/darryldecode/laravelshoppingcart/issues/137#issuecomment-707792986, or unsubscribe https://github.com/notifications/unsubscribe-auth/AL3334B76VSLLDNE57RG3JLSKRSK5ANCNFSM4FGH6CVQ .

Shaykhnazar avatar Oct 13 '20 15:10 Shaykhnazar

Did you include it in LoginController?

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Traits\AuthenticateUsersCustom;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticateUsersCustom;

    public function redirectTo()
    {
        return route('home');
    }

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

vlados avatar Oct 13 '20 17:10 vlados

Did you include it in LoginController?

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Traits\AuthenticateUsersCustom;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticateUsersCustom;

    public function redirectTo()
    {
        return route('home');
    }

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

I found the cause of the problem but how can I fix that? https://prnt.sc/v21bmd After login not working object type and works array https://prnt.sc/v21cgb.

Shaykhnazar avatar Oct 19 '20 04:10 Shaykhnazar

Can I change only cart_session_id without move items to new?

  1. https://prnt.sc/v21ktm -> guest
  2. https://prnt.sc/v21j1x -> register Error here: https://prnt.sc/v21pec

Shaykhnazar avatar Oct 19 '20 05:10 Shaykhnazar

I think that I've encountered the same problem. Editing your code like this, solved it:

 if ($old_cart_data->cart_data->count()) {
                \Cart::session(auth()->id());
                \Cart::clear();
                
                 $old_cart_data->cart_data->each(function ($item) {
                    \Cart::add($item->all());
                });
                
}

I think that you shouldn't convert the item toArray so you can use the associatedModel's properties.

hassou avatar Mar 08 '21 17:03 hassou

Can someone help me how can I delete the old cart row from the database now?

hassou avatar Mar 08 '21 17:03 hassou

I can't seem to work out the guest cart, when I remove the session auth it does not add any item on the cart. Can someone help or send code?

clrkrssl avatar May 21 '21 08:05 clrkrssl