rubenochoa's avatar

Undefined $variable creating dependent dropdown bookable activity

Project: bookable activity Error: Undefined variable $days Description: creating mini-eshop which you can choose if you want to go for riding, doing arts or do guided tour. User have to choose 3 of the activities by choosing time and day which are inserted manually at database managment.

web.php

//use db;

Route::get('product.index','ProductController@getDates');
Route::get('product.index/gettimes/{id}','ProductController@getTimes');

index.blade.php

section('title')
    Shopping Cart
@endsection
@section('content')    
    @foreach($products->chunk(3) as $productsChunk)
        <div class="row">
            @foreach($productsChunk as $products)
                <div class="col-sm-4 col-md-4">
                    <div class="thumbnail">
                        <img src="{{ $products->imagePath }}" alt="..." class="img-responsive">
                        <div class="caption">
                            <h3>{{ $products->title }}</h3>
                            <p class="description">{{ $products->description }}</p>
                            <div class="clearfix">
                            <script type="text/javascript">
                                jQuery(document).ready(function ()
                                {
                                        jQuery('select[day="day"]').on('change',function(){
                                        var dayID = jQuery(this).val();
                                        if(dayID)
                                        {
                                            jQuery.ajax({
                                                url : 'shop.index/getdates/' +dayId,
                                                type : "GET",
                                                dataType : "json",
                                                success:function(data)
                                                {
                                                    console.log(data);
                                                    jQuery('select[day="day"]').empty();
                                                    jQuery.each(data, function(key,value){
                                                    $('select[day="day"]').append('<option value="'+ key +'">'+ value +'</option>');
                                                    });
                                                }
                                            });
                                        }
                                        else
                                        {
                                            $('select[day="day"]').empty();
                                        }
                                        });
                                });
                                </script> 
                                <div class="container">                            <
                             <div class="form-group">
                            <label for="days">Select Day:</label>
                            <select day="day" class="form-control" style="width:250px">
                                <option value="">--- Select Day ---</option>
                                @foreach ($days as $key => $value)
                                <option value="{{ $key }}">{{ $value }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="time">Select Time:</label>
                            <select time="time" class="form-control"style="width:250px">
                            <option>--Time--</option>
                            </select>
                        </div>
                </div>
                            <script type="text/javascript">
                            jQuery(document).ready(function ()
                            {
                                    jQuery('select[time="time"]').on('change',function(){
                                    var times_id = jQuery(this).val();
                                    if(timesID)
                                    {
                                        jQuery.ajax({
                                            url : 'index/getindex/' +timesId,
                                            type : "GET",
                                            dataType : "json",
                                            success:function(data)
                                            {
                                                console.log(data);
                                                jQuery('select[time="time"]').empty();
                                                jQuery.each(data, function(key,value){
                                                $('select[time="time"]').append('<option value="'+ key +'">'+ value +'</option>');
                                                });
                                            }
                                        });
                                    }
                                    else
                                    {
                                        $('select[time="time"]').empty();
                                    }
                                    });
                            });
                </script>                  
                                <div class="pull-left price">${{ $products->price }}</div>
                                <a href="{{ route('product.addToCart', ['id' => $products->id]) }}"
                                   class="btn btn-success pull-right" role="button">Add to cart</a>
                            </div>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>
    @endforeach
@endsection

productController.php classes

class ProductController extends Controller
{
    public function getIndex()
    {
        $products = Product::all();
        return view('shop.index', ['products' => $products]);
    }

    public function getDates()
    {
        $days = DB::table('days')->pluck("day","id");
        return view('shop.index',compact('days'));
    }

    public function getTimes($id) 
    {
        $times = DB::table("times")->where("time_id",$id)->pluck("time","dayoftime","id");
        return json_encode($times);
    }

    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('sk_test_ptSt4XL8KRmHvbdVAsvC7bAk00EOC00h7u');

            // 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');
    }    
}

migration days

public function up()
    {
        Schema::create('days', function (Blueprint $table) {
            $table->increments('id');
            $table->string('day');
            $table->timestamps();
        });
    }

migration times:

public function up()
    {
        Schema::create('times', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('times_id');
            $table->string('dayoftime');
            $table->string('time');
            $table->timestamps();
        });
    }

index.blade.php else shop.index

@section('title')
    Shopping Cart
