0% found this document useful (0 votes)
66 views

Laravel Cart

The document outlines the routes, models, controllers, and cart logic for an e-commerce application built with Laravel. Key routes include product listing, user authentication, adding/removing from cart, and checkout. Models defined include Product, Order, User. Controllers manage authentication, user profile, cart, and checkout. The Cart class facilitates adding/removing items and calculating totals.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Laravel Cart

The document outlines the routes, models, controllers, and cart logic for an e-commerce application built with Laravel. Key routes include product listing, user authentication, adding/removing from cart, and checkout. Models defined include Product, Order, User. Controllers manage authentication, user profile, cart, and checkout. The Cart class facilitates adding/removing items and calculating totals.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 14

laravel cart

//routes

Route::get('/', function () {

return view('shop.index');

});

Route::get('/', [

'uses' => 'ProductController@getIndex',

'as' => 'product.index'

]);

Route::group(['prefix' => 'user'], function(){

Route::group(['middleware' => 'guest'], function() {

Route::get('signup', [

'uses' => 'userController@getSignup',

'as' => 'user.signup',

]);

Route::post('signup', [

'uses' => 'userController@postSignup',

'as' => 'user.signup',

]);

Route::get('signin', [

'uses' => 'userController@getSignin',

'as' => 'user.signin',

]);

Route::post('signin', [

'uses' => 'userController@postSignin',


'as' => 'user.signin',

]);

});

Route::group(['middleware' => 'auth'], function() {

Route::get('profile', [

'uses' => 'userController@getProfile',

'as' => 'user.profile',

]);

Route::get('logout', [

'uses' => 'userController@getLogout',

'as' => 'user.logout',

]);

});

});

Route::get('add-to-cart/{id}',[

'uses' => 'ProductController@getAddToCart',

'as' => 'product.addToCart'

]);

Route::get('shopping-cart', [

'uses' => 'ProductController@getCart',

'as' => 'product.shoppingCart'


]);

Route::get('checkout',[

'uses' => 'productController@postCheckout',

'as' => 'checkout',

'middleware' =>'auth'

]);

Route::get('reduce/{id}',[

'uses' => 'productController@getReduceByOne',

'as' => 'product.reduceByOne'

]);

Route::get('remove/{id}',[

'uses'=>'productController@getRemoveItem',

'as' => 'product.remove'

]);

Route::get('remove/{id}',[

'uses'=>'productController@getRemoveItem',

'as' => 'product.remove'

]);

//migrations

class CreateProductsTable extends Migration

/**

* Run the migrations.

* @return void

*/
public function up()

Schema::create('products', function (Blueprint $table) {

$table->increments('id');

$table->timestamps();

$table->string('imagePath');

$table->string('title');

$table->text('description');

$table->integer('price');

});

class CreateOrdersTable extends Migration

/**

* Run the migrations.

* @return void

*/

public function up()

Schema::create('orders', function (Blueprint $table) {

$table->increments('id');

$table->timestamps();

$table->integer('user_id');

$table->text('cart');

});

}
//models

App\user

