I am creating a page where message is sent after form is submitted. To send sms, I'm using Twilio as provider. When I try to add volunteer data, it outputs BadMethodCallException error with following message
Call to undefined method App\\Models\\Volunteers::sendMessage()
If I remove any mentions of sendMessage() function, the function outputs the desired outcome. However the sendMessage() seems to break the code functionality.
VolunteerController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Volunteers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;
use Twilio\Rest\Client;
public function store(Request $request)
{
$data = $request->validate([
'name' => 'required',
'phone' => 'required|string',
'email' => 'required',
]);
$volunteerDetails = [
'name' => $data['name'],
'phone' => $data['phone'],
'email' => $data['email'],
];
$volunteer = Volunteers::create($volunteerDetails);
$message = 'You have been registered as volunteer';
$recipient = $data['phone'];
$volunteer->sendMessage($message,$recipient);
}
public function sendMessage($message, $recipients)
{
$account_sid = getenv("TWILIO_SID");
$auth_token = getenv("TWILIO_AUTH_TOKEN");
$twilio_number = getenv("TWILIO_NUMBER");
$client = new Client($account_sid, $auth_token);
$client->messages->create($recipients, ['from' => $twilio_number, 'body' => $message] );
}
Model Volunteer.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Volunteers extends Model
{
use HasFactory, Notifiable;
protected $fillable = [
'type',
'district',
'local',
'ward_no',
'phone',
'email',
'interested_area',
'manpower'
];
}
And my route is via api
Route::post('/volunteer/add', [VolunteerController::class, 'store']);
CodePudding user response:
@brombeer solved the problem. I used $volunteer->sendMessage
instead of $this->sendMessage
CodePudding user response:
Well to explain the issue here.
The line refers to the Model Volunteers' instance
$volunteer = Volunteers::create($volunteerDetails);
The sendMessage($message,$recipient) method is a method of the controller class
using the $voluteer to call the sendMessage method gave the error
$volunteer->sendMessage($message,$recipient);
As suggested by @brombeer you should use "$this" rather