0

Tengo la siguiente clase Cart que es la de un carrito de compras en Laravel que es la siguiente:

  <?php

     namespace App\Services;

     use App\Models\Coupon;
     use App\Models\Course;
     use App\Helpers\Currency;
     use Illuminate\Support\Collection;

     /**
    * Class Cart
      * @package App\Classes
      */

   class Cart
   {

/**
 * @var Collection
 */
protected Collection $cart;

/**
 * Cart constructor.
 */
public function __construct()
{
    if (session()->has("cart")) {
        $this->cart = session("cart");
    } else {
        $this->cart = new Collection;
    }
}

/**
 *
 * Get cart contents
 *
 */
public function getContent(): Collection
{
    return $this->cart;
}

/**
 * Save the cart on session
 */
protected function save(): void
{
    session()->put("cart", $this->cart);
    session()->save();
}

/**
 *
 * Add course on cart
 *
 * @param Course $course
 */
public function addCourse(Course $course): void
{
        $this->cart->push($course);
        $this->save();
}


/**
 *
 * Remove course from cart
 *
 * @param int $id
 */
public function removeCourse(int $id): void
{
    $this->cart = $this->cart->reject(function (Course $course) use ($id) {
        return $course->id === $id;
    });
    $this->save();
}

/**
 *
 * calculates the total cost in the cart
 *
 * @param bool $formatted
 * @return mixed
 */
public function totalAmount($formatted = true)
{
    $amount = $this->cart->sum(function (Course $course) {
        return $course->price;
    });
    if ($formatted) {
        return Currency::formatCurrency($amount);
    }
    return $amount;
}

/**
 *
 * all taxes for cart
 *
 * @param bool $formatted
 * @return float|int|string
 */
public function taxes($formatted = true)
{
    $total = $this->totalAmount(false);
    if ($total) {
        $total = ($total * env('TAXES')) / 100;
        if ($formatted) {
            return Currency::formatCurrency($total);
        }
        return $total;
    }
    return 0;
}

/**
 *
 * Total products in cart
 *
 * @return int
 */
public function hasProducts(): int
{
    return $this->cart->count();
}

/*
 * Clear cart
 */
public function clear(): void
{
    $this->cart = new Collection;
    $this->save();
}

/**
 *
 * calculates the total cost in the cart with coupon
 *
 * @param bool $formatted
 * @return string
 */
public function totalAmountWithDiscount($formatted = true)
{
    $amount = $this->totalAmount(false);
    $withDiscount = $amount;
    if (session()->has("coupon")) {
        $coupon = Coupon::available(session("coupon"))->first();
        if (!$coupon) {
            return $amount;
        }

        $coursesInCart = $this->getContent()->pluck("id");
        if ($coursesInCart) {
            // courses attached to coupon in database
            $coursesForApply = $coupon->courses()->whereIn("id", $coursesInCart);

            // id courses attached on database for apply coupon
            $idCourses = $coursesForApply->pluck("id")->toArray();

            if (!count($idCourses)) {
                $this->removeCoupon();
                session()->flash("message", ["danger", __("El cupón no se puede aplicar")]);
                return $amount;
            }

            // total price courses without discount applied
            $priceCourses = $coursesForApply->sum("price");

            // check discount type and apply
            if ($coupon->discount_type === Coupon::PERCENT) {
                $discount = round($priceCourses - ($priceCourses * ((100 - $coupon->discount) / 100)), 2);
                $withDiscount = $amount - $discount;
            }
            if ($coupon->discount_type === Coupon::PRICE) {
                $withDiscount = $amount - $coupon->discount;
            }
        } else {
            $this->removeCoupon();
            return $amount;
        }
    }
    if ($formatted) {
        return Currency::formatCurrency($withDiscount);
    }
    return $withDiscount;
}

protected function removeCoupon(): void
{
    session()->remove("coupon");
    session()->save();
}
}

La clase cart me funciona desde la creación de carrito, agregar productos, aplicar los cupones, mostrar el precio y el total, aplicar el descuento del cupon, etc.

EL único detalle es el siguiente, al agregar un producto se puede volver a agregar el mismo producto como es la siguiente imagen:

productos duplicados en un carrito

Pude buscar sobre utilizar contains, pero la duda es dónde implementar si tengo que hacer un nuevo método dentro de mi clase Cart o tengo que implementar contains en el método addCourse, si me pudieran ayudar por favor.

1 respuesta 1

0

Si estas manejando algún tipo de id para el producto solo cuando agregues verifica sí ya existe en tu carrito con un if(), sí existe aumenta la cantidad ++ y si no manejas por cantidad solo manda una variable a la vista que diga que ya existe.

3
  • Ok entiendo pero enqué parte de mi clase haria eso y como sería? el 30 nov. 2022 a las 17:41
  • Podrías poner el código dónde agregas el producto, así podremos ayudarte mejor el 30 nov. 2022 a las 18:48
  • Aquí es donde se agrega cada producto /** * * Add course on cart * * @param Course $course */ public function addCourse(Course $course): void { $this->cart->push($course); $this->save(); } el 30 nov. 2022 a las 19:48

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.