Tech AI Insights

Send Slack Notifications From Laravel App

Slack is a powerful messaging and collaboration platform designed for teams and workplaces. It enables real-time communication through channels, direct messages, and threaded conversations, keeping discussions organized.

Many IT companies use Slack to collaborate with teammates, communicate with clients, and assign tasks efficiently. Unlike WhatsApp, Slack allows users to create threads within chats for better context and organization.

Additionally, Slack integrates seamlessly with tools like Google Drive, Trello, GitHub, and more, helping teams streamline their workflow and boost productivity.

Here are the steps to send the message over slack:

Step 1:  First you need to Install Slack notification package via Composer

composer require laravel/slack-notification-channel

If you getting errors in installing the Slack notification then please follow these steps otherwise skip if your package installed successfully

    • Clear Composer Cache

Run the following command to clear the Composer cache and try again:
composer clear-cache

    • Then, try installing the package again:

composer require laravel/slack-notification-channel

    • If you want to run a specific version or a lower version provide that version name

composer require laravel/slack-notification-channel:^1.0

Step 2:

We need to create a Slack App for our team.(this setup is for that user how don’t have any slack account) after clicking on the above link you will be redirected to Slack API page, for example we can choose From Scratch here.

Step 3:

Write the app name that will send the message and pick your workspace. If you do not have the workspace, please create one first. Next, click Create App

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

Step 5: Click add new webhooks to Workspace.

Step 6: Select your channel.

Step 7: Now you have the webhook url for your channel

Step 8: Create a Notification Class

Run the following command to generate a Slack notification class:

php artisan make:notification SlackNotification

Step 9: Configure the Notification Class

Open app/Notifications/SlackNotification.php and modify it:

  <?php

  namespace App\Notifications;

  use Illuminate\Bus\Queueable;
  use Illuminate\Notifications\Notification;
  use Illuminate\Notifications\Messages\SlackMessage;

  class SlackNotification extends Notification
  {
    use Queueable;
    /**
      * Create a new notification instance.
      *
      * @return void
      */
    public function __construct()
    {
    //
    }

  /**
    * Get the notification's delivery channels.
    *
    * @param mixed $notifiable
    * @return array
    */
    public function via($notifiable)
    {
      return ['slack'];
    }

    /**
    * Get the Slack representation of the notification.
    *
    * @param mixed $notifiable
    * @return \Illuminate\Notifications\Messages\SlackMessage
    */
    public function toSlack($notifiable)
    {
      return (new SlackMessage)
          ->content("🚀 A new update has been posted on your Laravel app!")
          ->attachment(function ($attachment) {
              $attachment->title('View Details', url('/'))
              ->content('Click the link to see the update.');
      });
    }
  }

Step 10: Set Up Notifiable Entity

You can send notifications to a Slack channel directly from anywhere in your app. However, to make it reusable, add a routeNotificationForSlack() method in a Notifiable model (e.g., User or a separate class).

For global Slack notifications:

  <?php

  namespace App\Models;

  use Illuminate\Notifications\Notifiable;

  class SlackChannel
  {
    use Notifiable;

    public function routeNotificationForSlack()
    {
      return env('SLACK_WEBHOOK_URL'); // Store your Slack Webhook in the .env file
    }
  }

  

In your .env file, add:

SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXXXX/YYYYY/ZZZZZ

Step 11: Send Slack Notifications

Now, you can send notifications anywhere in your app, for example, in a controller:

I’m creating this in my UserController when you hit sendNotification() function, the notification will be sent automatically on your slack channel that you select

  <?php 
  namespace App\Http\Controllers;

  use Froiden\RestAPI\ApiController;
  use App\Notifications\SlackNotification;
  use App\Model\SlackChannel;

  class UserController extends ApiController
  {
      public function sendNotification()
      {
          $slack = new SlackChannel();
          $slack->notify(new SlackNotification());

          return response()->json(['message' => 'Send slack notification successfully']);
      }
  }

  

In web.php just hit the route

 Route::get('send-notification', 'UserController@sendNotification');

If you can send a parameter to the Slack notification file and use that parameter in your content

Step1:

 $slack = new SlackChannel();
 $slack->notify(new SlackNotification($company->name));

Step 2 Modify Your SlackNotification Class

and in the SlackNotification file, you can use this parameter like

  <?php

  namespace App\Notifications;

  use Illuminate\Bus\Queueable;
  use Illuminate\Notifications\Notification;
  use Illuminate\Notifications\Messages\SlackMessage;

  class SlackNotification extends Notification
  {
      use Queueable;

      protected $companyName; // Declare a variable

      /**
       * Create a new notification instance.
       *
       * @return void
       */
      public function __construct($companyName)
      {
          $this->companyName = $companyName;
      }

      /**
       * Get the notification's delivery channels.
       *
       * @param  mixed  $notifiable
       * @return array
       */
      public function via($notifiable)
      {
          return ['slack'];
      }

      /**
       * Get the Slack representation of the notification.
       *
       * @param  mixed  $notifiable
       * @return \Illuminate\Notifications\Messages\SlackMessage
       */
      public function toSlack($notifiable)
      {
          return (new SlackMessage)
          ->content("*Hello* \n\n"
                  . "*This is the first title* \n\n"
                  . "This is the title description");
      }
  }
  

Final Notes

– Use *bold* for bold text in Slack messages.
– Use \n for new lines.

Scroll to Top