Using Laravel Notifications in Lumen

One of the undocumented features of Lumen is the ability to use the Laravel Notification functionality with a bit of bootstrapping. (In fact quite alot of Laravel core framework can be bootstrapped into Lumen).

Notifications are super useful because API’s have plenty of occasions where they may want to generate notifications, and the Laravel Notification service is a neat way of combining mail, sms, web sockets and other types of notifications.

The first step is requiring the illuminate/notifications package:

I also require illuminate/support, i’m not 100% if this is a required dependency for notifications. If you get errors this might be why.

Next, register the service provider in bootstrap/app.php

Add the Notifiable trait to whichever models you like, User would be an obvious one:

Write notifications the normal way:

Send notifications from your app the normal way:

From here on in, you can pretty well follow the notification docs. Read on to see how to Unit Test mocked notifications in Lumen.

When it comes to Unit Testing, it will come as no surprise that Lumen has no support for Notification mocking; nothing that can’t be solved by a bit of copy and paste from laravel/framework! (Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php to be precise – I also wrote my own doesntExpectNotification() as it doesn’t exist in Laravel)

Make your tests/TestCase.php resemble this:

Now you can expect or not expect notifications in your tests.

One gotcha is that for some reason, Notifications are not actually sent within test suites by default, but with mocking you can still assert whether they were sent or not.

 

Leave a Reply

Your email address will not be published. Required fields are marked *