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

问题描述 投票:0回答:1

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

但是不久我意识到用户的购物车数据会存储在会话中,每当用户注销并再次登录时,购物车数据都会丢失。用户也无法从另一个浏览器或另一个设备访问购物车项目,因为它是临时保存在特定浏览器的会话中的。我想将相同的数据存储到数据库中并从那里访问它。关于将数据存储在数据库中的文档解释中关于此的内容很少,但是还不清楚。谁能给我一个关于如何实现这一目标的想法

php laravel shopping-cart
1个回答
1
投票
Darryldecode购物车是一种在项目中实现购物车功能的双向方法。就我而言,我正在尝试对愿望清单使用持久性存储,以便用户登录时仍然可以看到其愿望清单项目。首先要做的是通过运行命令来创建迁移

php artisan make:migration create_wishlist_storage_table

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

<?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'); } }

之后,运行php artisan migrate命令。这将在数​​据库中创建一个带有列表ID,wishlist_data和时间戳记的wishlist_storage表。下一步是通过运行命令php artisan make:model DatabaseStorageModel创建一个雄辩的模型来处理我们的迁移。打开应用目录中的DatabaseStorageModel.php文件,并用以下代码行替换整个代码块。

<?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); } }

接下来要做的是创建一个新类,将其注入到我们的购物车实例中。为此,使用您的应用程序名称空间创建一个名为DatabaseStorage.php的文件,然后粘贴以下代码行。

<?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 ]); } } }

由您决定文件和类的命名方式,但是我正在确切地解释我是如何做到的。最后一步是使DatabaseStorage类成为购物车的默认存储。运行命令

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

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

'storage'=>null,

with

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

您现在可以按照正常过程在控制器中使用购物车。    
© www.soinside.com 2019 - 2024. All rights reserved.