octoxan's avatar

How to make this more DRY? Looking for best practice advice.

Let me start off by apologizing that there's not really going to be any code posted by me in this question, I'm just going to have to explain it all verbally. This is both because the sensitive nature of the code, and how long it would take me to "example-ify" it all.

Okay, so I have 3 different controllers currently.

On the index controller, I accept about 60+ requests over ajax and filter the model by all these requests, and return a paginated 250 of them (loading the next 250 by ajax upon reaching the bottom of the list). There's a whole lot of weird complex logic going on with all these requests before I actually call the model with like 30 scopes.

Then there's a "counter" controller, which literally does all the same many filters and instead of ->paginate(250) I'm calling ->count().

Then there's a "load all" controller, which does all the same stuff but just called ->get() instead of a paginated version.

I realize I have way to much repeated code if I'm doing all of these filters for each controller/ Would it be best practice to have one function on my model that does all of this and depending on the variables returns all, pagination, or the count, or should I avoid a function that accepts like 60 arguments to decide what to return?

Perhaps the best method would be to have one controller, one route, and if a request->count or request->all is sent, swap out paginate, count, or get?

I'd still have a huge block of code repeated with my 30 scopes but with a different final -> call.

Is there a way in Laravel to perhaps store that in a variable, so when I add a new filter I don't have to do it in multiple places?

I hope that all made sense.

0 likes
1 reply

Please or to participate in this conversation.