Laravel Shopping Cart 轻松实现购物车功能 Laravel购物车插件

阅读 (6197)
Laravel Shopping Cart 轻松实现购物车功能,搭建电商平台

Laravel的简单购物车实现。

安装 Installation

通过Composer安装包。

从终端运行Composer require命令:

composer require gloudemans/shoppingcart

如果您使用的是Laravel 5.5,那么这样就安装完成了。

如果您仍然使用Laravel的5.4版本,添加软件包的服务,添加别名。请打开config/app.php文件。

providers数组中添加一个新行:

Gloudemans\Shoppingcart\ShoppingcartServiceProvider::class

并可选择向aliases数组添加一个新行:

'Cart' => Gloudemans\Shoppingcart\Facades\Cart::class,

现在,您已准备好开始在应用程序中使用shoppingcart。

从该软件包的第2版开始,可能会使用依赖注入将Cart类的实例注入到控制器或其他类中

以下为快速索引,以了解有关LaravelShoppingcart的更多信息

使用方法 Usage

购物车为您提供以下方法:

Cart::add()

将项目添加到购物车非常简单,只需使用add()接受各种参数的方法即可。

在最基本的表单中,您可以指定要添加到购物车的产品的ID,名称,数量和价格。

Cart::add('293ad', 'Product 1', 1, 9.99);

作为可选的第五个参数,您可以传递它选项,因此您可以添加具有相同ID的多个项目,例如具有不同的尺寸的商品。

Cart::add('293ad', 'Product 1', 1, 9.99, ['size' => 'large']);

add()方法将返回刚刚添加到购物车中的项目的CartItem实例。

也许您更喜欢使用数组添加项目?只要数组包含所需的键,就可以将其传递给方法。options选项键是可选的。

