-2

hello m trying to get categories/products seprately, like when i click on specific category then its related products shown:

but it says: Call to undefined relationship [categories] on model [App\Category].

actually my categories starts from "8" when i type 8 to replace 0 then it shows : Undefined variable: categoriesDetails

  categories = Category::with('categories')->where(['parent_id'=>0])->get();

code of ProductsController:

  public function products($url = null){

  $categories = Category::with('categories')->where(['parent_id'=>0])->get();

  $categoryDetails = Category::where(['url' => $url])->first();
  $productsAll = Product::where(['category_id' => $categoriesDetails->id])->get();
  return view('products.listing')->with(compact('categories','categoryDetails','productsAll'));
}

code of Product model:

  <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
 public function category(){
 return $this->belongsTo('App\Category');

 }
}
pro
  • 609
  • 4
  • 17
  • 40
  • You're defining the relationship as `category()`, so you can't call `categories`... – Tim Lewis Jan 14 '19 at 16:21
  • i changed it to $categoriesDet = Category::with('categories')->where(['parent_id'=>0])->get();return view('products.listing')->with(compact('categoriesDet','categoryDetails','productsAll')); but still same error – pro Jan 14 '19 at 16:27
  • `public function category()` should be `public function categories()` to work via `->with("categories")`. You function name needs to be the same as what you're using in `->with()`. Currently, it is not. – Tim Lewis Jan 14 '19 at 16:30

1 Answers1

0

Your with must match the function's name. with('category') will work, but you should probably rename it to categories if a product can have multiple categories.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • changed it to category but same result – pro Jan 14 '19 at 16:27
  • @azibdhaken You have other issues in this code, yes. `Category::with('categories')` doesn't make sense - categories don't have categories, your products do. You'd do something like `Product::with('categories')`, or `Category::with('products')`. I strongly recommend you go re-read the docs on Eloquent relationships and how they work. – ceejayoz Jan 14 '19 at 16:29
  • nice now its showing "Undefined variable: categoriesDetails" at this line:$productsAll = Product::where(['category_id' => $categoriesDetails->id])->get(); – pro Jan 14 '19 at 16:34
  • would u prefer to tell me this last sol. – pro Jan 14 '19 at 16:39