Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a custom function in a model?

There is a model data:

class Order extends Model
{
}

How to write a custom method inside the Order class so that it can be called in constructor like this:

Order::myMethod()
Order->myMethod()

Where myMethod is:

public function myMethod() {
     return DB::query(<SQL QUERY>);
}

Purpose is to move SQL queries inside model's class, that don't mess this code in controllers.

like image 828
OPV Avatar asked May 01 '26 16:05

OPV


1 Answers

Rather create a custom function in Model, You can use traits to achieve the desired output.

Please follow either steps:-

  • https://medium.com/@kshitij206/traits-in-laravel-5db8beffbcc3
  • https://www.conetix.com.au/blog/simple-guide-using-traits-laravel-5
like image 175
Mayank Majithya Avatar answered May 03 '26 08:05

Mayank Majithya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!