Home > Software engineering >  Undefined $variable by creating dependent dropdown bookable activity
Undefined $variable by creating dependent dropdown bookable activity

Time:10-10

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.
More error details: at https://flareapp.io/share/Bm0jQD07#F47
Update: According to your ideas 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.

web.php

//use db;

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

productcontroller

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 >
            @foreach($productsChunk as $products)
                <div >
                    <div >
                        <img src="{{ $products->imagePath }}" alt="..." >
                        <div >
                            <h3>{{ $products->title }}</h3>
                            <p >{{ $products->description }}</p>
                            <div >
                            <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 >
                            <h2>Dependent Dropdown</h2>
                             <div >
                            <label for="days">Select Day:</label>
                            <select day="day"  style="width:250px">
                                <option value="">--- Select Day ---</option>
                                @foreach ($days as $key => $value)
                                <option value="{{ $key }}">{{ $value }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div >
                            <label for="time">Select Time:</label>
                            <select name="time" 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 >${{ $products->price }}</div>
                                <a href="{{ route('product.addToCart', ['id' => $products->id]) }}"
                                    role="button">Add to cart</a>
                            </div>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>
    @endforeach
@endsection

CodePudding user response:

While looking at the code for Controller...

You are calling getDates method of ProductsController which opens the index.blade.php inside shops folder in resources...

public function getDates() // shop.index needs both $products and $days
{
    $days = DB::table('days')->pluck("day","id");
    return view('shop.index',compact('days')); // No Products sent.. 
}

Index has $product ... so when u open the index page from getDates method it wont have the $products variable...

public function getIndex() // shop.index needs both $products and $days
{
    $products = Product::all();
    return view('shop.index', ['products' => $products]); // no Days sent.
}

Both the variables $days and $products are needed in the shop.index template in shops folder.

secondly, opening a route that would call the index method of the ProductController would open the shop.index template but won't find the $days variable as it is not being sent in the Index function of ProductsController.

CodePudding user response:

So the stack trace provided by you at https://flareapp.io/share/Bm0jQD07#F47 shows that your error is occurring on line 24 of your ProductController and is due to you trying to use a variable $days which you’ve neither declared nor initialised:

return view('shop.index', ['products' => $products], ['days' => $days]);

You need to declare and initialise the $days variable to resolve the error.

For example:

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