1

I have next Notification class:

class WelcomeNotification extends Notification
{
    use Queueable;

    public function __construct()
    {
        //
    }

    public function via($notifiable)
    {
        return ['database'];
    }

    public function toDatabase($notifiable)
    {
        return [
            //
        ];
    }
}

And I want add some function to this. For example:

public function myFunction()
{
    return 'something';
}

But $user->notifications->first()->myFunction return nothing

Igor Ostapiuk
  • 589
  • 3
  • 7
  • 23

1 Answers1

2

When you call the notifications() relation it turns out is a polymorphic relation using the DatabaseNotification model. The proper way is to inherit DatabaseNotification and write the custom function their.

For example, create app/DatabaseNotification/WelcomeNotification.php and inherit DatabaseNotification model.

namespace App\DatabaseNotification;

use Illuminate\Notifications\DatabaseNotification;

class WelcomeNotification extends DatabaseNotification
{

    public function foo() {
        return 'bar';
    }

}

And override the notifications() function that uses the Notifiable trait:

use App\DatabaseNotification\WelcomeNotification;

class User extends Authenticatable
{
    use Notifiable;

    ...

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

    ...

}

And now you can call the custom function as follows:

$user->notifications->first()->foo();
Ben
  • 5,069
  • 4
  • 18
  • 26