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

前端 未结 5 1684
慢半拍i
慢半拍i 2020-12-25 15:19

I have a Product model

class Product extends Model
{
    ...

    public function prices()
    {
        return $this->hasMany(\'App\\Price\');
    }

            


        
5条回答
  •  忘掉有多难
    2020-12-25 15:50

    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:

    public function getLowestAttribute()
    {
        //do whatever you want to do
        return 'lowest price';
    }
    

    Now you should be able to access it like this:

    Product::find(1)->lowest;
    

提交回复
热议问题