Jordan Vit Jordan Vit - 6 months ago 60
PHP Question

Showing categories and lowest price with Laravel

Trying to show all categories from database and based of products in category to show lowest price. So what I have so far is:
Model

Categories.php


class Categories extends Eloquent {
protected $table = 'category';
protected $primaryKey = 'category_id';

public $timestamps = false;

public function products()
{
return $this->hasMany('Product', 'category_id');
//return $this->belongsToMany('Product', 'category_id');
}
}


This is
Product.php
Model

class Product extends Eloquent {
protected $table = 'products';
protected $primaryKey = 'product_id';

public function categories()
{
return $this->hasMany('Categories', 'category_id');
//return $this->belongsToMany('Categories', 'category_id');
}

public $timestamps = false;
}


And this is HomeController.php which load index.blade.php view

class HomeController extends BaseController {

public function index()
{
$products = Product::where('category_id', '!=', 1)
->with('category')
->min('price')
->get();

return View::make('site.index', [
'categories' => $categories
]);
}
}


Right now when I load the page I get this error

production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function get() on a non-object' in ....


What is wrong here and how I can display categories and lowest price of each category?

Update: This is how is look now

Categories.php model

class Categories extends Eloquent {
protected $table = 'category';
protected $primaryKey = 'category_id';

public $timestamps = false;

public function products()
{
return $this->hasMany('Product', 'category_id');
}

public function lowestProduct() {
return $this->products()->selectRaw('*, max(price) as aggregate')
->groupBy('products.product_id')->orderBy('aggregate');
}
}


HomeController.php

public function index()
{

$categories = Categories::with('lowestProduct')->get();
//$categories = Categories::paginate(15);
return View::make('site.index', [
'categories' => $categories
]);
}

Answer

In your view you probably have a foreach statement. Put this there:

$category->products()->min('price');

It is the lowest product's price in this category.