Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

davidleads's avatar

Repetitive eloquent query across 1 controller.

Let's assume that I have a controller which is dedicated to control the views, so i have different types of views and i send to them different variables, but - i have one query which repeats itself across all the functions, in this case its

$companies = Company::where('enabled',1)->get()->sortByDesc('score');

What would be the right approach to keep it DRY? Is it safe to put this variable in the external scope of the controller and not in every function?

0 likes
4 replies
sr57's avatar

Put it int the construct function of your controller

	public function __construct() {
		$this->companies=...
}
davidleads's avatar

So what's the best approach? The view composer or simply putting this query inside my controller's construct?

MichalOravec's avatar

If you need it only in views than it's a view composer.

1 like

Please or to participate in this conversation.