Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DuikGek's avatar

shopping cart migration

I want to build a shopping card and the reason is that all shopping cart are using session and i want save the data into my db with json.

now is that the right way to start.

migration

public function up()
{
    Schema::create('shopping_carts', function (Blueprint $table) {
        $table->increments('id');
        $table->json('soppingCart');
        $table->timestamps();
    });
}

model

lass ShoppingCart extends Model
{
        protected $fillable = ['shoppingCart'];

    protected $casts =['shoppingCart'  =>'json'];
}

or do i miss something ?

0 likes
3 replies
martinbean's avatar

No one can really answer as we don’t know your shopping cart’s requirements, so therefore don’t know if you “missed” something or not.

DuikGek's avatar

ShoppingCart migration

class CreateShoppingCartsTable extends Migration
{

  public function up()
  {
    Schema::create('shopping_carts', function (Blueprint $table) {
        $table->increments('id');

        $table->string('key');
        $table->integer('total_products');
        $table->float('total_price');

        $table->timestamps();
        $table->softDeletes();
    });
 }

 public function down()
 {
    Schema::dropIfExists('shopping_carts');
    }

shoppingCartItems

public function up()
{
    Schema::create('shopping_cart_items', function (Blueprint $table) {
        $table->increments('id');
        $table->float('price');
        $table->float('amount');

        $table->unsignedInteger('product_id');
        $table->foreign('product_id')->references('id')->on('products');

        $table->timestamps();
        $table->softDeletes();
    });
}

my controller

 protected function loadShoppingCart(Request $request)
{
    // get the db from shopping cart

    $shoppingCart = ShoppingCart::firstOrCreate(['key'=>$request->get('key'), 'total_products'=>$request->get('total_products'),
        'total_price'=>$request->get('total_price'), $request->all() ]);
    if (empty($shoppingCart)){
        $cart = ShoppingCart::create($request->all()  );
    }

}
Lars-Janssen's avatar

@mmagaber@gmail.com why would you want to store the shopping card into the database? I would store it on the client side.

Please or to participate in this conversation.