gabogabans
gabogabans

Reputation: 3553

Property [products] does not exist on this collection instance

in my app I first retrieve product categories with products, now I want to extract products from product categories but I get the following error:

Property [products] does not exist on this collection instance.

This is how I get categories first and then products

$productCategories = ProductCategory::with('products')->get(); //This works

$products = $productCategories->products; //Then this gives me error

Here are my models and migrations:

class Product extends FilterableModel
{


    protected $table = 'products';

    public function category()
    {
        return $this->belongsTo('App\Models\ProductCategory', 'productcategory_id');
    }
class ProductCategory extends FilterableModel
{


    protected $table = 'productcategories';


    public function products()
    {
        return $this->HasMany('App\Models\Product', 'productcategory_id');
    }


}
Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('productcategory_id')->index();
            $table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade')->onUpdate('cascade');
            $table->string('title');
            $table->string('slug');
            $table->string('url');
            $table->text('body')->nullable();
            $table->string('image')->nullable();
            $table->boolean('isVisible')->default(false);
            $table->boolean('isFeatured')->default(false);
            $table->integer('stock')->default(0);
            $table->decimal('originalPrice', 5,2)->default(0.00);
            $table->decimal('finalPrice', 5,2)->default(0.00);
            $table->timestamps();
        });
Schema::create('productcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->string('slug')->unique();
            $table->string('url')->unique();
            $table->text('body')->nullable();
            $table->string('image')->default(config('app.defaultImage'));
            $table->string('icon')->default('fa fa-tag');
            $table->boolean('isVisible')->default(false);
            $table->boolean('isFeatured')->default(false);
            $table->timestamps();
        });

Upvotes: 0

Views: 143

Answers (1)

Oleg Nurutdinov
Oleg Nurutdinov

Reputation: 633

So, your $productCategories variable is a Collection of ProductCategory instances. If you want to get a products of all of them, you need to loopin it:

foreach ($productCategories as $productCategory) {
   dump($productCategory->products);
}

If you want to get products of one of productCategory you need to select it from database:

$productCategory = ProductCategory::findOrFail($productCategoryId);
dump($productCategory->products);

Hope it helps.

Upvotes: 2

Related Questions