PHP code example of hkwise / laravel-slack-notifier

1. Go to this page and download the library: Download hkwise/laravel-slack-notifier library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hkwise / laravel-slack-notifier example snippets


use HKWise\LaravelSlackNotifier\Facades\SlackNotifier;

// Simple webhook message
SlackNotifier::text('Hello from Laravel!')
    ->send();

// Send to a specific channel using Web API
SlackNotifier::via('api')
    ->to('#general')
    ->text('Hello from Laravel!')
    ->send();

// Send to a user
SlackNotifier::via('api')
    ->to('@username')
    ->text('Hey! Check this out.')
    ->send();

// Send an ephemeral message (only visible to specific user)
SlackNotifier::via('api')
    ->to('#general')
    ->toUser('U1234567890')  // Slack user ID
    ->text('This message is only visible to you!')
    ->asEphemeral()
    ->send();

// Quick ephemeral message
SlackNotifier::quickEphemeralMessage(
    'You have a pending approval request',
    'U1234567890',
    '#approvals'
);

// Ephemeral block message
SlackNotifier::via('api')
    ->to('#team')
    ->toUser('U1234567890')
    ->addHeader('Private Notification')
    ->addSection('This is visible only to you')
    ->asEphemeral()
    ->send();

// Quick simple message
SlackNotifier::quickMessage('Server is up and running!', '#monitoring');

// Quick block message with header
SlackNotifier::quickBlockMessage(
    'Deployment Complete',
    'Your application has been successfully deployed to production.',
    '#deployments'
);

use HKWise\LaravelSlackNotifier\Facades\SlackNotifier;

SlackNotifier::via('api')
    ->to('#general')
    ->addHeader('📊 Daily Report')
    ->addDivider()
    ->addSection('*Sales Overview*')
    ->addSection('Total Sales: $12,450\nNew Customers: 23\nOrders: 145')
    ->addDivider()
    ->addContext([
        [
            'type' => 'mrkdwn',
            'text' => 'Generated on: ' . now()->format('M d, Y')
        ]
    ])
    ->send();

SlackNotifier::blocks([
    [
        'type' => 'header',
        'text' => [
            'type' => 'plain_text',
            'text' => '🚨 System Alert'
        ]
    ],
    [
        'type' => 'section',
        'text' => [
            'type' => 'mrkdwn',
            'text' => '*High CPU Usage Detected*\nServer: web-01\nUsage: 95%'
        ]
    ],
    [
        'type' => 'section',
        'fields' => [
            [
                'type' => 'mrkdwn',
                'text' => '*Server:*\nweb-01'
            ],
            [
                'type' => 'mrkdwn',
                'text' => '*CPU:*\n95%'
            ]
        ]
    ]
])->send();

SlackNotifier::username('Custom Bot')
    ->iconEmoji(':fire:')
    ->text('Message with custom appearance')
    ->send();

try {
    // Your code here
} catch (\Exception $e) {
    SlackNotifier::via('api')
        ->to('#errors')
        ->username('Error Bot')
        ->iconEmoji(':warning:')
        ->addHeader('⚠️ Application Error')
        ->addDivider()
        ->addSection("*Error:* {$e->getMessage()}")
        ->addSection("*File:* {$e->getFile()}:{$e->getLine()}")
        ->addDivider()
        ->addContext([
            [
                'type' => 'mrkdwn',
                'text' => 'Environment: ' . app()->environment()
            ],
            [
                'type' => 'mrkdwn',
                'text' => 'Time: ' . now()->toDateTimeString()
            ]
        ])
        ->send();
}

namespace App\Http\Controllers;

use HKWise\LaravelSlackNotifier\Facades\SlackNotifier;

class OrderController extends Controller
{
    public function store(Request $request)
    {
        $order = Order::create($request->all());

        // Notify team about new order
        SlackNotifier::via('api')
            ->to('#orders')
            ->addHeader('🛍️ New Order Received')
            ->addSection("*Order ID:* #{$order->id}")
            ->addSection("*Customer:* {$order->customer_name}")
            ->addSection("*Total:* \${$order->total}")
            ->send();

        return response()->json($order);
    }
}

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use HKWise\LaravelSlackNotifier\Facades\SlackNotifier;

class NotifySlack implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        SlackNotifier::quickMessage('Background job completed!', '#notifications');
    }
}

->addHeader('My Header')

->addSection('*Bold text* and _italic text_')
->addSection('Plain text', 'plain_text')

->addDivider()

->addContext([
    ['type' => 'mrkdwn', 'text' => 'Context info'],
    ['type' => 'mrkdwn', 'text' => 'More context']
])

->blocks([
    [
        'type' => 'section',
        'text' => [
            'type' => 'mrkdwn',
            'text' => 'Custom section'
        ],
        'accessory' => [
            'type' => 'button',
            'text' => [
                'type' => 'plain_text',
                'text' => 'Click Me'
            ],
            'url' => 'https://example.com'
        ]
    ]
])

try {
    SlackNotifier::quickMessage('Hello!');
} catch (\Exception $e) {
    Log::error('Slack notification failed: ' . $e->getMessage());
}

return [
    'default_method' => 'webhook',  // or 'api'
    'webhook_url' => env('SLACK_WEBHOOK_URL'),
    'api' => [
        'token' => env('SLACK_BOT_TOKEN'),
        'default_channel' => env('SLACK_DEFAULT_CHANNEL', '#general'),
    ],
    'timeout' => 10,  // HTTP request timeout in seconds
    'enabled' => true,  // Enable/disable globally
    'defaults' => [
        'username' => 'Laravel Bot',
        'icon_emoji' => ':robot_face:',
    ],
];
bash
php artisan vendor:publish --tag=slack-notifier-config