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

MahmoudAdelAli's avatar

Decrease the dublicated quires

Hi , sometimes when i have course and categories when i loop in it be like

@foreach($categories as $category)
	// Here i want to add tabs 
		<a class=tab>  $category </a>
			// loop at courses inside this category
@endforeach

so here when i loop inside loop it looks like infinity cause i want to get the courses inside the category that i looped before , so i found my quires increased to 189 , at this moment i decided to use with

#new code
   public function index()
    {
        $countries = Country::all();
        $categories = CourseCategory::with(['courses','parent','courses.teacher','courses.category'])->whereStatus('1')->get();
        $parents = $categories->where('parent_id', null);
        $children= $categories->whereNotNull('parent_id');
        $data = [
            'cms' =>  $this->cmsService->getPhrases(app()->getLocale()),
            'courses' => Course::with(['category','teacher'])->whereStatus('1')->get(),
            'categories' => $categories,
            'children' => $children,
            'parents' => $parents,
            'countries' => $countries
        ];
        return view('clientside.Home.home', $data);
    }
#old Code
    public function index()
    {
        $countries = Country::all();

        $data = [
            'cms' =>  $this->cmsService->getPhrases(app()->getLocale()),
            'courses' => Course::whereStatus('1')->get(),
            'categories' => CourseCategory::all(),
            'products' => Product::whereStatus('1')->limit(3)->get(),
            'teachers' => Teacher::whereStatus('1')->limit(3)->get(),
            'countries' => $countries
        ];

        return view('clientside.Home.home', $data);
    }

but i feel there's better way here , cause at this controller i have 4 methods contain the same query , and better way to decrease the quires , any suggestions ?

0 likes
4 replies
sevenTopo's avatar

with statement is considered a best practice. But i think you still need to do somework here , make sure to formate your relationships before rendering example i only need the fields (Category:id, Category:name ), so no need to return also description created at ...etc to the view ( see Resource https://laravel.com/docs/10.x/eloquent-resources ) .

Regarding redundant code, consider optimizing it by employing a shared variable, such as $users, across multiple functions. Here's an example:

<?php

class MyController {
    protected $users;

    public function __construct(protected UserService $userService) {
        $this->users = $this->userService->all();
    }

    public function method1() {
        // Logic
        return $this->users;
    }

    public function method2() {
        // Logic
        return $this->users;
    }
}

Moreover, I personally avoid making any database queries in my controllers. I believe a controller should solely handle requests and provide responses. To achieve this separation of concerns, you can move all code related to data retrieval to a repository, adhering to the repository pattern. This practice enhances code organization and promotes a more maintainable and scalable architecture. u cane take a look on this for an example of use : https://github.com/hamza-topo/task-manager-api/blob/main/app/Http/Controllers/Api/ProjectController.php

1 like
MahmoudAdelAli's avatar

@sevenTopo Thank you your comment is very helpful , i agree with you too i avoid to do any query at the controller but when I did that, I found that I had to go to Service Pattern

1 like
sevenTopo's avatar

@MahmoudAdelAli That's the point using services or repositories pattern will help you so much for maintaining your code , debugging , and make it easy to read, no more spaghetti code haha

Snapey's avatar

just placing queries in a different class might reduce code duplication but makes no difference to duplicated queries.

Reduce n+1 situations and consider caching.

If you have repeated code, move it to a function that can be called from the places that need it.

1 like

Please or to participate in this conversation.