Laravel报错:Call to a member function routeNotificationFor() on string及代码求助
解决Laravel报错:在字符串上调用成员函数routeNotificationFor()
这个报错的核心原因是Laravel的Notification::send()方法要求第一个参数必须是实现了Notifiable trait的模型实例,而你现在直接传递了一个字符串类型的邮箱地址。系统尝试在这个字符串上调用routeNotificationFor()方法(这是Notifiable trait提供的内置方法),但字符串不是对象,自然会触发这个错误。
另外,你的代码里还有一个隐藏逻辑问题:return $staffs;这一行会直接终止方法执行,导致后面的session()->forget('checkState')和页面跳转逻辑完全不会运行,这个必须先修正。
下面给出两种可行的解决方案,推荐第一种更符合Laravel设计规范的实现方式:
方案1:使用Staff模型实例作为通知接收者(推荐)
这种方式更贴合Laravel通知系统的设计理念,也更便于后续维护和扩展。
步骤1:确保Staff模型引入Notifiable trait
打开你的Staff模型文件,添加Notifiable trait:
namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; class Staff extends Model { use Notifiable; // ... 模型其他已有代码 // 定义短信通道的路由规则(适配mightytext的邮箱格式) public function routeNotificationForMail() { // 自动将手机号转换为mightytext要求的邮箱格式 return str_replace(" ","","44".substr($this->mobile, 1)).'@mail.mightytext.net'; } }
步骤2:修正sendBookingSms方法
直接传递Staff模型实例给Notification::send(),同时移除错误的return $staffs;语句:
public function sendBookingSms(){ $checkState = session()->get('checkState'); $staffs = Staff::whereIn('staffId',$checkState)->get(); foreach ($staffs as $staff) { // 传递Staff模型实例,而非字符串邮箱 Notification::send($staff, new NewBooking()); } session()->forget('checkState'); return redirect(route('booking.current'))->with('message','Successfully sent SMS to selected staffs !!'); }
步骤3:调整NewBooking通知类
确保通知类的via方法指定使用mail通道(因为我们是通过邮箱转短信的方式实现):
namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Notifications\Messages\MailMessage; class NewBooking extends Notification { use Queueable; // 如果需要传递预订相关数据,可以在这里添加构造函数接收参数 // public function __construct($booking) // { // $this->booking = $booking; // } public function via($notifiable) { // 指定使用mail通道发送到mightytext的邮箱地址 return ['mail']; } public function toMail($notifiable) { // 定义短信(邮件)的具体内容 return (new MailMessage) ->line('You have a new booking assigned!') ->action('View Booking', url('/booking/current')) ->line('Thank you for your service!'); } }
方案2:直接发送到邮箱字符串(快速临时方案)
如果你不想修改模型代码,可以使用Notification::route()方法直接指定通道和目标路由地址:
public function sendBookingSms(){ $checkState = session()->get('checkState'); $staffs = Staff::whereIn('staffId',$checkState)->get(); foreach ($staffs as $staff) { $email = str_replace(" ","","44".substr($staff->mobile, 1)).'@mail.mightytext.net'; // 使用route方法直接指定mail通道和目标邮箱 Notification::route('mail', $email)->notify(new NewBooking()); } session()->forget('checkState'); return redirect(route('booking.current'))->with('message','Successfully sent SMS to selected staffs !!'); }
内容的提问来源于stack exchange,提问作者Jishad
相关产品推荐
相关产品推荐

