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