Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rubenochoa's avatar

selected option value from dropdownmenu

Trying to get the day and time which choose the user: Having 2 dropdown menu, times and dates in my simple eshop project at shopping cart page(shopping-cart.blade.php).

index.blade.php

<option value="">--- Select Day ---</option>
@foreach ($days as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach

And here is the shopping-cart.blade.php:

@foreach ($products as $product)
        <li class="list-group-item">
        <img src="{{ $product['item']['imagePath'] }}" height="120" width="100">
            <span class="badge badge-secondary">Quantity: {{ $product['qty'] }}</span>
            <span class="badge badge-secondary">Item: {{ $product['item']['title'] }}</span>
            <span class="badge badge-secondary">Day: 
            
            </span>
            <span class="badge badge-secondary">Time:
            @foreach ($times as $key => $value)
             <option value="{{ $key }}"{{ ( $key == $times_id) ? 'selected' : '' }}>{{ $value }}</option>
             @endforeach
            </span>           
        </span>
            <span class="badge badge-secondary">Price: ${{ $product['price'] }}</span>                           
            <div class="btn-group">
                <button type="button" class="btn btn-primary btn-md dropdown-toggle" data-toggle="dropdown">Action
                    <span class="caret"></span></button>
                <ul class="dropdown-menu">
                    <li><a href="{{ route('product.reduceByOne', ['id' => $product['item']['id']]) }}">Reduce by 1</a>
                    </li>
                    <li><a href="{{ route('product.remove', ['id' => $product['item']['id']]) }}">Reduce All</a></li>
                </ul>
            </div>            
        </li>
        @endforeach
    </ul>
    </div> 
  </div>
</div>
<div class="container-fluid">
     <div class="row"> 
         <div class="col-md-4 m-auto">
        <strong>Total Cost: ${{ $totalPrice }}</strong>
        </ul>
    </div>
</div>
</div>
<hr>
<div class="container-fluid">
    <div class="row"> 
        <div class="col-md-4 m-auto">
        <button><a href="{{ route('checkout') }}" type="button" class="btb-btn-success">Checkout</button></a>
    </div>
</div>
</div>
@else
<div class="container-fluid">
    <div class="row"> 
        <div class="col-md-4 m-auto">
        <h1>No item to cart</h1>
        </ul>
    </div>
</div>
</div>
@endif
@endsection

ProductController

class ProductController extends Controller
{
    public function getIndex() 
    {
        $products = Product::all(); 
        $days = DB::table('days')->pluck("name1", "id");
        $times = DB::table('times')->pluck("name2", "id");
        return view('shop.index', compact('products', 'days', 'times'),  ['products' => $products]);
    }

    public function getAddToCart(Request $request, $id)
    {
        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        $cart->add($product, $product->id);

        $request->session()->put('cart', $cart);
        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 getCheckout()
    {
        if (!Session::has('cart')) {
            return view('shop.shopping-cart');
        }
        $oldCart = Session::get('cart');
        $cart = new Cart($oldCart);
        $total = $cart->totalPrice;
        
        return view('shop.checkout', ['total' => $total]);
    }

    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)
    {
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        $cart->removeItem($id);
        if (count($cart->items) > 0){
            Session::put('cart', $cart);
        } else{
            Session::forget('cart');
        }       
        return redirect()->route('product.shoppingCart');
    }
    public function postCheckout(Request $request)
    {
        if (!Session::has('cart')) {
            return redirect()->route('shop.shoppingCart');
        }
        $oldCart = Session::get('cart');
        $cart = new Cart($oldCart);
        \Stripe\Stripe::setApiKey('xxx');

        // Token is created using Stripe Checkout or Elements!
        // Get the payment token ID submitted by the form:
        if (isset($_POST['stripeToken'])){
            $token  = $_POST['stripeToken'];
        }
        try {
            $charge = \Stripe\Charge::create([
                'amount' => $cart->totalPrice * 100,                    
                'currency' => 'usd',
                'description' => Carbon::now().' '.$request->input('card-name'),
                'source' => "tok_mastercard",
            ]);

            $request->validate([
                'cardname' => 'max:35',
                'name' => 'max:12',
                'surname' => 'max:13',
            ]);
    
            $order = new Order();
            $order->cart = serialize($cart);                
            $order->cardname = $request->input('cardname'); 
            $order->name = $request->input('name'); 
            $order->surname = $request->input('surname');                
            $order->payment_id = $charge->id;
               
            Auth::user()->orders()->save($order);
        } catch(\Stripe\Exception\CardException $e) {
            $request->session()->flash('fail-message1', 'Your payment was declined.');
            return redirect()->route('checkout');
        } catch (\Stripe\Exception\RateLimitException $e) {
            $request->session()->flash('fail-message2', 'To many requests to the API.');
            return redirect()->route('checkout');
        } catch (\Stripe\Exception\InvalidRequestException $e) {
            $request->session()->flash('fail-message3', 'Invalid parameters.');
            return redirect()->route('checkout');
        } catch (\Stripe\Exception\AuthenticationException $e) {
            $request->session()->flash('fail-message4', 'There are problems with authentication.');
            return redirect()->route('checkout');
        } catch (\Stripe\Exception\ApiConnectionException $e) {
            $request->session()->flash('fail-message5', 'There is a problem with the network.');
            return redirect()->route('checkout');
        } catch (\Stripe\Exception\ApiErrorException $e) {
            $request->session()->flash('fail-message6', 'There is a problem with the API.');
            return redirect()->route('checkout');
        } catch (Exception $e) {
            $request->session()->flash('fail-message7', 'We don\'t know what happened.');
            return redirect()->route('checkout');
        }

        Mail::send('shop.order_confirmation', [
            'user' => Auth()->user(),
            'products' => $cart->items,
            'totalPrice' => $cart->totalPrice,
        ], function($message) use ($user) {
            $message->to($user->email);
            $message->from("@@gmail.com");
            $message->subject("Your order confirmation");
            $message->bcc("@@gmail.com");
        });         
        Session::forget('cart');

        return redirect()->route('product.index')->with('success', 'Successfully purchased products! | You will receive an oder confirmation at your email');
    }
}

More informations: https://flareapp.io/share/RmrOEDkP#F54

0 likes
6 replies
Lumethys's avatar

exactly what went wrong? please state your expected behavior and actual behavior

rubenochoa's avatar

@Lumethys The expected behavior is that $days and $times are undefined variable cause missing initial values for $days and $times and the actual behavior is that neither compact neither $days = DB::table('days')->pluck("name1","id"); do this.

Please or to participate in this conversation.