'getting notifiable and implementing custom morph relation in Laravel notification

I want to get the notifiable model relation while getting notifications for a specific user. And plus I want to save and get custom morph relation (i.e. causer (causer_id and causer_type)) in notification table (just like notifiable). I was able to create a morph relation and saving it into table record but I am having trouble while getting the relation model, it returns null in both relations. Sharing the code.

  • custom DatabaseChannel -- the modified buildPayload method.
protected function buildPayload($notifiable, Notification $notification)
    {
        $data = $this->getData($notifiable, $notification);
        $causer = $data['causer'];

        unset($data['causer']);

        return [
            // README: removed uuid from here
            'type' => method_exists($notification, 'databaseType')
                ? $notification->databaseType($notifiable)
                : get_class($notification),
            'data' => $data,
            'read_at' => null,
            'causer_type' => get_class($causer),
            'causer_id' => $causer->id,
        ];
    }
  • custom notifiable trait
use Illuminate\Notifications\Notifiable as BaseNotifiable;

trait Notifiable
{
    use BaseNotifiable;

    /**
     * Get the entity's notifications.
     */
    public function notifications(): MorphMany
    {
        return $this->morphMany(Notification::class, 'notifiable')
            ->orderBy('created_at', 'desc');
    }
}

and one thing more I'd like to ask here, how can I refer to two morph relations to single table, like I want to add notifications method with causer and as well as notifiable.

  • custom Notifications Model
class Notification extends DatabaseNotification
{
    public function causer()
    {
        return $this->morphTo();
    }
}

what I am missing or doing wrong? Is it even possible what I am trying to do?



Solution 1:[1]

In order to get morph relation (one or maybe two), you need to select columns {morph}_id and {morph}_type, this is just in case if you are using ->select() while getting records, if you are not using select, that'd not be doing any issue.

EDIT

Here is how you add custom columns to notifications table

    public function up()
    {
        Schema::table('notifications', function (Blueprint $table) {
            $table->string("causer_type")->after('notifiable_id');
            $table->unsignedInteger("causer_id")->after('causer_type');
            $table->index(["causer_type", "causer_id"]);
        });
    }

    public function down()
    {
        Schema::table('notifications', function (Blueprint $table) {
            $table->dropMorphs('causer');
        });
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1