I have a Product model
class Product extends Model
{
...
public function prices()
{
return $this->hasMany('App\Price');
}
...
}
I want to add a function which will return the lowest price, and in controller I can get the value using:
Product::find(1)->lowest;
I added this in Product model:
public function lowest()
{
return $this->prices->min('price');
}
but I got an error saying:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
And if I use Product::find(1)->lowest();
, it will work. Is it possible to get Product::find(1)->lowest;
to work?
Any help would be appreciated.
you can use above methods or use following method to add a function direct into existing model:
Or use Illuminate\Support\Facades\DB; inside your function. Hope this help others.
When you try to access a function in the model as a variable, laravel assumes you're trying to retrieve a related model. They call them dynamic properties. What you need instead is a custom attribute.
add following method to your model:
Now you should be able to access it like this:
why you just dont do this? i know , it's not what you asked for specificallyand it migh be a bad practice sometimes. but in your case i guess it's good.
Use Eloquent accessors
Then