Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use App\Http\Controllers\Controller;
- use \App\User;
- use \App\Food;
- interface PagesInterface
- {
- public function index();
- public function food();
- public function addToCart($id);
- public function update(Request $request);
- public function remove(Request $request);
- }
- class PagesController extends Controller implements PagesInterface
- {
- public function index(){
- $users = User::all();
- return view('pages.index', ['users' => $users]);
- }
- public function food(){
- $foods = Food::all();
- return view('food.index', ['foods' => $foods]);
- }
- public function addToCart($id)
- {
- $food = Food::find($id);
- if(!$food) {
- abort(404);
- }
- $cart = session()->get('cart');
- // if cart is empty then this the first product
- if(!$cart) {
- $cart = [
- $id => [
- "name" => $food->name,
- "quantity" => 1,
- "price_big" => $food->price_big,
- "image" => $food->image
- ]
- ];
- session()->put('cart', $cart);
- return redirect()->back()->with('success', 'Product added to cart successfully!');
- }
- // if cart not empty then check if this product exist then increment quantity
- if(isset($cart[$id])) {
- $cart[$id]['quantity']++;
- session()->put('cart', $cart);
- return redirect()->back()->with('success', 'Product added to cart successfully!');
- }
- // if item not exist in cart then add to cart with quantity = 1
- $cart[$id] = [
- "name" => $food->name,
- "quantity" => 1,
- "price_big" => $food->price_big,
- "image" => $food->image
- ];
- session()->put('cart', $cart);
- return redirect()->back()->with('success', 'Product added to cart successfully!');
- }
- public function update(Request $request)
- {
- if($request->id and $request->quantity)
- {
- $cart = session()->get('cart');
- $cart[$request->id]["quantity"] = $request->quantity;
- session()->put('cart', $cart);
- session()->flash('success', 'Cart updated successfully');
- }
- }
- public function remove(Request $request)
- {
- if($request->id) {
- $cart = session()->get('cart');
- if(isset($cart[$request->id])) {
- unset($cart[$request->id]);
- session()->put('cart', $cart);
- }
- session()->flash('success', 'Product removed successfully');
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement