Skip to content
Advertisement

Laravel how to add a custom function in an Eloquent model?

I have a Product model

JavaScript

I want to add a function which will return the lowest price, and in controller I can get the value using:

JavaScript

I added this in Product model:

JavaScript

but I got an error saying:

JavaScript

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.

Advertisement

Answer

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.

Laravel 6 docs: https://laravel.com/docs/6.x/eloquent-mutators

add following method to your model:

JavaScript

Now you should be able to access it like this:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement