Send Slack Notifications From Laravel App
Tags: laravel, php, slack, backend
Published: 2023-01-12 14:47:59

---
title: Send Slack Notifications From Laravel App
published: true
date: 2022-06-30 03:01:46 UTC
tags: 
- Laravel
- PHP
- Slack
- Backend
canonical_url: https://fajarwz.com/blog/send-slack-notifications-from-laravel-app/
---
![Slack illustration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ti5pky0hnfjyrwkg4b1u.jpg)

Slack is a messaging app that generally used by companies. Even [Slack](https://slack.com) call their app as a Digital HQ for companies. Slack is like any other messaging app except it is really designed for business use. It can be used both at desktop and mobile device, making communications easy.

It could be really useful if Laravel can integrate with Slack, and yes it can. Let's get started.

## Requirement
We need to install and set the requirements first:

**#1** Install Slack notification package via Composer

```
composer require laravel/slack-notification-channel
```

**#2** We also need to create a [Slack App](https://api.slack.com/apps?new_app=1) for our team. 

**Step 1:** When you click the link above you will be redirected to Slack API page, for example we can choose **From Scratch** here.

![App from scratch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vghakk2wgjweui8qe0mj.png)

**Step 2:** Write the app name that will send the message and pick your workspace. If you haven't the workspace, please create one first. Next, click **Create App**

![Choose workspace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3he6rpb82rqlv1ckpk2e.png)

**Step 3:** Click **Incoming Webhooks**.

![Incoming webhooks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n85xinls71pq1ewc77v0.png)

**Step 4:** Activate the Incoming Webhooks. So the settings below it appear.

![Turn on incoming webhooks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v4pim6lfk3egkz9d3vo0.png)

**Step 5:** Click add new webhooks to Workspace.

![Add new webhooks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/23fmkjfeomlo7tirsusb.png)

**Step 6:** Select your channel.

![Select channel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/guj853xgrsycyu0p836k.png)

**Step 7:** Now you have the webhook url for your channel, copy it and use it in the `route` or `routeNotificationForSlack` in our Laravel app.

![Webhook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8936q4378h1k6jj1fvde.png)

## Generate Notifications
Create a class for our spesific notification with below artisan command, for example we create a `InvoicePaid` notification. This will generate the class in `App\Notifications` folder. If we don't have the folder yet, Laravel will create one for us.

```
php artisan make:notification InvoicePaid
```

## Create Notification format
Use the `toSlack` method and format the notification

### Simple message
We can create a simple notification message like so:

```php
// App\Notifications\InvoicePaid

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    return (new SlackMessage)
        ->content('One of your invoices has been paid!');
}
```

### With Attachments
We can also send attachments to Slack via Laravel. Here is the example:

```php
// App\Notifications\InvoicePaid

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    // ...

    return (new SlackMessage)
        ->error()
        ->content('Whoops! Something went wrong.')
        ->attachment(function ($attachment) use ($url) {
            $attachment->title('Exception: File Not Found', $url)
                        ->content('File [background.jpg] was not found.');
        });
}
```

> **Read also:**
> * [Create Login With Google OAuth Using Laravel Socialite](https://fajarwz.com/blog/create-login-with-google-oauth-using-laravel-socialite/)
> * [Laravel Rest API Authentication Using JWT Tutorial](https://fajarwz.com/blog/laravel-rest-api-authentication-using-jwt-tutorial/)
> * [Laravel 10 Bug Hunt Contest - $1,000 USD Prize](https://fajarwz.com/blog/laravel-10-bug-hunt-contest/)

## Sending Notifications
We can send the notification in two ways: Using **Trait** and **Facade**

### Using Trait
Using `Notifiable` trait. For example we can use this in User Model.

```php
<?php
 
namespace App\Models;
 
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
 
class User extends Authenticatable
{
    use Notifiable;
}
```

Specify the route notification in the model for our notification that we get in the Point 2 - Step 7 in the [Requirement](#requirement) section we previously do.

```php
// App\Models\User

/**
 * Route notifications for the Slack channel.
 *
 * @param  \Illuminate\Notifications\Notification  $notification
 * @return string
 */
public function routeNotificationForSlack($notification)
{
    return 'https://hooks.slack.com/services/...';
}
```

Use the `notify()` method that is provided by this trait to send the notification.

```php
use App\Models\User;
use App\Notifications\InvoicePaid;

$user = new User;
 
$user->notify(new InvoicePaid($invoice));
```

Here is an example display when the integration is successful and the notification sent successfully to Slack. Slack will categorize our notification system as an "App".

![Result example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/to8o61rxeto9cgh4wv7l.png)

### Using The Notification Facade
Another way is using `Notification` facade. We can use this in any class. Specify the route or the webhook.

```php
use Illuminate\Support\Facades\Notification;
 
Notification::route('slack', 'https://hooks.slack.com/services/...') //you can put the route in .env too
    ->notify(new InvoicePaid());
```

## Conclusions
That's it, it's easy to send notification to Slack with Laravel. First install the package required, create a webhook in Slack, and send the notification via one of the two ways: Trait or Facade.

A repo for this example can be found here [fajarwz/blog-laravel-slack](https://github.com/fajarwz/blog-laravel-slack).

There is also a known package for this package alternative: [spatie/laravel-slack-alerts](https://github.com/spatie/laravel-slack-alerts).

Any thought? Please comment below 👇, thank you!

## Further Reading
[Slack Notifications - Laravel Docs](https://laravel.com/docs/9.x/notifications#slack-notifications)

## Subscribe
Subscribe [@fajarwz Medium](https://fajarwz.medium.com/subscribe) for more content.