Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Empty cart after page refresh. #8

Closed
victorighalo opened this issue Mar 19, 2019 · 26 comments
Closed

Empty cart after page refresh. #8

victorighalo opened this issue Mar 19, 2019 · 26 comments
Assignees

Comments

@victorighalo
Copy link

I'm implementing a custom Buyable Model but after successfully adding to Cart, cart count returns the correct values but after page refresh cart count goes back to zero.

@fulopattila122 fulopattila122 self-assigned this Mar 19, 2019
@fulopattila122
Copy link
Member

Can you please post some code examples?

@victorighalo
Copy link
Author

victorighalo commented Mar 19, 2019

Can you please post some code examples?

use Illuminate\Http\Request;
use Vanilo\Cart\Facades\Cart;
use Vanilo\Cart\Contracts\CartItem;

//Add to Cart -- This works and returns quantity
$product = \App\Product::findBySlug($request->slug);
Cart::addItem($product, $request->qty);
return response()->json(['message' => 'Added to cart', 'cart_count' => Cart::itemCount()]);
//Returns zero after refresh
if(Cart::exists()){
$cart_count = Cart::itemCount();
$cart = Cart::model()->items;
}else{
$cart_count = 0;
$cart = [];
}
return view('pages.front.cart', compact('cart', 'cart_count'));
//Product model
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Vanilo\Contracts\Buyable;
use Vanilo\Product\Models\Product as BaseProduct;
use Vanilo\Support\Traits\BuyableModel;
use Vanilo\Support\Traits\BuyableImageSpatieV7;
use willvincent\Rateable\Rateable;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Vanilo\Category\Models\TaxonProxy;
use BrianFaust\Commentable\Traits\HasComments;

class Product extends BaseProduct implements Buyable, HasMedia
{
    use
        Rateable,
        BuyableModel,
        BuyableImageSpatieV7,
        HasComments,
        HasMediaTrait;

    public function taxons(): MorphToMany
    {
        return $this->morphToMany(
            TaxonProxy::modelClass(), 'model', 'model_taxons', 'model_id', 'taxon_id'
        );
    }
}

@fulopattila122
Copy link
Member

Can you please also include the use Class\Name section as well?

@victorighalo
Copy link
Author

Can you please also include the use Class\Name section as well?

I've updated the code example

@fulopattila122
Copy link
Member

Few tips:

  1. You can use the HasTaxons trait on your product model.
  2. You don't have to check whether the cart exists for the count, it's being done internally.
  3. Don't access the Cart::model() directly unless you really, really, really (really?) need it. Use Cart::getItems() instead.
return view('pages.front.cart', ['cart' => Cart::getItems(), 'cart_count' => Cart::itemCount()]);

Regarding the bug: do you use the web middleware on the routes?

@victorighalo
Copy link
Author

3. getItems

Thanks I have used the HasTaxons trait on my product model. I've updated the code to use Cart::getItems() instead, and yes, I use the Web middlleware in my controllers.

I noticed the user_id field in the cart table is null, could that be one of the problems?

@fulopattila122
Copy link
Member

No, the user <-> cart assignment is completely optional.

Is the session working properly in your application?

Eg. if you store some value, can you get the value back after page refresh?

//store some data in controller
session()->put('hey', 'yo');

// ... refresh the page ...
session()->get('hey');
// Do you get 'yo' here?

@victorighalo
Copy link
Author

No, the user <-> cart assignment is completely optional.

Is the session working properly in your application?

Eg. if you store some value, can you get the value back after page refresh?

//store some data in controller
session()->put('hey', 'yo');

// ... refresh the page ...
session()->get('hey');
// Do you get 'yo' here?

Yes. Session works fine. I can store and retrieve the value.

@fulopattila122
Copy link
Member

What's the value of config('vanilo.cart.session_key') ?
What does session()->get(config('vanilo.cart.session_key')) give when adding something to the cart, and after refreshing the page?

@victorighalo
Copy link
Author

What's the value of config('vanilo.cart.session_key') ?
What does session()->get(config('vanilo.cart.session_key')) give when adding something to the cart, and after refreshing the page?

config('vanilo.cart.session_key') = null

when adding to cart

session()->get(config('vanilo.cart.session_key'))  
array (size=3)
  '_token' => string 'rPjTNEhixJYj7ZeoRAkSWUJLRTdWtvxmZ8fuLUm5' (length=40)
  '_previous' => 
    array (size=1)
      'url' => string 'http://localhost/ecommerce-laravel/public/Toyota-bus/test-product-2' (length=67)
  '_flash' => 
    array (size=2)
      'old' => 
        array (size=0)
          empty
      'new' => 
        array (size=0)
          empty

after adding to cart

session()->get(config('vanilo.cart.session_key'))
array (size=1)
  '_token' => string 'rPjTNEhixJYj7ZeoRAkSWUJLRTdWtvxmZ8fuLUm5' (length=40)

after second refresh

array (size=3)
  '_token' => string 'rPjTNEhixJYj7ZeoRAkSWUJLRTdWtvxmZ8fuLUm5' (length=40)
  '_previous' => 
    array (size=1)
      'url' => string 'http://localhost/ecommerce-laravel/public/Toyota-bus/test-product-2' (length=67)
  '_flash' => 
    array (size=2)
      'old' => 
        array (size=0)
          empty
      'new' => 
        array (size=0)
          empty

@fulopattila122
Copy link
Member

fulopattila122 commented Mar 21, 2019

config('vanilo.cart.session_key') = null this is the problem.

