Developer654079525's avatar

Controller's helper fn

Where should i keep the helper fn that fetches some data from a particular db table and is then used extensively across only two controller classes? Should i keep it as a private member function in both controllers and then invoke it in other member functions as:

$result = this->myFn();

Or should I move it to a model, mark it as static and then in my controllers invoke it as:

$result = SomeModel::myFn();
1 like
3 replies
imranbru's avatar

Definitely don't duplicate the code in both controllers keep it DRY.

Since it involves fetching data, the logic belongs in the Model. Using a Local Scope is the most idiomatic Laravel way to handle this. However, if it’s a more specialized fetch that doesn’t fit a scope, a static method on the model is a solid choice. Just keep the database logic out of the controllers.

1 like
Snapey's avatar

another option is a trait, used in both places

1 like

Please or to participate in this conversation.