Charrua
1 week ago
363
11
Laravel

Making my controllers easy to understand, where to put code?

Posted 1 week ago by Charrua

Hello, I'm trying to make my controllers have less code and be really easy to read. Let's go to a real example, I have an a school system that has members and those members have exams.

Sometimes the members pre-paid exams, so when the exam date is coming I need to send an email for those members who have not paid exam with payment options and another email with the invitation for those who have already payed.

My controller on my ExamController looks like this:

public function sendNotifications(Request $request)
    {

        $exam = Exam::with('members')->findOrFail($request->id);
        $members = $exam->members;

        $members_to_charge = $members->filter(function ($member) {
            return $member->needsToPayExam();
        });
        Notification::send($members_to_charge, new SendPaymentInvitation($exam));

        $members_to_invite = $members->diff($members_to_charge);
        Notification::send($members_to_invite, new SendInvitation($exam));

        $exam->invitations_sent = 1;
        $exam->save();
        
        return response('Sent', 200);
    }

I would love to reduce this to something like:

public function sendNotifications(Request $request)
    {

        $exam = Exam::with('members')->findOrFail($request->id);
        $exam->sendInvitations($exam->members);

        $exam->invitations_sent = 1;
        $exam->save();
        
        return response('Sent', 200);
    }

My question is where do I need to place the code and method sendInvitations() the Exam model will be a correct place to do it? Let's imagine I have 15 more methods like this one, is the Exam model still the good place to do it?

Thank you

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