Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::routeNotificationFor()

Viewed 2309

I'm building a messaging system that notifies each user in the conversation when a reply is set.

MessageNotification.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'
        ];
    }
}

InboxController

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);
}

Error

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::routeNotificationFor()

Extra Information

I've had to build a custom Notifiable trait due to needing to use both Laravel Sparks notification system and Laravels stock notification system. Tutorial I got code from.

Custom notification trait

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');
    }

}

Also note that $reciever->notify(new MessageNotification()); works just fine when sending a notification to one user. The only other solution I saw on this was: https://laracasts.com/discuss/channels/code-review/call-to-undefined-method-routenotificationfor-while-sending-email-to-multiple-users

I tried to implement that, but I'm using a database channel so it shouldn't make a difference.

1 Answers

This line here:

$users = $conversation->participants();

Will set the $users variable to a QueryBuilder instance (assuming you are using conventional Laravel relationships), rather than a collection of users. This is because the () at the end of a relationship builds the query but doesn't run it yet. So then when you call Notification::send($users, etc...) you are not passing in a collection of users; you are passing in a QueryBuilder object.

Try this instead:

$users = $conversation->participants;

Again - this is assuming that the participants method on the Conversation model is a standard laravel relationship.

Related