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

Ligonsker's avatar

Is this a case for a Trait?

Hello, I have a few times in the controller where I need to send either SMS or Email to the user. Sometimes both.

Now it's just inside any Controller method that requires it. Is this a case where I can extract it to a Trait? Or something else?

Thanks

0 likes
2 replies
LaryAI's avatar
Level 58

Yes, this is a good case for a Trait. You can create a trait that contains the methods for sending SMS and email, and then use it in any controller that needs to send those messages.

Here's an example of what the trait might look like:

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Mail;
use Twilio\Rest\Client;

trait SendsMessages
{
    public function sendSms($phoneNumber, $message)
    {
        $twilio = new Client(config('services.twilio.sid'), config('services.twilio.token'));

        $twilio->messages->create(
            $phoneNumber,
            [
                'from' => config('services.twilio.from'),
                'body' => $message,
            ]
        );
    }

    public function sendEmail($to, $subject, $body)
    {
        Mail::to($to)->send(new \App\Mail\Message($subject, $body));
    }
}

Then, in any controller that needs to send messages, you can simply use the trait like this:

<?php

namespace App\Http\Controllers;

use App\Traits\SendsMessages;
use Illuminate\Http\Request;

class MyController extends Controller
{
    use SendsMessages;

    public function myMethod(Request $request)
    {
        // Send an SMS
        $this->sendSms($request->phone_number, 'Hello, world!');

        // Send an email
        $this->sendEmail($request->email, 'Hello', 'This is a test email.');
    }
}

Note that in this example, we're using the Twilio PHP library to send SMS messages, and the Laravel Mail facade to send emails. You'll need to configure these services in your config/services.php file for this code to work.

Please or to participate in this conversation.