Ad

Parse Error: Syntax Error, Unexpected '__construct' (T_STRING), Expecting Function (T_FUNCTION) Or Const (T_CONST)

- 1 answer

I have this problem. When I click on add to cart button there is an error:

Parse error: syntax error, unexpected '__construct' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

I'm new in Laravel and I really have no idea what I have to do,

This is my code on button add to Cart:

<a target="_blank" rel="nofollow noreferrer" href="{{route('get.addToCart',[$product->id])}}" class="cart-btn">Add to cart</a>

This is my route:

Route::get('add-to-cart/{id}', '[email protected]')->name('get.addToCart');

This I have in webcontroller:

public function addToCart(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);
   dd($request->session()->get('cart'));
   return redirect()->route(get.product);
}

And this is my cart.php

<?php
namespace App;
class Cart{
   public $items=null;
   public __construct($oldCart){
      if($oldCart){
        this->$items=$oldCart->items;
      }
   }
   public function add($item,$id){
      $storedItem= ['name'=>$item];
      if(this-> $items)
      { 
         if(array_key_exists($id, this->$items)){
           $storedItem=this->$items[$id];
         }
      }
      this->$items[$id]=$storedItem;
   }
}
Ad

Answer

Your __construct needs to have the word function in front of it, or better yet public function

Change the line to:

public function __construct($oldCart)

Read out here: Line no 8

Ad
source: stackoverflow.com
Ad