调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsToMany::routeNotificationFor()

Kyl*_*rst 2 notifications laravel laravel-6

我正在构建一个消息系统,在设置回复时通知对话中的每个用户。

消息通知.php

class MessageNotification extends Notification
{
    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    public function toArray($notifiable)
    {
        return [
            'data' => 'Messenger notification'
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

收件箱控制器

public function reply($hashedId, Request $request)
{
    $this->validate($request, [
        'body' => 'required',
    ]);

    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $users = $conversation->participants();

    //dd($conversationUserIds);

    $notifications = Notification::send($users, new MessageNotification());

    $message = $conversation->messages()->create([
        'sender_id' => auth()->user()->id,
        'body' => $request->body,
    ]);

    return new MessageResource($message);
}
Run Code Online (Sandbox Code Playgroud)

错误

调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsToMany::routeNotificationFor()

额外的信息

由于需要同时使用 Laravel Sparks 通知系统和 Laravel 库存通知系统,我必须构建一个自定义的 Not济 性特征。我从中获取代码的教程。

自定义通知特征

namespace App\Traits;

use Illuminate\Notifications\Notifiable as BaseNotifiable;
use App\Notifications\DatabaseNotification;

trait Notifiable {

    use BaseNotifiable;

    public function notifications() {
        return $this->morphMany(DatabaseNotification::class, 'notifiable')->orderBy('created_at', 'desc');
    }

}
Run Code Online (Sandbox Code Playgroud)

另请注意,$reciever->notify(new MessageNotification());向一位用户发送通知时效果很好。我对此看到的唯一其他解决方案是:https://laracasts.com/discuss/channels/code-review/call-to-undefined-method-routenotificationfor-while-sending-email-to-multiple-users

我尝试实现这一点,但我使用的是数据库通道,所以它应该不会产生影响。

小智 5

这行在这里:

$users = $conversation->participants();

$users变量设置为 QueryBuilder 实例(假设您使用传统的 Laravel 关系),而不是用户集合。这是因为()关系末尾会构建查询,但尚未运行它。因此,当您调用时,Notification::send($users, etc...)您不会传递用户集合;而是传递用户集合。您正在传递一个 QueryBuilder 对象。

试试这个:

$users = $conversation->participants;

再次强调 - 假设对话模型上的参与者方法是标准的 Laravel 关系。