PHP code example of mortogo321 / laravel-notify

1. Go to this page and download the library: Download mortogo321/laravel-notify 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/ */

    

mortogo321 / laravel-notify example snippets


use Mortogo321\LaravelNotify\Facades\Notify;

// Send a simple notification
Notify::send('Hello, this is a test notification!');

// Send to Slack
Notify::provider('slack')->send('Deployment completed successfully!');

// Send to Discord
Notify::provider('discord')->send('New user registered!');

// Send to Telegram
Notify::provider('telegram')->send('Server CPU usage is high!');

// Send to LINE Notify
Notify::provider('line')->send('Daily report is ready.');

// Send to Email
Notify::provider('email')->send('Monthly report is ready.');

$result = Notify::sendToMultiple(
    ['slack', 'discord', 'telegram', 'line'],
    'Critical: Database backup failed!'
);

// Returns an array with results from each provider
// [
//     'slack' => ['success' => true, ...],
//     'discord' => ['success' => true, ...],
//     'telegram' => ['success' => false, 'error' => '...'],
//     'line' => ['success' => true, ...],
// ]

// Check if provider exists
if (Notify::hasProvider('slack')) {
    Notify::provider('slack')->send('Hello!');
}

// Get all registered providers
$providers = Notify::getProviders(); // ['slack', 'discord', 'telegram', 'line', 'email']

// Get/set default provider
$default = Notify::getDefaultProvider(); // 'slack'
Notify::setDefaultProvider('discord');

// Get configuration
$config = Notify::getConfig(); // All config
$default = Notify::getConfig('default'); // 'slack'

$slack = Notify::provider('slack');

// Get configured settings
$channel = $slack->getChannel();           // '#general'
$username = $slack->getUsername();         // 'Laravel Notify'
$icon = $slack->getIconEmoji();           // ':bell:'
$webhookUrl = $slack->getWebhookUrl();    // Masked URL for security

// List channels (   'next_cursor' => '...'
// ]

// Get channel info by ID
$result = $slack->getChannelInfo('xoxb-your-bot-token', 'C1234567890');
// ['success' => true, 'channel' => [...]]

$discord = Notify::provider('discord');

// Get configured settings
$username = $discord->getUsername();       // 'Laravel Notify'
$avatarUrl = $discord->getAvatarUrl();    // Avatar URL
$webhookUrl = $discord->getWebhookUrl();  // Masked URL for security
$webhookId = $discord->getWebhookId();    // '123456789012345678'

// Get webhook info (channel ID, guild ID, etc.)
$info = $discord->getWebhookInfo();
// [
//     'success' => true,
//     'webhook' => [
//         'id' => '123456789012345678',
//         'name' => 'Laravel Notify',
//         'channel_id' => '987654321098765432',
//         'guild_id' => '111222333444555666',
//         'avatar' => '...'
//     ]
// ]

// Shorthand methods
$channelId = $discord->getChannelId();    // '987654321098765432'
$guildId = $discord->getGuildId();        // '111222333444555666'

// List guild channels (

$telegram = Notify::provider('telegram');

// Get configured settings
$chatId = $telegram->getChatId();         // '-1001234567890'
$botToken = $telegram->getBotToken();     // Masked token for security
$parseMode = $telegram->getParseMode();   // 'HTML'

// Get bot info
$bot = $telegram->getMe();
// [
//     'success' => true,
//     'bot' => [
//         'id' => 123456789,
//         'first_name' => 'My Bot',
//         'username' => 'my_bot',
//         'can_join_groups' => true,
//         ...
//     ]
// ]

// Get chat info
$chat = $telegram->getChat();  // Uses configured chat_id
$chat = $telegram->getChat('-1009876543210');  // Or specify a different chat
// [
//     'success' => true,
//     'chat' => [
//         'id' => -1001234567890,
//         'type' => 'supergroup',
//         'title' => 'My Group',
//         ...
//     ]
// ]

// Get recent updates to find chat IDs
// First, send a message to your bot, then call:
$updates = $telegram->getUpdates();
// [
//     'success' => true,
//     'updates' => [...],
//     'chats' => [
//         ['id' => 123456789, 'type' => 'private', 'first_name' => 'John', 'username' => 'john_doe'],
//         ['id' => -1001234567890, 'type' => 'supergroup', 'title' => 'My Group'],
//     ]
// ]

// Get chat member count
$count = $telegram->getChatMemberCount();
// ['success' => true, 'count' => 150]

// Get chat administrators
$admins = $telegram->getChatAdministrators();
// ['success' => true, 'administrators' => [...]]

// Webhook management
$telegram->setWebhook('https://your-domain.com/webhook', [
    'secret_token' => 'your-secret',
    'allowed_updates' => ['message', 'callback_query'],
]);
$telegram->deleteWebhook();
$webhookInfo = $telegram->getWebhookInfo();

$line = Notify::provider('line');

// Get masked access token
$token = $line->getAccessToken();  // 'test-****67890'

// Check API status
$status = $line->getStatus();
// [
//     'success' => true,
//     'status' => 200,
//     'target_type' => 'USER',
//     'target' => 'John Doe',
// ]

$email = Notify::provider('email');

// Get configured settings
$to = $email->getTo();                    // '[email protected]'
$from = $email->getFrom();                // '[email protected]'
$fromName = $email->getFromName();        // 'Laravel Notify'
$subject = $email->getSubject();          // 'Laravel Notification'
$cc = $email->getCc();                    // CC recipients
$bcc = $email->getBcc();                  // BCC recipients

// Validate email addresses
$isValid = $email->validateEmail('[email protected]');  // true
$isValid = $email->validateEmail('invalid-email');     // false

