How can I store my Cart data to database in Laravel using DarrylDecode Cart functionalities

陌路散爱 提交于 2020-07-22 14:14:50

问题


I was trying to learn Laravel by making a small ecommerce website project and for implementing cart functionality, I came across DarrylDecode Cart functionality (https://github.com/darryldecode/laravelshoppingcart)

But soon I realised that the cart data for a user gets stored in a session and whenever the user logs out and log back in again, the cart data gets lost. The user cannot access the cart items from another browser or another device aswell since it is saved on a session on particular browser on temporary basis. I wanted to store the same data into database and access it from there. There are few things about that in the documentation explaing about storing data in database but that is not that clear. Can anyone give me an idea on how to achieve this


回答1:


Darryldecode cart is a two-way method for implementing cart functionality in your project. In my case, I'm trying to use persistent storage for the wishlist so that when users log in, they will still see their wishlist items. The first thing to do is to create a migration by running the command

php artisan make:migration create_wishlist_storage_table

This will create the migration file in the database/migration directory, open the file, and replace the entire code block with these lines of code.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateWishlistStorageTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
 public function up()
{
    Schema::create('wishlist_storage', function (Blueprint $table) {
        $table->string('id')->index();
        $table->longText('wishlist_data');
        $table->timestamps();
        $table->primary('id');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('wishlist_storage');
}
}

After that, run the php artisan migrate command. This will create a wishlist_storage table in your database with columns id, wishlist_data, and the timestamps.The next thing is to create an eloquent model to handle our migration by running the command php artisan make:model DatabaseStorageModel. Open the DatabaseStorageModel.php file in your app directory and replace the entire code block with the following lines of code.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class DatabaseStorageModel extends Model
{
//
/**
 * Override eloquent default table
 * @var string
 */
protected $table = 'wishlist_storage';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'id', 'wishlist_data',
];


/**
 * Mutator for wishlist_column
 * @param $value
 */
public function setWishlistDataAttribute($value)
{
    $this->attributes['wishlist_data'] = serialize($value);
}


/**
 * Accessor for wishlist_column
 * @param $value
 * @return mixed
 */
public function getWishlistDataAttribute($value)
{
    return unserialize($value);
}

}

The next thing todo is to create a new class to be injected to our cart instance. For this, create a file named DatabaseStorage.php with your app namespace and paste this lines of code.

<?php
namespace App;

use Darryldecode\Cart\CartCollection;

class DatabaseStorage {

public function has($key)
{
    return DatabaseStorageModel::find($key);
}


public function get($key)
{
    if($this->has($key))
    {
        return new CartCollection(DatabaseStorageModel::find($key)->wishlist_data);
    }
    else
    {
        return [];
    }
}


public function put($key, $value)
{
    if($row = DatabaseStorageModel::find($key))
    {
        // update
        $row->wishlist_data = $value;
        $row->save();
    }
    else
    {
        DatabaseStorageModel::create([
            'id' => $key,
            'wishlist_data' => $value
        ]);
    }
}


}

It's up to you the way you name your files and classes, but i'm explaining exactly how i did it. The final step is to make the DatabaseStorage class the default storage for our Cart. Run the command

php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="config"

to publish the library configuration file name shopping_cart.php in the config directory. Open the shopping_cart.php file and replace

'storage'=>null,

with

'storage' => \App\DatabaseStorage::class,

You can now follow the normal procedure to use the cart in your controller.




回答2:


When I used this i found cart is now public for all. if one user removes the item it is being removed from cart totally and other user who has the same item can not see this.



来源:https://stackoverflow.com/questions/61309436/how-can-i-store-my-cart-data-to-database-in-laravel-using-darryldecode-cart-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!