如何使用DarrylDecode购物车功能将我的购物车数据存储到Laravel中的数据库中



我试图通过制作一个小型电子商务网站项目来学习Laravel,为了实现购物车功能,我遇到了DarrylDecode购物车功能(https://github.com/darryldecode/laravelshoppingcart)

但很快我意识到,用户的购物车数据存储在会话中,每当用户注销并再次登录时,购物车数据就会丢失。用户也无法从另一个浏览器或另一个设备访问购物车项目,因为它是临时保存在特定浏览器上的会话中的。我想将相同的数据存储到数据库中,并从那里访问它。在解释将数据存储在数据库中的文档中,几乎没有关于这一点的内容,但这一点并不明确。有人能给我一个如何实现的想法吗

Darryldecode cart是在项目中实现cart功能的双向方法。在我的案例中,我试图为愿望列表使用持久存储,这样当用户登录时,他们仍然可以看到他们的愿望列表项目。要做的第一件事是通过运行命令创建迁移

php artisan make:migration create_wishlist_storage_table

这将在数据库/迁移目录中创建迁移文件,打开该文件,并用这些代码行替换整个代码块。

<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
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');
}
}

之后,运行php artisan migrate命令。这将在数据库中创建一个wishlistrongtorage表,其中包含列id、wishlist_data和时间戳。接下来是通过运行命令php artisan make:model DatabaseStorageModel来创建一个有说服力的模型来处理我们的迁移。打开应用程序目录中的DatabaseStorageModel.php文件,并用以下代码行替换整个代码块。

<?php
namespace App;
use IlluminateDatabaseEloquentModel;
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);
}
}

接下来要做的是创建一个新类,将其注入到我们的cart实例中。为此,使用您的应用程序命名空间创建一个名为DatabaseStorage.php的文件,并粘贴这几行代码。

<?php
namespace App;
use DarryldecodeCartCartCollection;
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
]);
}
}

}

这取决于您命名文件和类的方式,但我正在解释我是如何做到的。最后一步是使DatabaseStorage类成为Cart的默认存储。运行命令

php artisan vendor:publish --provider="DarryldecodeCartCartServiceProvider" --tag="config"

以在config目录中发布库配置文件名shoppingcart.php。打开shopping_cart.php文件并替换

'storage'=>null,

带有

'storage' => AppDatabaseStorage::class,

现在,您可以按照正常程序在控制器中使用购物车。

当我使用这个时,我发现购物车现在对所有人都是公共的。如果一个用户删除了该项目,它将被完全从购物车中删除,而拥有相同项目的其他用户则看不到这一点。

最新更新