Parse error: syntax error, unexpected '__construct' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)
44,746
Solution 1
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
Solution 2
there is missing function keyword before __construct
<?php
namespace App;
class Cart{
public $items=null;
public function __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;
}
}
Author by
Angelika Beňová
Updated on July 09, 2022Comments
-
Angelika Beňová almost 2 years
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 href="{{route('get.addToCart',[$product->id])}}" class="cart-btn">Add to cart</a>
This is my route:
Route::get('add-to-cart/{id}', 'WebController@addToCart')->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; } }
-
Angelika Beňová over 5 yearsThanks can you help me with another problem?
-
Udhav Sarvaiya over 5 years@AngelikaBeňová yes, I will try my best
-
Angelika Beňová over 5 yearsThanks I have another problem you can see it in comments
-
Angelika Beňová over 5 yearsYou can see this problem in comment
-
Angelika Beňová over 5 yearsThanks I have another problem can you help me? You can see it in comment
-
Angelika Beňová over 5 yearsThere is still the problem Undefined index: item (View: C:\xampp\htdocs\laravel\resources\views\shoppingCart.blade.php)
-
Udhav Sarvaiya over 5 yearsundefined index occurs due to undefined variables.