Laravel Tutorials
- What is laravel
- Laravel Installation
- Directory Structure
- htaccess
- Remove public from url
- Artisan Command
- Laravel Configuration
- Routing Configuration
- Namespaces
- Request
- Response
- Controller
- Model
- User Authentication
- Multi User Authentication
- Database Seeding
- Database
- Database Query
- ORM
- One-to-One Relationship
- One-to-Many Relationship
- Many to Many Eloquent Relationship
- Has One Through
- Has Many Through
- Querying Relations
- Middleware
- Laravel Views
- Blade Views
- Print data on view page
- Get Site URL
- Get URL Segment
- Get images from Storage folder
- Clear cache
- Form Class not found
- Flash Message in laravel
- Redirections
- path
- CRUD Projerct
- CRUD in Laravel
- CRUD progran
- Laravel Validation
- Jquery Validation
- Cookie
- Session
- Email Send in laravel
- File uploading
- CSRF Protection
- Helper in Laravel
- Helper Functions
- Guzzle Http Client
- Paypal Payment Gatway Integration
- Cron Job in laravel
- Flash message
- path
- Errors Handling
- Date Format
- Date Format Validation
- Display Image on View Page
- Update User Status using toggle button
- Delete Multiple Records using Checkbox in Laravel?
- Confirmation Before Delete Record
- Delete image from storage
- Remove/Trim Empty & Whitespace From Input Requests
- Block IP Addresses from Accessing Website
- How to Disable New User Registration in Laravel
- Redirect HTTP To HTTPS Using Laravel Middleware
- CKEditor
- slug generate unique
- Prevent Browser's Back Button After Logout
- Datatable dunamically
- encrypt & Decript
- Download File
- Rest API
- Shopping Cart
- Shopping Cart Example
- Dynamic Category-Subcategory Menu
- Ajax Search
- Interview Question
- laravel Tutorilal link
- laravel Tutorilal
Important Links
How to install shopping Cart in laravel?
https://packagist.org/packages/darryldecode/cart
https://github.com/darryldecode/laravelshoppingcart
https://salitha94.blogspot.com/2019/11/create-shopping-cart-with-laravel-6-part-1.html
Install Shopping Cart Package
composer require "darryldecode/cart:~4.0"
############ OR ############
composer require "darryldecode/cart"
CONFIGURATION
Add service providers array in config/app.php
File name : app.php
Darryldecode\Cart\CartServiceProvider::class
Open config/app.php and add this line to your Aliases
'Cart' => Darryldecode\Cart\Facades\CartFacade::class
Configuration
File name : index.php
php artisan vendor:publish
This will publish the config file to config/cartalyst.cart.php where you can modify the package configuration.
Optional configuration file (useful if you plan to have full control)
File name : index.php
php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="config"
Quick Usage Example
File name : index.php
$Product = Product::find($productId); // assuming you have a Product model with id, name, description & price
$rowId = 456; // generate a unique() row ID
$userID = 2; // the user ID to bind the cart contents
// add the product to cart
\Cart::session($userID)->add(array(
'id' => $rowId,
'name' => $Product->name,
'price' => $Product->price,
'quantity' => 4,
'attributes' => array(),
'associatedModel' => $Product
));
// update the item on cart
\Cart::session($userID)->update($rowId,[
'quantity' => 2,
'price' => 98.67
]);
// delete an item on cart
\Cart::session($userID)->remove($rowId);
// view the cart items
$items = \Cart::getContent();
foreach($items as $row) {
echo $row->id; // row ID
echo $row->name;
echo $row->qty;
echo $row->price;
echo $item->associatedModel->id; // whatever properties your model have
echo $item->associatedModel->name; // whatever properties your model have
echo $item->associatedModel->description; // whatever properties your model have
}
// FOR FULL USAGE, SEE BELOW..
IMPORTANT NOTE!
By default, the cart has a default sessionKey that holds the cart data. This also serves as a cart unique identifier which you can use to bind a cart to a specific user. To override this default session Key, you will just simply call the \Cart::session($sessionKey) method BEFORE ANY OTHER METHODS!!.
File name : index.php
$userId // the current login user id
// This tells the cart that we only need or manipulate
// the cart data of a specific user. It doesn't need to be $userId,
// you can use any unique key that represents a unique to a user or customer.
// basically this binds the cart to a specific user.
\Cart::session($userId);
// then followed by the normal cart usage
\Cart::add();
\Cart::update();
\Cart::remove();
\Cart::condition($condition1);
\Cart::getTotal();
\Cart::getSubTotal();
\Cart::addItemCondition($productID, $coupon101);
// and so on..
How to add item in cart?
File name : index.php
// Simplest form to add item on your cart
Cart::add(455, 'Sample Item', 100.99, 2, array());
// array format
Cart::add(array(
'id' => 456, // inique row ID
'name' => 'Sample Item',
'price' => 67.99,
'quantity' => 4,
'attributes' => array()
));
// add multiple items at one time
Cart::add(array(
array(
'id' => 456,
'name' => 'Sample Item 1',
'price' => 67.99,
'quantity' => 4,
'attributes' => array()
),
array(
'id' => 568,
'name' => 'Sample Item 2',
'price' => 69.25,
'quantity' => 4,
'attributes' => array(
'size' => 'L',
'color' => 'blue'
)
),
));
// add cart items to a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->add(array(
'id' => 456, // inique row ID
'name' => 'Sample Item',
'price' => 67.99,
'quantity' => 4,
'attributes' => array(),
'associatedModel' => $Product
));
// NOTE:
// Please keep in mind that when adding an item on cart, the "id" should be unique as it serves as
// row identifier as well. If you provide same ID, it will assume the operation will be an update to its quantity
// to avoid cart item duplicates
Updating an item on a cart: Cart::update()
Cart::update(456, array(
'name' => 'New Item Name', // new item name
'price' => 98.67, // new item price, price can also be a string format like so: '98.67'
));
// you may also want to update a product's quantity
Cart::update(456, array(
'quantity' => 2, // so if the current product has a quantity of 4, another 2 will be added so this will result to 6
));
// you may also want to update a product by reducing its quantity, you do this like so:
Cart::update(456, array(
'quantity' => -1, // so if the current product has a quantity of 4, it will subtract 1 and will result to 3
));
// NOTE: as you can see by default, the quantity update is relative to its current value
// if you want to just totally replace the quantity instead of incrementing or decrementing its current quantity value
// you can pass an array in quantity value like so:
Cart::update(456, array(
'quantity' => array(
'relative' => false,
'value' => 5
),
));
// so with that code above as relative is flagged as false, if the item's quantity before is 2 it will now be 5 instead of
// 5 + 2 which results to 7 if updated relatively..
// updating a cart for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->update(456, array(
'name' => 'New Item Name', // new item name
'price' => 98.67, // new item price, price can also be a string format like so: '98.67'
));
Removing an item on a cart: Cart::remove()
File name : index.php
Cart::remove(456);
// removing cart item for a specific user's cart
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->remove(456);
Getting an item on a cart: Cart::get()
/**
* get an item on a cart by item ID
* if item ID is not found, this will return null
*
* @param $itemId
* @return null|array
*/
$itemId = 456;
Cart::get($itemId);
// You can also get the sum of the Item multiplied by its quantity, see below:
$summedPrice = Cart::get($itemId)->getPriceSum();
// get an item on a cart by item ID for a specific user's cart
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->get($itemId);
Getting cart's contents and count: Cart::getContent()
/**
* get the cart
*
* @return CartCollection
*/
$cartCollection = Cart::getContent();
// NOTE: Because cart collection extends Laravel's Collection
// You can use methods you already know about Laravel's Collection
// See some of its method below:
// count carts contents
$cartCollection->count();
// transformations
$cartCollection->toArray();
$cartCollection->toJson();
// Getting cart's contents for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->getContent($itemId);
Check if cart is empty: Cart::isEmpty()
/**
* check if cart is empty
*
* @return bool
*/
Cart::isEmpty();
// Check if cart's contents is empty for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->isEmpty();
Get cart total quantity: Cart::getTotalQuantity()
File name : index.php
/**
* get total quantity of items in the cart
*
* @return int
*/
$cartTotalQuantity = Cart::getTotalQuantity();
// for a specific user
$cartTotalQuantity = Cart::session($userId)->getTotalQuantity();
Get cart subtotal: Cart::getSubTotal()
/**
* get cart sub total
*
* @return float
*/
$subTotal = Cart::getSubTotal();
// for a specific user
$subTotal = Cart::session($userId)->getSubTotal();
Get cart total: Cart::getTotal()
/**
* the new total in which conditions are already applied
*
* @return float
*/
$total = Cart::getTotal();
// for a specific user
$total = Cart::session($userId)->getTotal();
Clearing the Cart: Cart::clear()
File name : index.php
/**
* clear cart
*
* @return void
*/
Cart::clear();
Cart::session($userId)->clear();
Conditions
File name : index.php
Laravel Shopping Cart supports cart conditions. Conditions are very useful in terms of (coupons,discounts,sale,per-item sale and discounts etc.) See below carefully on how to use conditions.
Conditions can be added on:
1.) Whole Cart Value bases
2.) Per-Item Bases
When adding a condition on a cart bases, the 'target' should have value of 'subtotal' or 'total'. If the target is "subtotal" then this condition will be applied to subtotal. If the target is "total" then this condition will be applied to total. The order of operation also during calculation will vary on the order you have added the conditions.
Also, when adding conditions, the 'value' field will be the bases of calculation. You can change this order by adding 'order' parameter in CartCondition.
// add single condition on a cart bases
$condition = new \Darryldecode\Cart\CartCondition(array(
'name' => 'VAT 12.5%',
'type' => 'tax',
'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
'value' => '12.5%',
'attributes' => array( // attributes field is optional
'description' => 'Value added tax',
'more_data' => 'more data here'
)
));
Cart::condition($condition);
Cart::session($userId)->condition($condition); // for a speicifc user's cart
// or add multiple conditions from different condition instances
$condition1 = new \Darryldecode\Cart\CartCondition(array(
'name' => 'VAT 12.5%',
'type' => 'tax',
'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
'value' => '12.5%',
'order' => 2
));
$condition2 = new \Darryldecode\Cart\CartCondition(array(
'name' => 'Express Shipping $15',
'type' => 'shipping',
'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
'value' => '+15',
'order' => 1
));
Cart::condition($condition1);
Cart::condition($condition2);
// Note that after adding conditions that are targeted to be applied on subtotal, the result on getTotal()
// will also be affected as getTotal() depends in getSubTotal() which is the subtotal.
// add condition to only apply on totals, not in subtotal
$condition = new \Darryldecode\Cart\CartCondition(array(
'name' => 'Express Shipping $15',
'type' => 'shipping',
'target' => 'total', // this condition will be applied to cart's total when getTotal() is called.
'value' => '+15',
'order' => 1 // the order of calculation of cart base conditions. The bigger the later to be applied.
));
Cart::condition($condition);
// The property 'order' lets you control the sequence of conditions when calculated. Also it lets you add different conditions through for example a shopping process with multiple
// pages and still be able to set an order to apply the conditions. If no order is defined defaults to 0
// NOTE!! On current version, 'order' parameter is only applicable for conditions for cart bases. It does not support on per item conditions.
// or add multiple conditions as array
Cart::condition([$condition1, $condition2]);
// To get all applied conditions on a cart, use below:
$cartConditions = Cart::getConditions();
foreach($cartConditions as $condition)
{
$condition->getTarget(); // the target of which the condition was applied
$condition->getName(); // the name of the condition
$condition->getType(); // the type
$condition->getValue(); // the value of the condition
$condition->getOrder(); // the order of the condition
$condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added
}
// You can also get a condition that has been applied on the cart by using its name, use below:
$condition = Cart::getCondition('VAT 12.5%');
$condition->getTarget(); // the target of which the condition was applied
$condition->getName(); // the name of the condition
$condition->getType(); // the type
$condition->getValue(); // the value of the condition
$condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added
// You can get the conditions calculated value by providing the subtotal, see below:
$subTotal = Cart::getSubTotal();
$condition = Cart::getCondition('VAT 12.5%');
$conditionCalculatedValue = $condition->getCalculatedValue($subTotal);
NOTE: All cart based conditions should be added to cart's conditions before calling Cart::getTotal() and if there are also conditions that are targeted to be applied to subtotal, it should be added to cart's conditions before calling Cart::getSubTotal()
$cartTotal = Cart::getSubTotal(); // the subtotal with the conditions targeted to "subtotal" applied
$cartTotal = Cart::getTotal(); // the total with the conditions targeted to "total" applied
$cartTotal = Cart::session($userId)->getSubTotal(); // for a specific user's cart
$cartTotal = Cart::session($userId)->getTotal(); // for a specific user's cart
Next is the Condition on Per-Item Bases.
This is very useful if you have coupons to be applied specifically on an item and not on the whole cart value.
NOTE: When adding a condition on a per-item bases, the 'target' parameter is not needed or can be omitted. unlike when adding conditions or per cart bases.
// lets create first our condition instance
$saleCondition = new \Darryldecode\Cart\CartCondition(array(
'name' => 'SALE 5%',
'type' => 'tax',
'value' => '-5%',
));
// now the product to be added on cart
$product = array(
'id' => 456,
'name' => 'Sample Item 1',
'price' => 100,
'quantity' => 1,
'attributes' => array(),
'conditions' => $saleCondition
);
// finally add the product on the cart
Cart::add($product);
// you may also add multiple condition on an item
$itemCondition1 = new \Darryldecode\Cart\CartCondition(array(
'name' => 'SALE 5%',
'type' => 'sale',
'value' => '-5%',
));
$itemCondition2 = new CartCondition(array(
'name' => 'Item Gift Pack 25.00',
'type' => 'promo',
'value' => '-25',
));
$itemCondition3 = new \Darryldecode\Cart\CartCondition(array(
'name' => 'MISC',
'type' => 'misc',
'value' => '+10',
));
$item = array(
'id' => 456,
'name' => 'Sample Item 1',
'price' => 100,
'quantity' => 1,
'attributes' => array(),
'conditions' => [$itemCondition1, $itemCondition2, $itemCondition3]
);
Cart::add($item);
NOTE: All cart per-item conditions should be added before calling Cart::getSubTotal()
Then Finally you can call Cart::getSubTotal() to get the Cart sub total with the applied conditions on each of the items.
// the subtotal will be calculated based on the conditions added that has target => "subtotal"
// and also conditions that are added on per item
$cartSubTotal = Cart::getSubTotal();
Add condition to existing Item on the cart: Cart::addItemCondition($productId, $itemCondition)
Adding Condition to an existing Item on the cart is simple as well.
This is very useful when adding new conditions on an item during checkout process like coupons and promo codes. Let's see the example how to do it:
$productID = 456;
$coupon101 = new CartCondition(array(
'name' => 'COUPON 101',
'type' => 'coupon',
'value' => '-5%',
));
Cart::addItemCondition($productID, $coupon101);
Clearing Cart Conditions: Cart::clearCartConditions()
/**
* clears all conditions on a cart,
* this does not remove conditions that has been added specifically to an item/product.
* If you wish to remove a specific condition to a product, you may use the method: removeItemCondition($itemId,$conditionName)
*
* @return void
*/
Cart::clearCartConditions()
Remove Specific Cart Condition: Cart::removeCartCondition($conditionName)
$conditionName = 'Summer Sale 5%';
Cart::removeCartCondition($conditionName)
Remove Specific Item Condition: Cart::removeItemCondition($itemId, $conditionName)
Cart::removeItemCondition($itemId, $conditionName)
Clear all Item Conditions: Cart::clearItemConditions($itemId)
Cart::clearItemConditions($itemId)
Get conditions by type: Cart::getConditionsByType($type)
public function getConditionsByType($type)
Remove conditions by type: Cart::removeConditionsByType($type)
public function removeConditionsByType($type)
Items
The method Cart::getContent() returns a collection of items.
To get the id of an item, use the property $item->id.
To get the name of an item, use the property $item->name.
To get the quantity of an item, use the property $item->quantity.
To get the attributes of an item, use the property $item->attributes.
To get the price of a single item without the conditions applied, use the property $item->price.
To get the subtotal of an item without the conditions applied, use the method $item->getPriceSum().
public function getPriceSum()