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

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


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;


Use Eloquent accessors

public function getLowestAttribute(){    return $this->prices->min('price');}

Then

$product->lowest;


you can use above methods or use following method to add a function direct into existing model:

class Company extends Model{    protected $table = 'companies';    // get detail by id    static function detail($id)    {        return self::find($id)->toArray();    }    // get list by condition    static function list($name = '')    {        if ( !empty($name) ) return self::where('name', 'LIKE', $name)->get()->toArray();        else return self::all()->toArray();    }}

Or use Illuminate\Support\Facades\DB; inside your function. Hope this help others.