Cart::add(['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'options' => ['size' => 'large']]);

该软件包的第2版中的新功能是可以使用该Buyable接口。这种方式的工作方式是你有一个模型实现Buyable接口,这将使你实现一些方法,所以包知道如何从你的模型中获取id,名称和价格。通过这种方式,您只需将add()方法传递给模型和数量,它就会自动将其添加到购物车中。

作为额外的奖励,它会自动将模型与CartItem相关联

Cart::add($product, 1, ['size' => 'large']);

作为可选的第三个参数,您可以添加选项。

Cart::add($product, 1, ['size' => 'large']);

最后,您还可以立即将多重项目添加到购物车。您可以只传递add()一个数组数组或一个Buyables数组,然后将它们添加到购物车中。

将多个项目添加到购物add()车时,该方法将返回CartItems数组。

Cart::add([
  ['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 10.00],
  ['id' => '4832k', 'name' => 'Product 2', 'qty' => 1, 'price' => 10.00, 'options' => ['size' => 'large']]
]);

Cart::add([$product1, $product2]);

Cart::update()

要更新购物车中的商品,您首先需要商品的rowId。接下来,您可以使用该update()方法来更新它。

如果您只想更新数量,则会将更新方法传递给rowId和新数量:

$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';

Cart::update($rowId, 2); // 将更新商品数量

如果要更新项目的更多属性,可以将update方法传递给数组,也可以将其Buyable作为第二个参数传递。这样,您可以使用给定的rowId更新项目的所有信息。

Cart::update($rowId, ['name' => 'Product 1']); // Will update the name

Cart::update($rowId, $product); // Will update the id, name and price

Cart::remove()

要删除购物车的商品,您将再次需要rowId。这个rowId你只需传递给remove()方法,它将从购物车中删除该项目。

$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';

Cart::remove($rowId);

Cart::get()

如果你想使用rowId从购物车中获取商品,你可以简单地get()在购物车上调用方法并将其传递给rowId。

$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';

Cart::get($rowId);

Cart::content()

当然,您也想获得购物车的内容。这是您将使用该content方法的地方。此方法将返回CartItems集合,您可以迭代并向客户显示内容。

Cart::content();

此方法将返回当前购物车实例的内容,如果您想要其他实例的内容,只需链接调用。

Cart::instance('wishlist')->content();

Cart::destroy()

要删除购物车的商品,您将再次需要rowId。这个rowId你只需传递给remove()方法,它将从购物车中删除该项目。

Cart::destroy();

Cart::total()

根据total()价格和数量,该方法可用于获得购物车中所有商品的计算总数。

Cart::total();

该方法将自动格式化结果,您可以使用三个可选参数进行调整

Cart::total($decimals, $decimalSeperator, $thousandSeperator);

您可以在配置文件中设置默认数字格式。

如果您没有使用Facade,但在(例如)Controller中使用依赖注入,您也可以简单地获取总属性 $cart->total

Cart::tax()

根据tax()价格和数量,该方法可用于获取购物车中所有商品的计算税额。

Cart::tax();

该方法将自动格式化结果,您可以使用三个可选参数进行调整

Cart::tax($decimals, $decimalSeperator, $thousandSeperator);

您可以在配置文件中设置默认数字格式。

如果你没有使用Facade,但在你的(例如)控制器中使用依赖注入,你也可以简单地获得税收属性 $cart->tax

Cart::subtotal()

subtotal()方法可用于获取购物车中所有商品的总和减去税额总额。

Cart::subtotal();

该方法将自动格式化结果,您可以使用三个可选参数进行调整

Cart::subtotal($decimals, $decimalSeperator, $thousandSeperator);

您可以在配置文件中设置默认数字格式。

如果您没有使用Facade,但在(例如)Controller中使用依赖注入,您还可以简单地获取小计属性 $cart->subtotal

Cart::count()

如果您想知道购物车中有多少商品,可以使用该count()方法。此方法将返回购物车中的项目总数。因此,如果您添加了2本书和1件衬衫,它将返回3件物品。

Cart::count();

Cart::search()

要在购物车中查找商品,您可以使用该search()方法。

此方法在版本2上已更改

在后台代码中,该方法只使用Laravel Collection类的过滤方法。这意味着您必须将它传递给Closure,您将在其中指定搜索条件。

例如,如果您要查找ID为1的所有项目:

$cart->search(function ($cartItem, $rowId) {
	return $cartItem->id === 1;
});

如您所见,Closure将收到两个参数。第一个是CartItem来执行检查。第二个参数是此CartItem的rowId。

该方法将返回一个Collection,其中包含找到的所有CartItems

这种搜索方式使您可以完全控制搜索过程,并使您能够创建非常精确和特定的搜索。

集合 Collections

在多个实例中,购物车将返回一个集合。这只是一个简单的Laravel Collection,因此您可以在Laravel Collection上调用的所有方法也可以在结果中使用。

例如,您可以快速获取购物车中唯一产品的数量:

Cart::content()->count();

或者您可以按产品的ID对内容进行分组:

Cart::content()->groupBy('id');

实例 Instances

这些包支持购物车的多个实例。这种方式是这样的:

您可以通过调用设置购物车的当前实例Cart::instance('newInstance')。从这时起,购物车的活动实例将是newInstance,因此当您添加,删除或获取购物车的内容时,您将使用newInstance购物车的实例。如果要切换实例,只需Cart::instance('otherInstance')再次调用,然后otherInstance再次使用。

一个小例子:

Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99);

// Get the content of the 'shopping' cart
Cart::content();

Cart::instance('wishlist')->add('sdjk922', 'Product 2', 1, 19.95, ['size' => 'medium']);

// Get the content of the 'wishlist' cart
Cart::content();

// If you want to get the content of the 'shopping' cart again
Cart::instance('shopping')->content();

// And the count of the 'wishlist' cart again
Cart::instance('wishlist')->count();

注意1:只要在脚本执行期间未设置其他实例,购物车就会保留在最后设置的实例中。

注意2:调用默认的购物车实例default,因此当您不使用实例时,Cart::content();与实例相同Cart::instance('default')->content()

模型 Models

因为能够从CartItem直接访问模型非常方便,所以可以将模型与购物车中的项目相关联。假设Product您的应用程序中有一个模型。使用该associate()方法,您可以告诉购物车购物车中的商品与Product模型相关联。

这样你就可以直接访问你的模型CartItem

可以通过modelCartItem 上的属性访问该模型。

如果您的模型实现了Buyable界面并且您使用模型将项目添加到购物车,它将自动关联。

这是一个例子:

// First we'll add the item to the cart.
$cartItem = Cart::add('293ad', 'Product 1', 1, 9.99, ['size' => 'large']);

// Next we associate a model with the item.
Cart::associate($cartItem->rowId, 'Product');

// Or even easier, call the associate method on the CartItem!
$cartItem->associate('Product');

// You can even make it a one-liner
Cart::add('293ad', 'Product 1', 1, 9.99, ['size' => 'large'])->associate('Product');

// Now, when iterating over the content of the cart, you can access the model.
foreach(Cart::content() as $row) {
	echo 'You have ' . $row->qty . ' items of ' . $row->model->name . ' with description: "' . $row->model->description . '" in your cart.';
}

数据库 Database

数据库配置 Configuration

要将购物车保存到数据库中以便以后检索,包需要知道要使用的数据库连接以及表的名称。默认情况下,程序包将使用默认数据库连接并使用名为的表shoppingcart。如果要更改这些选项,则必须发布该config文件。

php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="config"

这将为您提供一个cart.php配置文件,您可以在其中进行更改。

为了让您的生活更轻松,该软件包还包括一个随时可以使用的服务migration,您可以通过运行来发布:

php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="migrations"

这会将shoppingcart表的迁移文件放入database/migrations目录中。现在,您只需运行php artisan migrate迁移数据库即可。

保存购物车到数据库 Storing the cart

要将购物车实例存储到数据库中,您必须调用该store($identifier)方法。其中$identifier是随机密钥,例如用户的ID或用户名。

Cart::store('username');

// To store a cart instance named 'wishlist'
Cart::instance('wishlist')->store('username');

从数据库恢复购物车 Restoring the cart

如果要从数据库中检索购物车并将其还原,您只需调用 restore($identifier)where $identifier是您为该store方法指定的键。

Cart::restore('username');

// To restore a cart instance named 'wishlist'
Cart::instance('wishlist')->restore('username');

异常 Exceptions

如果出现问题,Cart包将抛出异常。这样,使用Cart包调试代码或根据异常类型处理错误更容易。Cart包可以抛出以下异常:

Exception Reason
CartAlreadyStoredException When trying to store a cart that was already stored using the specified identifier
InvalidRowIDException When the rowId that got passed doesn't exists in the current cart instance
UnknownModelException When you try to associate an none existing model to a CartItem.

 

事件 Events

购物车还内置了活动。有五个活动可供您收听。

Event Fired Parameter
cart.added When an item was added to the cart. The CartItem that was added.
cart.updated When an item in the cart was updated. The CartItem that was updated.
cart.removed When an item is removed from the cart. The CartItem that was removed.
cart.stored When the content of a cart was stored. -
cart.restored When the content of a cart was restored. -

 

样例 Example

以下是如何在表格中列出购物车内容的一个小示例:

// Add some items in your Controller.
Cart::add('192ao12', 'Product 1', 1, 9.99);
Cart::add('1239ad0', 'Product 2', 2, 5.95, ['size' => 'large']);
// Display the content in a View.
<table>
   	<thead>
       	<tr>
           	<th>Product</th>
           	<th>Qty</th>
           	<th>Price</th>
           	<th>Subtotal</th>
       	</tr>
   	</thead>

   	<tbody>

   		<?php foreach(Cart::content() as $row) :?>

       		<tr>
           		<td>
               		<p><strong><?php echo $row->name; ?></strong></p>
               		<p><?php echo ($row->options->has('size') ? $row->options->size : ''); ?></p>
           		</td>
           		<td><input type="text" value="<?php echo $row->qty; ?>"></td>
           		<td>$<?php echo $row->price; ?></td>
           		<td>$<?php echo $row->total; ?></td>
       		</tr>

	   	<?php endforeach;?>

   	</tbody>
   	
   	<tfoot>
   		<tr>
   			<td colspan="2">&nbsp;</td>
   			<td>Subtotal</td>
   			<td><?php echo Cart::subtotal(); ?></td>
   		</tr>
   		<tr>
   			<td colspan="2">&nbsp;</td>
   			<td>Tax</td>
   			<td><?php echo Cart::tax(); ?></td>
   		</tr>
   		<tr>
   			<td colspan="2">&nbsp;</td>
   			<td>Total</td>
   			<td><?php echo Cart::total(); ?></td>
   		</tr>
   	</tfoot>
</table>
更新于:2018-07-14 17:31:08
返回顶部