I'm trying to query all products from a category and it's subcategories. But I'm getting this error on my Controller.
Class 'App\Http\Controllers\App\Category' not found
I have a products table
id
name
category_id (fk)
And a categories table:
id
name
parent_id
So if the categories looked like this:
id | title | parent
1 | Electronics | null
2 | Smartphones | 1
3 | Android | 2
4 | Clothes | null
And products:
id | title | category_id (fk)
1 | Smartphone1 | 3
1 | Smartphone2 | 2
This is my code on how to do this:
The Category Model - app/category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class category extends Model
{
//
protected $fillable = array('id', 'name', 'parent_id', 'image_url');
public function products()
{
// Build an array containing the parent category ID and all subcategory IDs found
$categoryIds = array_merge([$this->id], $this->subcategoryIds());
// Find all products that match the retrieved category IDs
return Product::whereIn('category_id', $categoryIds)->get();
}
protected function subcategoryIds($id = null, &$ids= [])
{
// If no ID is passed, set the current model ID as the parent
if (is_null($id)) {
$id = $this->id;
}
// Find subcategory IDs
$categoryIds = $this->query()->where('parent', $id)->lists('id');
// Add each ID to the list and recursively find other subcategory IDs
foreach ($categoryIds as $categoryId) {
$ids[] = $categoryId;
$ids += $this->subcategoryIds($categoryId, $ids);
}
return $ids;
}
}
And on my app/Http/Controllers/ProductController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use App\Product;
use App\Category;
use App\Repositories\CategoryRepository;
public function getProductsFromCategory()
{
$id = 1;
$products = App\Category::find($id)->products();
return view('welcome', [
'products' => $products,
]);
}
Replace
$products = App\Category::find($id)->products();
with
$products = Category::find($id)->products();
You've already imported the class and don't have to specify the path again.
you declare class with 'category' and use with it with capital notation App\Category so change your class name to class Category. And if you use on top than you don't have to call with App\Cateogry every time you can directly use with Category::whatever().