Can you post the contents of config/concord.php here? Do you have config/vanilo.php file?

@victorighalo
Copy link
Author

My config/concrd.php file

<?php

return [
    'modules' => [
        Konekt\AppShell\Providers\ModuleServiceProvider::class => [
            'ui' => [
                'name' => 'Vanilo',
                'url' => '/admin/product'
            ]
        ],
        Vanilo\Framework\Providers\ModuleServiceProvider::class
    ]
];

I also don't have a config/vanilo.php file

@fulopattila122
Copy link
Member

That's strange, because it looks as it should. What's the output of var_dump(config('vanilo')) ?

@victorighalo
Copy link
Author

That's strange, because it looks as it should. What's the output of var_dump(config('vanilo')) ?

Null

fulopattila122 added a commit that referenced this issue Mar 24, 2019
Prevents problems like issue #8 from silently happening.
@fulopattila122
Copy link
Member

What do config('concord') and config('session') calls return?

@victorighalo
Copy link
Author

What do config('concord') and config('session') calls return?

config('session') returns

array:15 [▼
  "driver" => "file"
  "lifetime" => "120"
  "expire_on_close" => false
  "encrypt" => false
  "files" => "C:\wamp64\www\ecommerce-laravel\storage\framework/sessions"
  "connection" => null
  "table" => "sessions"
  "store" => null
  "lottery" => array:2 [▼
    0 => 2
    1 => 100
  ]
  "cookie" => "laravel_session"
  "path" => "/"
  "domain" => null
  "secure" => false
  "http_only" => true
  "same_site" => null
]

config('concord')

array:1 [▼
  "modules" => array:2 [▼
    "Konekt\AppShell\Providers\ModuleServiceProvider" => array:1 [▼
      "ui" => array:2 [▼
        "name" => "Vanilo"
        "url" => "/admin/product"
      ]
    ]
    0 => "Vanilo\Framework\Providers\ModuleServiceProvider"
  ]
]

@victorighalo
Copy link
Author

Please how can I fix this?

@fulopattila122
Copy link
Member

Your complete vanilo config is gone. Somehow you overwrote it.
The last thing I can think of: what's the content of vendor/vanilo/cart/src/resources/config/module/php ?

@victorighalo
Copy link
Author

Your complete vanilo config is gone. Somehow you overwrote it.
The last thing I can think of: what's the content of vendor/vanilo/cart/src/resources/config/module/php ?

return [
    'event_listeners'   => true,
    'session_key'       => 'vanilo_cart', // The session key where the cart id gets saved
    'auto_destroy'      => false, // Whether to immediately delete carts with 0 items
    'auto_assign_user'  => true, // Whether to automatically set the user_id on new carts (based on Auth::user())
    'preserve_for_user' => false, // Whether to keep and restore user carts across logins and devices
    'items'             => [
        'extra_product_attributes_to_merge' => []
    ]
];

@fulopattila122
Copy link
Member

fulopattila122 commented Mar 24, 2019

Can you maybe zip your entire project along with the vendor/ folder (remove sensitive parts) and make it available for download?

@victorighalo
Copy link
Author

Can you maybe zip your entire project along with the vendor/ folder (remove sensitive parts) and make it available for download?

https://drive.google.com/file/d/1IffV0zfohUhfYvHb7lMRoZmGxKPJB6UX/view?usp=sharing

@fulopattila122
Copy link
Member

My OS says it's not a zip file. Please either fix it or send .tar.gz

@victorighalo
Copy link
Author

My OS says it's not a zip file. Please either fix it or send .tar.gz

Fixed

https://drive.google.com/file/d/1f_J89IUUR5_iLmD8r2fCYifhd4iH0DCi/view?usp=sharing

@fulopattila122
Copy link
Member

I've checked your code. Here's what to do:

Move these 3 routes from routes/api.php => routes/web.php:

Route::post('/cart/add', 'CartController@add')->name('add_to_cart');
Route::post('/cart/update/{cart_item?}', 'CartController@update')->name('update_cart');
Route::post('/cart/destroy/{cart_item?}', 'CartController@destroy')->name('destroy_cart');

Remove api/cart/* from the except array in the App\Http\Middleware\VerifyCsrfToken class:

protected $except = [
    'api/cart/*' // <- remove
];

In general, Vanilo could do much more for you.
You're reimplementing a lots of existing Vanilo functionalities, often not in a proper way.
I suggest to re-read the docs and study the code of the demo app.

@victorighalo
Copy link
Author

I've checked your code. Here's what to do:

Move these 3 routes from routes/api.php => routes/web.php:

Route::post('/cart/add', 'CartController@add')->name('add_to_cart');
Route::post('/cart/update/{cart_item?}', 'CartController@update')->name('update_cart');
Route::post('/cart/destroy/{cart_item?}', 'CartController@destroy')->name('destroy_cart');

Remove api/cart/* from the except array in the App\Http\Middleware\VerifyCsrfToken class:

protected $except = [
    'api/cart/*' // <- remove
];

In general, Vanilo could do much more for you.
You're reimplementing a lots of existing Vanilo functionalities, often not in a proper way.
I suggest to re-read the docs and study the code of the demo app.

Thanks so much. It works now.
I'll have to take a deeper study of the Vanilo Docs so I can get things right. I will appreciate if you can point of some specific changes i can make to improve my use of Vanillo.

@fulopattila122
Copy link
Member

fulopattila122 commented Mar 28, 2019

I will appreciate if you can point of some specific changes i can make to improve my use of Vanillo.

I'll do that in the coming days.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants