Laravel Custom Notification - Getting API Response from Custom Notification Channel
In Laravel, you can create custom notification channels to handle notifications in various ways, including sending notifications via email, SMS, or even through external APIs. In this answer, we will discuss how to create a custom notification channel to get an API response from an external service.
First, let's assume that you have an external API that accepts a POST request with some data and returns a JSON response. To create a custom notification channel, follow these steps:
- Create a new class for your custom notification channel. You can place it in the
app/Notifications
directory. For example, let's call itApiResponseNotification.php
:
namespace App\Notifications;
use Illuminate\Notifications\Notification;
use GuzzleHttp\Client;
class ApiResponseNotification extends Notification
{
protected $apiUrl;
/**
* Create a new notification instance.
*
* @param string $apiUrl
*/
public function __construct($apiUrl)
{
$this->apiUrl = $apiUrl;
}
}
In the constructor, we accept the API URL as a parameter and store it in a protected property.
- Add a
toApi
method to theApiResponseNotification
class. This method will handle sending the notification to the external API:
public function toApi($notifiable)
{
$client = new Client();
$response = $client->post($this->apiUrl, [
'json' => [
'data' => [
'type' => get_class($notifiable),
'id' => $notifiable->id,
],
],
]);
if ($response->getStatusCode() != 200) {
throw new \Exception('Failed to send notification to API.');
}
return $response->getBody()->getContents();
}
In the toApi
method, we create a new GuzzleHttp client and send a POST request to the API URL with the data in JSON format. We check the response status code and throw an exception if it's not 200. If the response is successful, we return the response body as a string.
- Register the custom notification channel in the
app/Providers/AppServiceProvider.php
file:
use App\Notifications\ApiResponseNotification;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
// ...
Notification::channel('api', function ($notifiable) {
return new ApiResponseNotification('https://api.example.com/notifications');
});
}
}
In the register
method, we register the ApiResponseNotification
channel with the name api
and the API URL as a closure that returns a new instance of the ApiResponseNotification
class.
- Use the custom notification channel in your notification:
use App\Notifications\ApiResponseNotification;
use App\Models\User;
class YourNotification extends Notification
{
protected $user;
/**
* Create a new notification instance.
*
* @param \App\Models\User $user
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* @return array
*/
public function via($notifiable)
{
return ['api'];
}
/**
* Get the array representation of the notification.
*
* @return array
*/
public function toArray($notifiable)
{
return [
'message' => 'Your message here',
];
}
/**
* Get the API response representation of the notification.
*
* @return string
*/
public function toApi($notifiable)
{
return (new ApiResponseNotification('https://api.example.com/notifications'))->with($this->user)->toApi($notifiable);
}
}
In the YourNotification
class, we override the via
method to return the api
channel. We also create a new toApi
method that calls the toApi
method of the ApiResponseNotification
instance with the $notifiable
object as a parameter.
- Send the notification as usual:
use App\Models\User;
use App\Notifications\YourNotification;
$user = User::find(1);
$user->notify(new YourNotification($user));
When you send the notification, Laravel will automatically use the api
channel to send the notification to the external API and return the API response as a string.