Laravel 9:向指定角色用户发送数据库通知遇数组错误
解决“Call to a member function notify() on array”错误
问题原因
你当前的$recipients是通过pluck('email')->toArray()生成的邮箱字符串数组,而notify()是Laravel Eloquent模型(这里是User模型)的专属方法,数组无法调用该方法,因此触发错误。
修复方案
步骤1:获取用户模型集合
先修正$recipients的查询逻辑,直接获取符合条件的User模型集合,不要提取邮箱转数组:
$recipients = User::whereHas("roles", function($q) { $q->whereIn("id", [ 1, // Super Admin 6, // Admin 2, // Security Supervisor 5, // Security Manager ]); })->get();
步骤2:批量发送通知
有两种方式实现批量通知:
方式一:遍历用户逐个发送
foreach ($recipients as $user) { $user->notify( Notification::make() ->title('New Incident Created') ->icon('heroicon-o-document-text') ->toDatabase() ); }
方式二:用Laravel Notification门面批量发送
use Illuminate\Support\Facades\Notification; Notification::send($recipients, Notification::make() ->title('New Incident Created') ->icon('heroicon-o-document-text') ->toDatabase() );
两种方式都能正常触发Filament的数据库通知,根据你的习惯选择即可。
内容的提问来源于stack exchange,提问作者Abdulrahman Mushref
相关产品推荐
相关产品推荐

