<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
livewireshopping / livewire-shopping-cart example snippets
php artisan vendor:publish --provider="LivewireShopping\LivewireShoppingCart\CartServiceProvider" --tag="config"
This will create a cart.php file in the config folder where you can modify the cart settings.
Create a Livewire component `AddToCart`:
Modify the AddToCart component:
namespace App\Http\Livewire;
use Livewire\Component;
use Cart;
class AddToCart extends Component
{
public $product;
public function addToCart($product)
{
Cart::add($product);
$this->emit('cartUpdated');
}
public function render()
{
return view('livewire.add-to-cart');
}
}
<!-- resources/views/livewire/add-to-cart.blade.php -->
<button wire:click="addToCart({{ $product->id }})">Add to Cart</button>
php artisan make:livewire CartTotal
namespace App\Http\Livewire;
use Livewire\Component;
use Cart;
class CartTotal extends Component
{
protected $listeners = ['cartUpdated' => 'updateTotal'];
public $total;
public function mount()
{
$this->total = Cart::total();
}
public function updateTotal()
{
$this->total = Cart::total();
}
public function render()
{
return view('livewire.cart-total');
}
}
Create the view for the cart-total.blade.php component:
<!-- resources/views/livewire/cart-total.blade.php -->
<div>
Total: ${{ $total }}
</div>
Use the Components in the Main View
<!-- resources/views/shop.blade.php -->
@extends('layouts.app')
@section('content')
<div>
@foreach($products as $product)
<div>
<h3>{{ $product->name }}</h3>
<livewire:add-to-cart :product="$product" />
</div>
@endforeach
</div>
<div>
<livewire:cart-total />
</div>
@endsection