// Validate multiple emails
$result = $email->validateEmails([
    '[email protected]',
    '[email protected]',
    'invalid-email',
    'bad@',
]);
// [
//     'valid' => ['[email protected]', '[email protected]'],
//     'invalid' => ['invalid-email', 'bad@']
// ]

Notify::provider('slack')->send('Check out this info:', [
    'username' => 'Custom Bot Name',
    'icon_emoji' => ':rocket:',
    'channel' => '#deployments',
    'attachments' => [
        [
            'color' => 'good',
            'title' => 'Deployment Status',
            'text' => 'Successfully deployed to production',
            'fields' => [
                [
                    'title' => 'Environment',
                    'value' => 'Production',
                    'short' => true
                ],
                [
                    'title' => 'Version',
                    'value' => 'v2.1.0',
                    'short' => true
                ]
            ]
        ]
    ]
]);

Notify::provider('slack')->send('', [
    'blocks' => [
        [
            'type' => 'section',
            'text' => [
                'type' => 'mrkdwn',
                'text' => '*Deployment Alert* :rocket:'
            ]
        ],
        [
            'type' => 'divider'
        ],
        [
            'type' => 'section',
            'fields' => [
                [
                    'type' => 'mrkdwn',
                    'text' => '*Status:*\nSuccess'
                ],
                [
                    'type' => 'mrkdwn',
                    'text' => '*Environment:*\nProduction'
                ]
            ]
        ]
    ]
]);

Notify::provider('discord')->send('New deployment!', [
    'username' => 'Deploy Bot',
    'embeds' => [
        [
            'title' => 'Deployment Status',
            'description' => 'Successfully deployed to production',
            'color' => 3066993, // Green color
            'fields' => [
                [
                    'name' => 'Environment',
                    'value' => 'Production',
                    'inline' => true
                ],
                [
                    'name' => 'Version',
                    'value' => 'v2.1.0',
                    'inline' => true
                ]
            ],
            'timestamp' => now()->toIso8601String()
        ]
    ]
]);

Notify::provider('telegram')->send('<b>Alert!</b> Server CPU usage is at 90%', [
    'parse_mode' => 'HTML',
    'disable_notification' => false,
    'reply_markup' => [
        'inline_keyboard' => [
            [
                ['text' => 'View Dashboard', 'url' => 'https://dashboard.example.com']
            ]
        ]
    ]
]);

Notify::provider('line')->send('Deployment completed!', [
    'stickerPackageId' => 446,
    'stickerId' => 1988,
]);

Notify::provider('line')->send('Check this chart:', [
    'imageThumbnail' => 'https://example.com/chart-thumb.png',
    'imageFullsize' => 'https://example.com/chart-full.png',
]);

Notify::provider('email')->send('<h1>Monthly Report</h1><p>Your report is ready!</p>', [
    'to' => '[email protected]',
    'subject' => 'Your Monthly Report',
    'from' => '[email protected]',
    'from_name' => 'Report System',
    'cc' => '[email protected]',
    'bcc' => '[email protected]',
]);



namespace App\Http\Controllers;

use Mortogo321\LaravelNotify\Facades\Notify;
use Mortogo321\LaravelNotify\Exceptions\NotificationException;

class DeploymentController extends Controller
{
    public function deploy()
    {
        // Your deployment logic...

        try {
            Notify::provider('slack')->send('Deployment completed successfully!', [
                'attachments' => [
                    [
                        'color' => 'good',
                        'title' => 'Deployment Status',
                        'text' => 'All services are running normally',
                    ]
                ]
            ]);
        } catch (NotificationException $e) {
            logger()->error('Failed to send notification: ' . $e->getMessage(), [
                'provider' => $e->getProvider(),
                'context' => $e->getContext(),
            ]);
        }

        return response()->json(['status' => 'success']);
    }
}



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 Mortogo321\LaravelNotify\Facades\Notify;

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

    public function handle(): void
    {
        // Process data...

        Notify::send('Data processing completed!');
    }

    public function failed(\Throwable $exception): void
    {
        Notify::provider('slack')->send('Job failed: ' . $exception->getMessage(), [
            'attachments' => [
                [
                    'color' => 'danger',
                    'title' => 'Job Failure',
                    'text' => $exception->getMessage(),
                ]
            ]
        ]);
    }
}

use Mortogo321\LaravelNotify\Providers\AbstractProvider;
use Mortogo321\LaravelNotify\Facades\Notify;

class CustomProvider extends AbstractProvider
{
    protected string $name = 'custom';

    public function __construct(array $config = [])
    {
        parent::__construct($config);
        $this->validateConfig(['api_key']);
    }

    public function send(string $message, array $options = []): array
    {
        if (! $this->isEnabled()) {
            return $this->disabledResponse();
        }

        // Your custom implementation
        return $this->post('https://api.custom-service.com/send', [
            'message' => $message,
            'api_key' => $this->getConfig('api_key'),
        ]);
    }
}

// Register the custom provider
Notify::extend('custom', new CustomProvider([
    'enabled' => true,
    'api_key' => 'your-api-key',
]));

// Use it
Notify::provider('custom')->send('Hello from custom provider!');

if (!function_exists('notify')) {
    function notify(string $message, ?string $provider = null, array $options = [])
    {
        if ($provider) {
            return app('notify')->provider($provider)->send($message, $options);
        }

        return app('notify')->send($message, $options);
    }
}

// Usage
notify('Hello World!');
notify('Hello Slack!', 'slack');
notify('Hello Discord!', 'discord', ['username' => 'Custom Bot']);
bash
php artisan vendor:publish --tag=notify-config