@endsection
@section('content')    
    @foreach($products->chunk(3) as $productsChunk)
        <div class="row">
            @foreach($productsChunk as $products)
                <div class="col-sm-4 col-md-4">
                    <div class="thumbnail">
                        <img src="{{ $products->imagePath }}" alt="..." class="img-responsive">
                        <div class="caption">
                            <h3>{{ $products->title }}</h3>
                            <p class="description">{{ $products->description }}</p>
                            <div class="clearfix">
                            <script type="text/javascript">
                                jQuery(document).ready(function ()
                                {
                                        jQuery('select[day="day"]').on('change',function(){
                                        var dayID = jQuery(this).val();
                                        if(dayID)
                                        {
                                            jQuery.ajax({
                                                url : 'shop.index/getdates/' +dayID,
                                                type : "GET",
                                                dataType : "json",
                                                success:function(data)
                                                {
                                                    console.log(data);
                                                    jQuery('select[name="time"]').empty();
                                                    jQuery.each(data, function(key,value){
                                                    $('select[name="time"]').append('<option value="'+ key +'">'+ value +'</option>');
                                                    });
                                                }
                                            });
                                        }
                                        else
                                        {
                                            $('select[time="time"]').empty();
                                        }
                                        });
                                });
                                </script> 
                                <div class="container">
                            <h2>Dependent Dropdown</h2>
                             <div class="form-group">
                            <label for="days">Select Day:</label>
                            <select day="day" class="form-control" style="width:250px">
                                <option value="">--- Select Day ---</option>
                                @foreach ($days as $key => $value)
                                <option value="{{ $key }}">{{ $value }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="time">Select Time:</label>
                            <select name="time" class="form-control"style="width:250px">
                            <option>--Time--</option>
                            </select>
                        </div>
                </div>
                            <script type="text/javascript">
                            jQuery(document).ready(function ()
                            {
                                    jQuery('select[day="day"]').on('change',function(){
                                    var countryID = jQuery(this).val();
                                    if(countryID)
                                    {
                                        jQuery.ajax({
                                            url : 'index/getdates/' +dayID,
                                            type : "GET",
                                            dataType : "json",
                                            success:function(data)
                                            {
                                                console.log(data);
                                                jQuery('select[time="time"]').empty();
                                                jQuery.each(data, function(key,value){
                                                $('select[time="time"]').append('<option value="'+ key +'">'+ value +'</option>');
                                                });
                                            }
                                        });
                                    }
                                    else
                                    {
                                        $('select[time="time"]').empty();
                                    }
                                    });
                            });
                </script>                  
                                <div class="pull-left price">${{ $products->price }}</div>
                                <a href="{{ route('product.addToCart', ['id' => $products->id]) }}"
                                   class="btn btn-success pull-right" role="button">Add to cart</a>
                            </div>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>
    @endforeach
@endsection
0 likes
12 replies
priyalaks's avatar

Can you show ur Product controller ? You have pasted web.php content in ur product controller.php in your query .

rubenochoa's avatar

@Sinnbeck i got your point and i posted(updated) all the code. The url is shop.index as you see at productcontroller

Sinnbeck's avatar

Here you use the same view but pass completely different data to it?

    public function getIndex()
    {
        $products = Product::all();
        return view('shop.index', ['products' => $products]);
    }

    public function getDates()
    {
        $days = DB::table('days')->pluck("day","id");
        return view('shop.index',compact('days'));
    }
rubenochoa's avatar

@Sinnbeck yes. the first (getindex)are the items(activities) and the getdates are the days and times if i got you right.

Sinnbeck's avatar

@rubenochoa I assume it's a mistake. If you need dates and products in the view, you need to pass both. And then the methods are identical. Not sure what are trying to do

rubenochoa's avatar

@Sinnbeck Yes indeed, days and products must be together so i take off getDates() and use the getIndex() by doing that

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

and found the variable $days but not times.

rubenochoa's avatar
rubenochoa
OP
Best Answer
Level 2

Solution:

at index.blade.php was needed:

<label for="time">Select Time:</label>
                                                <select name2="time" class="form-control"style="width:250px">
                                                <option value="">--Time--</option>
                                                @foreach ($times as $key => $value)
                                                    <option value="{{ $key }}">{{ $value }}</option>
                                                    @endforeach
                                                </select>

and productController.php:

$products = Product::all(); 
        $days = DB::table('days')->pluck("name1","id");
        $times = DB::table('times')->pluck("name2","id");
        return view('shop.index',compact('days','times'), ['products' => $products]);

Please or to participate in this conversation.