Gazmir Sulcaj
Gazmir Sulcaj

Reputation: 101

Laravel error: Trying to get property 'id' of non-object

I have to delete product from shopping cart, but i'm stack on this below error:

Trying to get property 'id' of non-object (View: /home/acer/test/project_basket/basket/resources/views/cart.blade.php).

I tried also in different way, ... to remove sessions but i don't know seems to be a little difficult because i need to delete only one product. For every identical added product in shopping cart i create badge that increment by one every time.

cart.blade.php

@foreach($products as $product)
<tr>
   <td><img src="https://via.placeholder.com/400x200/" class="img-cart"></td>
      <td><strong>{{ $product['item']['title'] }}</strong></td>
          <td>
            <form class="form-inline">
                 <input class="form-control" type="text" value="{{ $product['qty'] }}" style="margin-right: 20px" >
                  <!--<button rel="tooltip" class="btn btn-default"><i class="fa fa-pencil"></i></button>-->
                       <form method="POST" action="{{ route('remove.item', $product->id) }}" > 
                             @csrf
                             {{ method_field('DELETE') }}
                             <input type="submit" value="Delete" onclick="return confirm('Are you sure?')" class="btn btn-primary" />
                                    
                       </form>
                     </form>
                   </td>
                  <td>${{ $product['price'] }}</td>
              </tr>
@endforeach

ProductController.php

<?php

namespace App\Http\Controllers;

use App\Cart;
use App\Product;

use Illuminate\Http\Request;
use Session;

class ProductController extends Controller

{
    /**
    *@return \Illuminate\Http\Response
    */
    public function index()
    {
        $products = Product::all();
        return view('home', ['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('home');
    }

    public function getCart()
    {
        if (!Session::has('cart')) {
            return view('cart');
        }
        $oldCart = Session::get('cart');
        $cart = new Cart($oldCart);
        return view('cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();


        return redirect()->route('cart');
    }
}

Routes:

Route::get('/add-cart/{id}', [
          'uses' => 'ProductController@getAddToCart',
          'as' => 'addToCart'
      ]);

Route::get('/cart', [
          'uses' => 'ProductController@getCart',
          'as' => 'shoppingCart'
      ]);



Route::get('/destroy/{id}', [
     'uses' => 'ProductController@destroy',
     'as' => 'remove.item']);

Cart.php

<?php

namespace App;

class Cart 
{
   public $items = null;
   public $totalQty = 0;
   public $totalPrice = 0;

   public function __construct($oldCart)
   {
     if ($oldCart) {
        $this->items = $oldCart->items;
        $this->totalQty = $oldCart->totalQty;
        $this->totalPrice = $oldCart->totalPrice;
     }
   }

   public function add($item, $id)
   {
     $storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];

     if ($this->items ) {

            if (array_key_exists($id, $this->items)) {
                 $storedItem = $this->items[$id];
             }
         }
         $storedItem['qty']++;
         $storedItem['price'] = $item->price * $storedItem['qty'];
         $this->items[$id] = $storedItem;
         $this->totalQty++;
         $this->totalPrice += $item->price;
    }
}

Upvotes: 0

Views: 3629

Answers (3)

A.A Noman
A.A Noman

Reputation: 5270

You have to use like that

<form method="POST" action="{{route('remove.item',['product'=>$product['id']])}}" > 

or

<form method="POST" action="{{route('remove.item',['product'=>$product->id])}}" > 

Upvotes: 1

Rouhollah Mazarei
Rouhollah Mazarei

Reputation: 4153

Try replacing $product->id with $product['id']. So this line:

<form method="POST" action="{{ route('remove.item', $product->id) }}" > 

changes to this:

<form method="POST" action="{{ route('remove.item', $product['id']) }}" > 

Upvotes: 0

Senthurkumaran
Senthurkumaran

Reputation: 1858

Modify your code like below

cart.blade.php

<form method="POST" action="{{ route('remove.item', $product) }}" > 
    @csrf
    {{ method_field('DELETE') }}
    <input type="submit" value="Delete" onclick="return confirm('Are you sure?')" class="btn btn-primary" />
</form>

Routes

Route::get('/destroy/{product}', [
     'uses' => 'ProductController@destroy',
     'as' => 'remove.item']);

Then It should solve your problem

Upvotes: 0

Related Questions