RafaelMunoznl
7 months ago
913
9
Laravel

Best practice to avoid three almos identical Controllers?

Posted 7 months ago by RafaelMunoznl

I have three very similar controllers: EmployeesController and Companiescontroller and RegionsController

They have almost not logic at all. All what they do is to calls a lot of methods in different services and models, get the results and pass then each to a different views. All those But these calls are all identical, like this:

    public function show(Company $company, User $user,  $date = null)
    {
        if (Auth::user()->email !== $user->email) {
            return view('errors.not_allowed');
        }
        $page_name = 'users';
        $index = 'show';
        $element = $user;

// From this point onwards the calls are identicals 
        $today = substr(today(), 0, 10);
        $employees = User::getEmployees($company->id);
        $date ? $currentDay = $date : $currentDay = today();
        $openingHours = Openinghour::getOpenings($company->id);
        $element->completeName = $user->getCompleteNameAttribute();
        $daysView = Appointment::daysView($company->id, $currentDay, $user->id);
        $futureAppointment = Appointment::futureAppointment($company->id, $currentDay, $user->id);
        $calendar = Appointment::organizeAppointment($daysView['currentDay']['appointments'], $employees, $openingHours);
/// end of identical calls here

return view( ‘the-particular-view-here’, compact(‘variables here’)  );

The point is that I am repeating in three times the same calls. Since I am still coding, each time I change something, I have to do it three times (or it breaks somewhere else).Is there any best-practice approach to such a situation? Perhaps a super-controller passing to a view with a condition (IF loop)?

Please sign in or create an account to participate in this conversation.