public function orders(){

return $this->hasMany('App\Order');

class Product extends Model

//protected $fillable=['imagePath','title','description','price'];

public $timestamp =false;

public $primaryKey = 'item_id';

public $table = 'item';

public $timestamps = false;

protected $fillable = ['description','sell_price','cost_price','img_path'

];

public function orders(){

//return $this->belongToMany('App\Order','orderline','item_id','orderinfo_id');

return $this->belongToMany('App\Order','orderline');

class Product extends Model

//protected $fillable=['imagePath','title','description','price'];

public $timestamp =false;


public $primaryKey = 'item_id';

public $table = 'item';

public $timestamps = false;

protected $fillable = ['description','sell_price','cost_price','img_path'

];

public function orders(){

//return $this->belongToMany('App\Order','orderline','item_id','orderinfo_id');

return $this->belongToMany('App\Order','orderline');

class Order extends Model

protected $table = 'orderinfo';

protected $primaryKey = 'orderinfo_id';

public $timestamps = false;

public function user(){

return $this->belongsTo('App\User');

public function items(){

return $this->belongsToMany('App\Item','orderline','orderinfo_id','item_id');

//cart model
<?php

namespace App;

use Session;

class Cart

public $items = null;

public $totalQty = 0;

public $totalPrice = 0;

public function __construct($oldCart) {

if($oldCart) {

$this->items = $oldCart->items;

$this->totalQty = $oldCart->totalQty;

$this->totalPrice = $oldCart->totalPrice;

public function add($item, $id){

//dd($this->items);

$storedItem = ['qty'=>0, 'price'=>$item->sell_price, 'item'=> $item];

if ($this->items){

if (array_key_exists($id, $this->items)){

$storedItem = $this->items[$id];

//$storedItem['qty'] += $item->qty;

$storedItem['qty']++;

$storedItem['price'] = $item->sell_price * $storedItem['qty'];

$this->items[$id] = $storedItem;

$this->totalQty++;
$this->totalPrice += $item->sell_price;

public function reduceByOne($id){

$this->items[$id]['qty']--;

$this->items[$id]['price']-= $this->items[$id]['item']['sell_price'];

$this->totalQty --;

$this->totalPrice -= $this->items[$id]['item']['sell_price'];

if ($this->items[$id]['qty'] <= 0) {

unset($this->items[$id]);

public function removeItem($id){

$this->totalQty -= $this->items[$id]['qty'];

$this->totalPrice -= $this->items[$id]['price'];

unset($this->items[$id]);

//usercontroller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use Auth;

class UserController extends Controller

{
public function getSignup(){

return view('user.signup');

public function postSignup(Request $request){

$this->validate($request, [

'email' => 'email| required| unique:users',

'password' => 'required| min:4'

]);

$user = new User([

'name' => $request->input('name'),

'email' => $request->input('email'),

'password' => bcrypt($request->input('password'))

]);

$user->save();

Auth::login($user);

return redirect()->route('user.profile');

public function getSignin(){

return view('user.signin');

public function postSignin(Request $request){

$this->validate($request, [

'email' => 'email| required',

'password' => 'required| min:4'

]);

if(Auth::attempt(['email' => $request->input('email'),'password' =>


$request->input('password')])){

return redirect()->route('user.profile');
}else{

return redirect()->back();

};

public function getProfile(){

//$orders = Auth::user()->with('orders')->get();

$orders = Auth::user()->orders;

//dd($orders);

$orders->transform(function($order, $key){

$order->cart = unserialize($order->cart);

return $order;

});

//dd($orders);

return view('user.profile',compact('orders'));

public function getLogout(){

Auth::logout();

return redirect()->route('product.index');

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Product;

use Session;

use App\Cart;

use App\Order;

use App\Customer;

use Auth;

use App\Item;

use DB;

class ProductController extends Controller

public function getIndex(){

$products = \App\Product::all();

return view('shop.index',compact('products'));

public function getAddToCart(Request $request , $id){

$product = Product::find($id);

/*

if (Session::has('cart')){

$oldCart = Session::get('cart');

$cart['items'][$id] = $product->item_id;

$cart['items']['sell_price'] = $product->sell_price;

$cart['items']['qty'] = 1;

$cart = array_merge($oldCart,$cart);

Session:push('cart',$cart);
}*/

/*else

Session::put('cart',$cart);*/

//dd(Session::has('cart'));

// $cart = Session::has('cart') ? Session::get('cart') : null;

//dd($cart);

$oldCart = Session::has('cart') ? $request->session()->get('cart'):null;

//$cart = Session::has('cart') ? Session::get('cart') : null;

//dd($oldCart);

$cart = new Cart($oldCart);

$cart->add($product, $product->item_id);

$request->session()->put('cart', $cart);

Session::put('cart', $cart);

$request->session()->save();

//dd(Session::all());

//return redirect()->route('product.index');

return redirect()->route('product.index');

public function getCart() {

if (!Session::has('cart')) {

return view('shop.shopping-cart');

$oldCart = Session::get('cart');

$cart = new Cart($oldCart);

return view('shop.shopping-cart', ['products' => $cart->items, 'totalPrice'


=> $cart->totalPrice]);

}
public function getSession(){

Session::flush();

public function postCheckout(Request $request){

if (!Session::has('cart')) {

return redirect()->route('product.shoppingCart');

$oldCart = Session::get('cart');

$cart = new Cart($oldCart);

try {

DB::beginTransaction();

$order = new Order();

try {

$order = new Order();

$order->cart = serialize($cart);

Auth::user()->orders()->save($order);

}catch (\Exception $e) {

return redirect()->route('checkout')->with('error', $e->getMessage());

Session::forget('cart');

return redirect()->route('product.index')->with('success','Successfully
Purchased Your Products!!!');

}
public function getReduceByOne($id){

$oldCart = Session::has('cart') ? Session::get('cart') : null;

$cart = new Cart($oldCart);

$cart->reduceByOne($id);

if (count($cart->items) > 0) {

Session::put('cart',$cart);

}else{

Session::forget('cart');

return redirect()->route('product.shoppingCart');

public function getRemoveItem($id){

$oldCard = Session::has('cart') ? Session::get('cart') : null;

$cart = new Cart($oldCard);

$cart->removeItem($id);

if (count($cart->items) > 0) {

Session::put('cart',$cart);

}else{

Session::forget('cart');

return redirect()->route('product.shoppingCart');

You might also like