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.