Laravel 11 Slack API to Send Notifications in Slack Channel

Slack API intigration using laravel

Last Updated On - August 2nd, 2024 Published On - Apr 16, 2023

Slack is a famous team communication tool that allows users to send messages, share files, and collaborate on projects. Laravel is a robust PHP web framework that makes it easy to build web applications. This tutorial will explore how to send messages and notifications on Slack using the Slack API in Laravel 11 – The most popular Php framework.

Create a Slack App

The first step is to create a Slack app. You can create a new app on the Slack API website.

Slack API website

Create slack APP

Slack app creation from scratch


Also Read: Graph API In Laravel: Read, filter, save emails in PDF


Define Scope/permissions

Once you have created a new app, go to the “OAuth & Permissions” section and add the chat:write scope to your bot token.

Activate Slack app incoming webhooks

Add chat:write permission to the app

Add webhook to workspace

Install the app to the workspace

Webhook URL for the Slack channel


Also Read: Setting Up and Configuring Supervisor for Process Management on AWS EC2 Ubuntu


Install the Slack Package

To use the Slack API in Laravel, we need to install the laravel/slack-notification-channel package using Composer. Open your terminal and run the following command:

composer require laravel/slack-notification-channel


Set webhook URL in .env (Environment)

This URL can be found in the “Incoming Webhooks” section of your Slack app settings. Set this URL in environment file of the application for configuration setting.

SLACK_WEBHOOK_URL="https://hooks.slack.com/services/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Hqa"

Also Read: What is N+1 Query Problem? How do you solve it in Laravel?


Create a Notification Class

We will use Laravel’s notification system to send messages to Slack. To create a new notification class, run the following Artisan command:

php artisan make:notification SlackNotification

This will create a new SlackNotification.php file in the app/Notifications directory.

Define the via method

Open the file and define the via method to return an array with the “slack” channel. This tells Laravel to send the message using the Slack channel.

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

Add a toSlack method

Next, add a “toSlack” method that returns a new SlackMessage instance with the message to be sent to Slack.

public function toSlack($notifiable)
    {
        return (new SlackMessage)
            ->content('Hi! everyone this is welcome message');
    }

Make sure to include SlackMessage class in the file

use Illuminate\Notifications\Messages\SlackMessage;

You can customize the message by passing different parameters to the SlackMessage constructor or by adding additional methods to the SlackMessage instance.


Also Read: Create Short URL Hashing & Tracking Project in 10 Minutes


Send a Message to Slack

To send messages on the Slack channel, We create a controller and define a method that we call using a route. In the method body, we call notification that we have created in the above step.

php artisan make:contoller Api/ApiController

This will create an ApiController.php file in side app/http/controller/Api folder. In this file we define our method to call the notification.

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Notifications\SlackNotification;
use Illuminate\Support\Facades\Notification;

class ApiController extends Controller
{
    function slackNotificationMessage(){
        Notification::route('slack',env('SLACK_WEBHOOK_URL'))->notify(new SlackNotification());
        return response()->json(['message'=>'Notification sent'], 200);
    }
}

Define a route to execute this method. Open routes/api.php and write the following code.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

 Route::get('/slack-message', 'Api\ApiController@slackNotificationMessage');

Also Read: How To Validate Location From IP & Zipcode Using Laravel 10?


Output

Calling the API to send the message on Slack channel

Message received on Slack



FAQs

Why do users want to send notifications on a Slack channel?

Users want to streamline communication and collaboration on projects.
Efficient collaboration is crucial in project management. The use of Slack, a centralized platform for real-time communication and file sharing, offers a unified space where teams can interact seamlessly. This consolidation eliminates the need for scattered communication channels, providing a focused environment for project-related discussions and updates.

Why do users need to streamline communication and collaboration?

Efficient communication enhances productivity and ensures timely project updates.
Timely updates and clear communication are vital for project success. In a collaborative environment, quick information exchange enables team members to stay informed about project developments. This, in turn, facilitates prompt decision-making, allowing teams to adapt to changes effectively and maintain productivity levels.

Why is efficient communication essential for productivity and project updates?

Timely information exchange helps in quick decision-making, reduces delays, and promotes a synchronized workflow among team members.
A synchronized workflow is critical for maintaining project timelines. Efficient communication not only reduces the risk of misunderstandings but also promotes a cohesive team environment. Team members working in sync can make decisions promptly, minimizing delays and ensuring that the project progresses according to the established timelines.

Why is synchronized workflow crucial for decision-making and project timelines?

Lack of synchronization can lead to miscommunication, errors, and project delays, impacting overall project success and team efficiency.
A lack of synchronization introduces the risk of team members working with outdated or conflicting information. Miscommunication in such scenarios can result in errors during project execution, leading to delays. These delays can have a cascading effect on the overall success of the project and the efficiency of the team.

Why does miscommunication lead to errors and project delays?

Miscommunication can result from disparate communication tools, causing confusion and misunderstandings among team members, ultimately affecting project timelines and success.

Conclusion

You should now be able to send messages to your Slack channel using the Slack API in Laravel.